es6.js 4.4 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847438484384943850438514385243853438544385543856438574385843859438604386143862438634386443865438664386743868438694387043871438724387343874438754387643877438784387943880438814388243883438844388543886438874388843889438904389143892438934389443895438964389743898438994390043901439024390343904439054390643907439084390943910439114391243913439144391543916439174391843919439204392143922439234392443925439264392743928439294393043931439324393343934439354393643937439384393943940439414394243943439444394543946439474394843949439504395143952439534395443955439564395743958439594396043961439624396343964439654396643967439684396943970439714397243973439744397543976439774397843979439804398143982439834398443985439864398743988439894399043991439924399343994439954399643997439984399944000440014400244003440044400544006440074400844009440104401144012440134401444015440164401744018440194402044021440224402344024440254402644027440284402944030440314403244033440344403544036440374403844039440404404144042440434404444045440464404744048440494405044051440524405344054440554405644057440584405944060440614406244063440644406544066440674406844069440704407144072440734407444075440764407744078440794408044081440824408344084440854408644087440884408944090440914409244093440944409544096440974409844099441004410144102441034410444105441064410744108441094411044111441124411344114441154411644117441184411944120441214412244123441244412544126441274412844129441304413144132441334413444135441364413744138441394414044141441424414344144441454414644147441484414944150441514415244153441544415544156441574415844159441604416144162441634416444165441664416744168441694417044171441724417344174441754417644177441784417944180441814418244183441844418544186441874418844189441904419144192441934419444195441964419744198441994420044201442024420344204442054420644207442084420944210442114421244213442144421544216442174421844219442204422144222442234422444225442264422744228442294423044231442324423344234442354423644237442384423944240442414424244243442444424544246442474424844249442504425144252442534425444255442564425744258442594426044261442624426344264442654426644267442684426944270442714427244273442744427544276442774427844279442804428144282442834428444285442864428744288442894429044291442924429344294442954429644297442984429944300443014430244303443044430544306443074430844309443104431144312443134431444315443164431744318443194432044321443224432344324443254432644327443284432944330443314433244333443344433544336443374433844339443404434144342443434434444345443464434744348443494435044351443524435344354443554435644357443584435944360443614436244363443644436544366443674436844369443704437144372443734437444375443764437744378443794438044381443824438344384443854438644387443884438944390443914439244393443944439544396443974439844399444004440144402444034440444405444064440744408444094441044411444124441344414444154441644417444184441944420444214442244423444244442544426444274442844429444304443144432444334443444435444364443744438444394444044441444424444344444444454444644447444484444944450444514445244453444544445544456444574445844459444604446144462444634446444465444664446744468444694447044471444724447344474444754447644477444784447944480444814448244483444844448544486444874448844489444904449144492444934449444495444964449744498444994450044501445024450344504445054450644507445084450944510445114451244513445144451544516445174451844519445204452144522445234452444525445264452744528445294453044531445324453344534445354453644537445384453944540445414454244543445444454544546445474454844549445504455144552445534455444555445564455744558445594456044561445624456344564445654456644567445684456944570445714457244573445744457544576445774457844579445804458144582445834458444585445864458744588445894459044591445924459344594445954459644597445984459944600446014460244603446044460544606446074460844609446104461144612446134461444615446164461744618446194462044621446224462344624446254462644627446284462944630446314463244633446344463544636446374463844639446404464144642446434464444645446464464744648446494465044651446524465344654446554465644657446584465944660446614466244663446644466544666446674466844669446704467144672446734467444675446764467744678446794468044681446824468344684446854468644687446884468944690446914469244693446944469544696446974469844699447004470144702447034470444705447064470744708447094471044711447124471344714447154471644717447184471944720447214472244723447244472544726447274472844729447304473144732447334473444735447364473744738447394474044741447424474344744447454474644747447484474944750447514475244753447544475544756447574475844759447604476144762447634476444765447664476744768447694477044771447724477344774447754477644777447784477944780447814478244783447844478544786447874478844789447904479144792447934479444795447964479744798447994480044801448024480344804448054480644807448084480944810448114481244813448144481544816448174481844819448204482144822448234482444825448264482744828448294483044831448324483344834448354483644837448384483944840448414484244843448444484544846448474484844849448504485144852448534485444855448564485744858448594486044861448624486344864448654486644867448684486944870448714487244873448744487544876448774487844879448804488144882448834488444885448864488744888448894489044891448924489344894448954489644897448984489944900449014490244903449044490544906449074490844909449104491144912449134491444915449164491744918449194492044921449224492344924449254492644927449284492944930449314493244933449344493544936449374493844939449404494144942449434494444945449464494744948449494495044951449524495344954449554495644957449584495944960449614496244963449644496544966449674496844969449704497144972449734497444975449764497744978449794498044981449824498344984449854498644987449884498944990449914499244993449944499544996449974499844999450004500145002450034500445005450064500745008450094501045011450124501345014450154501645017450184501945020450214502245023450244502545026450274502845029450304503145032450334503445035450364503745038450394504045041450424504345044450454504645047450484504945050450514505245053450544505545056450574505845059450604506145062450634506445065450664506745068450694507045071450724507345074450754507645077450784507945080450814508245083450844508545086450874508845089450904509145092450934509445095450964509745098450994510045101451024510345104451054510645107451084510945110451114511245113451144511545116451174511845119451204512145122451234512445125451264512745128451294513045131451324513345134451354513645137451384513945140451414514245143451444514545146451474514845149451504515145152451534515445155451564515745158451594516045161451624516345164451654516645167451684516945170451714517245173451744517545176451774517845179451804518145182451834518445185451864518745188451894519045191451924519345194451954519645197451984519945200452014520245203452044520545206452074520845209452104521145212452134521445215452164521745218452194522045221452224522345224452254522645227452284522945230452314523245233452344523545236452374523845239452404524145242452434524445245452464524745248452494525045251452524525345254452554525645257452584525945260452614526245263452644526545266452674526845269452704527145272452734527445275452764527745278452794528045281452824528345284452854528645287452884528945290452914529245293452944529545296452974529845299453004530145302453034530445305453064530745308453094531045311453124531345314453154531645317453184531945320453214532245323453244532545326453274532845329453304533145332453334533445335453364533745338453394534045341453424534345344453454534645347453484534945350453514535245353453544535545356453574535845359453604536145362453634536445365453664536745368453694537045371453724537345374453754537645377453784537945380453814538245383453844538545386453874538845389453904539145392453934539445395453964539745398453994540045401454024540345404454054540645407454084540945410454114541245413454144541545416454174541845419454204542145422454234542445425454264542745428454294543045431454324543345434454354543645437454384543945440454414544245443454444544545446454474544845449454504545145452454534545445455454564545745458454594546045461454624546345464454654546645467454684546945470454714547245473454744547545476454774547845479454804548145482454834548445485454864548745488454894549045491454924549345494454954549645497454984549945500455014550245503455044550545506455074550845509455104551145512455134551445515455164551745518455194552045521455224552345524455254552645527455284552945530455314553245533455344553545536455374553845539455404554145542455434554445545455464554745548455494555045551455524555345554455554555645557455584555945560455614556245563455644556545566455674556845569455704557145572455734557445575455764557745578455794558045581455824558345584455854558645587455884558945590455914559245593455944559545596455974559845599456004560145602456034560445605456064560745608456094561045611456124561345614456154561645617456184561945620456214562245623456244562545626456274562845629456304563145632456334563445635456364563745638456394564045641456424564345644456454564645647456484564945650456514565245653456544565545656456574565845659456604566145662456634566445665456664566745668456694567045671456724567345674456754567645677456784567945680456814568245683456844568545686456874568845689456904569145692456934569445695456964569745698456994570045701457024570345704457054570645707457084570945710457114571245713457144571545716457174571845719457204572145722457234572445725457264572745728457294573045731457324573345734457354573645737457384573945740457414574245743457444574545746457474574845749457504575145752457534575445755457564575745758457594576045761457624576345764457654576645767457684576945770457714577245773457744577545776457774577845779457804578145782457834578445785457864578745788457894579045791457924579345794457954579645797457984579945800458014580245803458044580545806458074580845809458104581145812458134581445815458164581745818458194582045821458224582345824458254582645827458284582945830458314583245833458344583545836458374583845839458404584145842458434584445845458464584745848458494585045851458524585345854458554585645857458584585945860458614586245863458644586545866458674586845869458704587145872458734587445875458764587745878458794588045881458824588345884458854588645887458884588945890458914589245893458944589545896458974589845899459004590145902459034590445905459064590745908459094591045911459124591345914459154591645917459184591945920459214592245923459244592545926459274592845929459304593145932459334593445935459364593745938459394594045941459424594345944459454594645947459484594945950459514595245953459544595545956459574595845959459604596145962459634596445965459664596745968459694597045971459724597345974459754597645977459784597945980459814598245983459844598545986459874598845989459904599145992459934599445995459964599745998459994600046001460024600346004460054600646007460084600946010460114601246013460144601546016460174601846019460204602146022460234602446025460264602746028460294603046031460324603346034460354603646037460384603946040460414604246043460444604546046460474604846049460504605146052460534605446055460564605746058460594606046061460624606346064460654606646067460684606946070460714607246073460744607546076460774607846079460804608146082460834608446085460864608746088460894609046091460924609346094460954609646097460984609946100461014610246103461044610546106461074610846109461104611146112461134611446115461164611746118461194612046121461224612346124461254612646127461284612946130461314613246133461344613546136461374613846139461404614146142461434614446145461464614746148461494615046151461524615346154461554615646157461584615946160461614616246163461644616546166461674616846169461704617146172461734617446175461764617746178461794618046181461824618346184461854618646187461884618946190461914619246193461944619546196461974619846199462004620146202462034620446205462064620746208462094621046211462124621346214462154621646217462184621946220462214622246223462244622546226462274622846229462304623146232462334623446235462364623746238462394624046241462424624346244462454624646247462484624946250462514625246253462544625546256462574625846259462604626146262462634626446265462664626746268462694627046271462724627346274462754627646277462784627946280462814628246283462844628546286462874628846289462904629146292462934629446295462964629746298462994630046301463024630346304463054630646307463084630946310463114631246313463144631546316463174631846319463204632146322463234632446325463264632746328463294633046331463324633346334463354633646337463384633946340463414634246343463444634546346463474634846349463504635146352463534635446355463564635746358463594636046361463624636346364463654636646367463684636946370463714637246373463744637546376463774637846379463804638146382463834638446385463864638746388463894639046391463924639346394463954639646397463984639946400464014640246403464044640546406464074640846409464104641146412464134641446415464164641746418464194642046421464224642346424464254642646427464284642946430464314643246433464344643546436464374643846439464404644146442464434644446445464464644746448464494645046451464524645346454464554645646457464584645946460464614646246463464644646546466464674646846469464704647146472464734647446475464764647746478464794648046481464824648346484464854648646487464884648946490464914649246493464944649546496464974649846499465004650146502465034650446505465064650746508465094651046511465124651346514465154651646517465184651946520465214652246523465244652546526465274652846529465304653146532465334653446535465364653746538465394654046541465424654346544465454654646547465484654946550465514655246553465544655546556465574655846559465604656146562465634656446565465664656746568465694657046571465724657346574465754657646577465784657946580465814658246583465844658546586465874658846589465904659146592465934659446595465964659746598465994660046601466024660346604466054660646607466084660946610466114661246613466144661546616466174661846619466204662146622466234662446625466264662746628466294663046631466324663346634466354663646637466384663946640466414664246643466444664546646466474664846649466504665146652466534665446655466564665746658466594666046661466624666346664466654666646667466684666946670466714667246673466744667546676466774667846679466804668146682466834668446685466864668746688466894669046691466924669346694466954669646697466984669946700467014670246703467044670546706467074670846709467104671146712467134671446715467164671746718467194672046721467224672346724467254672646727467284672946730467314673246733467344673546736467374673846739467404674146742467434674446745467464674746748467494675046751467524675346754467554675646757467584675946760467614676246763467644676546766467674676846769467704677146772467734677446775467764677746778467794678046781467824678346784467854678646787467884678946790467914679246793467944679546796467974679846799468004680146802468034680446805468064680746808468094681046811468124681346814468154681646817468184681946820468214682246823468244682546826468274682846829468304683146832468334683446835468364683746838468394684046841468424684346844468454684646847468484684946850468514685246853468544685546856468574685846859468604686146862468634686446865468664686746868468694687046871468724687346874468754687646877468784687946880468814688246883468844688546886468874688846889468904689146892468934689446895468964689746898468994690046901469024690346904469054690646907469084690946910469114691246913469144691546916469174691846919469204692146922469234692446925469264692746928469294693046931469324693346934469354693646937469384693946940469414694246943469444694546946469474694846949469504695146952469534695446955469564695746958469594696046961469624696346964469654696646967469684696946970469714697246973469744697546976469774697846979469804698146982469834698446985469864698746988469894699046991469924699346994469954699646997469984699947000470014700247003470044700547006470074700847009470104701147012470134701447015470164701747018470194702047021470224702347024470254702647027470284702947030470314703247033470344703547036470374703847039470404704147042470434704447045470464704747048470494705047051470524705347054470554705647057470584705947060470614706247063470644706547066470674706847069470704707147072470734707447075470764707747078470794708047081470824708347084470854708647087470884708947090470914709247093470944709547096470974709847099471004710147102471034710447105471064710747108471094711047111471124711347114471154711647117471184711947120471214712247123471244712547126471274712847129471304713147132471334713447135471364713747138471394714047141471424714347144471454714647147471484714947150471514715247153471544715547156471574715847159471604716147162471634716447165471664716747168471694717047171471724717347174471754717647177471784717947180471814718247183471844718547186471874718847189471904719147192471934719447195471964719747198471994720047201472024720347204472054720647207472084720947210472114721247213472144721547216472174721847219472204722147222472234722447225472264722747228472294723047231472324723347234472354723647237472384723947240472414724247243472444724547246472474724847249472504725147252472534725447255472564725747258472594726047261472624726347264472654726647267472684726947270472714727247273472744727547276472774727847279472804728147282472834728447285472864728747288472894729047291472924729347294472954729647297472984729947300473014730247303473044730547306473074730847309473104731147312473134731447315473164731747318473194732047321473224732347324473254732647327473284732947330473314733247333473344733547336473374733847339473404734147342473434734447345473464734747348473494735047351473524735347354473554735647357473584735947360473614736247363473644736547366473674736847369473704737147372473734737447375473764737747378473794738047381473824738347384473854738647387473884738947390473914739247393473944739547396473974739847399474004740147402474034740447405474064740747408474094741047411474124741347414474154741647417474184741947420474214742247423474244742547426474274742847429474304743147432474334743447435474364743747438474394744047441474424744347444474454744647447474484744947450474514745247453474544745547456474574745847459474604746147462474634746447465474664746747468474694747047471474724747347474474754747647477474784747947480474814748247483474844748547486474874748847489474904749147492474934749447495474964749747498474994750047501475024750347504475054750647507475084750947510475114751247513475144751547516475174751847519475204752147522475234752447525475264752747528475294753047531475324753347534475354753647537475384753947540475414754247543475444754547546475474754847549475504755147552475534755447555475564755747558475594756047561475624756347564475654756647567475684756947570475714757247573475744757547576475774757847579475804758147582475834758447585475864758747588475894759047591475924759347594475954759647597475984759947600476014760247603476044760547606476074760847609476104761147612476134761447615476164761747618476194762047621476224762347624476254762647627476284762947630476314763247633476344763547636476374763847639476404764147642476434764447645476464764747648476494765047651476524765347654476554765647657476584765947660476614766247663476644766547666476674766847669476704767147672476734767447675476764767747678476794768047681476824768347684476854768647687476884768947690476914769247693476944769547696476974769847699477004770147702477034770447705477064770747708477094771047711477124771347714477154771647717477184771947720477214772247723477244772547726477274772847729477304773147732477334773447735477364773747738477394774047741477424774347744477454774647747477484774947750477514775247753477544775547756477574775847759477604776147762477634776447765477664776747768477694777047771477724777347774477754777647777477784777947780477814778247783477844778547786477874778847789477904779147792477934779447795477964779747798477994780047801478024780347804478054780647807478084780947810478114781247813478144781547816478174781847819478204782147822478234782447825478264782747828478294783047831478324783347834478354783647837478384783947840478414784247843478444784547846478474784847849478504785147852478534785447855478564785747858478594786047861478624786347864478654786647867478684786947870478714787247873478744787547876478774787847879478804788147882478834788447885478864788747888478894789047891478924789347894478954789647897478984789947900479014790247903479044790547906479074790847909479104791147912479134791447915479164791747918479194792047921479224792347924479254792647927479284792947930479314793247933479344793547936479374793847939479404794147942479434794447945479464794747948479494795047951479524795347954479554795647957479584795947960479614796247963479644796547966479674796847969479704797147972479734797447975479764797747978479794798047981479824798347984479854798647987479884798947990479914799247993479944799547996479974799847999480004800148002480034800448005480064800748008480094801048011480124801348014480154801648017480184801948020480214802248023480244802548026480274802848029480304803148032480334803448035480364803748038480394804048041480424804348044480454804648047480484804948050480514805248053480544805548056480574805848059480604806148062480634806448065480664806748068480694807048071480724807348074480754807648077480784807948080480814808248083480844808548086480874808848089480904809148092480934809448095480964809748098480994810048101481024810348104481054810648107481084810948110481114811248113481144811548116481174811848119481204812148122481234812448125481264812748128481294813048131481324813348134481354813648137481384813948140481414814248143481444814548146481474814848149481504815148152481534815448155481564815748158481594816048161481624816348164481654816648167481684816948170481714817248173481744817548176481774817848179481804818148182481834818448185481864818748188481894819048191481924819348194481954819648197481984819948200482014820248203482044820548206482074820848209482104821148212482134821448215482164821748218482194822048221482224822348224482254822648227482284822948230482314823248233482344823548236482374823848239482404824148242482434824448245482464824748248482494825048251482524825348254482554825648257482584825948260482614826248263482644826548266482674826848269482704827148272482734827448275482764827748278482794828048281482824828348284482854828648287482884828948290482914829248293482944829548296482974829848299483004830148302483034830448305483064830748308483094831048311483124831348314483154831648317483184831948320483214832248323483244832548326483274832848329483304833148332483334833448335483364833748338483394834048341483424834348344483454834648347483484834948350483514835248353483544835548356483574835848359483604836148362483634836448365483664836748368483694837048371483724837348374483754837648377483784837948380483814838248383483844838548386483874838848389483904839148392483934839448395483964839748398483994840048401484024840348404484054840648407484084840948410484114841248413484144841548416484174841848419484204842148422484234842448425484264842748428484294843048431484324843348434484354843648437484384843948440484414844248443484444844548446484474844848449484504845148452484534845448455484564845748458484594846048461484624846348464484654846648467484684846948470484714847248473484744847548476484774847848479484804848148482484834848448485484864848748488484894849048491484924849348494484954849648497484984849948500485014850248503485044850548506485074850848509485104851148512485134851448515485164851748518485194852048521485224852348524485254852648527485284852948530485314853248533485344853548536485374853848539485404854148542485434854448545485464854748548485494855048551485524855348554485554855648557485584855948560485614856248563485644856548566485674856848569485704857148572485734857448575485764857748578485794858048581485824858348584485854858648587485884858948590485914859248593485944859548596485974859848599486004860148602486034860448605486064860748608486094861048611486124861348614486154861648617486184861948620486214862248623486244862548626486274862848629486304863148632486334863448635486364863748638486394864048641486424864348644486454864648647486484864948650486514865248653486544865548656486574865848659486604866148662486634866448665486664866748668486694867048671486724867348674486754867648677486784867948680486814868248683486844868548686486874868848689486904869148692486934869448695486964869748698486994870048701487024870348704487054870648707487084870948710487114871248713487144871548716487174871848719487204872148722487234872448725487264872748728487294873048731487324873348734487354873648737487384873948740487414874248743487444874548746487474874848749487504875148752487534875448755487564875748758487594876048761487624876348764487654876648767487684876948770487714877248773487744877548776487774877848779487804878148782487834878448785487864878748788487894879048791487924879348794487954879648797487984879948800488014880248803488044880548806488074880848809488104881148812488134881448815488164881748818488194882048821488224882348824488254882648827488284882948830488314883248833488344883548836488374883848839488404884148842488434884448845488464884748848488494885048851488524885348854488554885648857488584885948860488614886248863488644886548866488674886848869488704887148872488734887448875488764887748878488794888048881488824888348884488854888648887488884888948890488914889248893488944889548896488974889848899489004890148902489034890448905489064890748908489094891048911489124891348914489154891648917489184891948920489214892248923489244892548926489274892848929489304893148932489334893448935489364893748938489394894048941489424894348944489454894648947489484894948950489514895248953489544895548956489574895848959489604896148962489634896448965489664896748968489694897048971489724897348974489754897648977489784897948980489814898248983489844898548986489874898848989489904899148992489934899448995489964899748998489994900049001490024900349004490054900649007490084900949010490114901249013490144901549016490174901849019490204902149022490234902449025490264902749028490294903049031490324903349034490354903649037490384903949040490414904249043490444904549046490474904849049490504905149052490534905449055490564905749058490594906049061490624906349064490654906649067490684906949070490714907249073490744907549076490774907849079490804908149082490834908449085490864908749088490894909049091490924909349094490954909649097490984909949100491014910249103491044910549106491074910849109491104911149112491134911449115491164911749118491194912049121491224912349124491254912649127491284912949130491314913249133491344913549136491374913849139491404914149142491434914449145491464914749148491494915049151491524915349154491554915649157491584915949160491614916249163491644916549166491674916849169491704917149172491734917449175491764917749178491794918049181491824918349184491854918649187491884918949190491914919249193491944919549196491974919849199492004920149202492034920449205492064920749208492094921049211492124921349214492154921649217492184921949220492214922249223492244922549226492274922849229492304923149232492334923449235492364923749238492394924049241492424924349244492454924649247492484924949250492514925249253492544925549256492574925849259492604926149262492634926449265492664926749268492694927049271492724927349274492754927649277492784927949280492814928249283492844928549286492874928849289492904929149292492934929449295492964929749298492994930049301493024930349304493054930649307493084930949310493114931249313493144931549316493174931849319493204932149322493234932449325493264932749328493294933049331493324933349334493354933649337493384933949340493414934249343493444934549346493474934849349493504935149352493534935449355493564935749358493594936049361493624936349364493654936649367493684936949370493714937249373493744937549376493774937849379493804938149382493834938449385493864938749388493894939049391493924939349394493954939649397493984939949400494014940249403494044940549406494074940849409494104941149412494134941449415494164941749418494194942049421494224942349424494254942649427494284942949430494314943249433494344943549436494374943849439494404944149442494434944449445494464944749448494494945049451494524945349454494554945649457494584945949460494614946249463494644946549466494674946849469494704947149472494734947449475494764947749478494794948049481494824948349484494854948649487494884948949490494914949249493494944949549496494974949849499495004950149502495034950449505495064950749508495094951049511495124951349514495154951649517495184951949520495214952249523495244952549526495274952849529495304953149532495334953449535495364953749538495394954049541495424954349544495454954649547495484954949550495514955249553495544955549556495574955849559495604956149562495634956449565495664956749568495694957049571495724957349574495754957649577495784957949580495814958249583495844958549586495874958849589495904959149592495934959449595495964959749598495994960049601496024960349604496054960649607496084960949610496114961249613496144961549616496174961849619496204962149622496234962449625496264962749628496294963049631496324963349634496354963649637496384963949640496414964249643496444964549646496474964849649496504965149652496534965449655496564965749658496594966049661496624966349664496654966649667496684966949670496714967249673496744967549676496774967849679496804968149682496834968449685496864968749688496894969049691496924969349694496954969649697496984969949700497014970249703497044970549706497074970849709497104971149712497134971449715497164971749718497194972049721497224972349724497254972649727497284972949730497314973249733497344973549736497374973849739497404974149742497434974449745497464974749748497494975049751497524975349754497554975649757497584975949760497614976249763497644976549766497674976849769497704977149772497734977449775497764977749778497794978049781497824978349784497854978649787497884978949790497914979249793497944979549796497974979849799498004980149802498034980449805498064980749808498094981049811498124981349814498154981649817498184981949820498214982249823498244982549826498274982849829498304983149832498334983449835498364983749838498394984049841498424984349844498454984649847498484984949850498514985249853498544985549856498574985849859498604986149862498634986449865498664986749868498694987049871498724987349874498754987649877498784987949880498814988249883498844988549886498874988849889498904989149892498934989449895498964989749898498994990049901499024990349904499054990649907499084990949910499114991249913499144991549916499174991849919499204992149922499234992449925499264992749928499294993049931499324993349934499354993649937499384993949940499414994249943499444994549946499474994849949499504995149952499534995449955499564995749958499594996049961499624996349964499654996649967499684996949970499714997249973499744997549976499774997849979499804998149982499834998449985499864998749988499894999049991499924999349994499954999649997499984999950000500015000250003500045000550006500075000850009500105001150012500135001450015500165001750018500195002050021500225002350024500255002650027500285002950030500315003250033500345003550036500375003850039500405004150042500435004450045500465004750048500495005050051500525005350054500555005650057500585005950060500615006250063500645006550066500675006850069500705007150072500735007450075500765007750078500795008050081500825008350084500855008650087500885008950090500915009250093500945009550096500975009850099501005010150102501035010450105501065010750108501095011050111501125011350114501155011650117501185011950120501215012250123501245012550126501275012850129501305013150132501335013450135501365013750138501395014050141501425014350144501455014650147501485014950150501515015250153501545015550156501575015850159501605016150162501635016450165501665016750168501695017050171501725017350174501755017650177501785017950180501815018250183501845018550186501875018850189501905019150192501935019450195501965019750198501995020050201502025020350204502055020650207502085020950210502115021250213502145021550216502175021850219502205022150222502235022450225502265022750228502295023050231502325023350234502355023650237502385023950240502415024250243502445024550246502475024850249502505025150252502535025450255502565025750258502595026050261502625026350264502655026650267502685026950270502715027250273502745027550276502775027850279502805028150282502835028450285502865028750288502895029050291502925029350294502955029650297502985029950300503015030250303503045030550306503075030850309503105031150312503135031450315503165031750318503195032050321503225032350324503255032650327503285032950330503315033250333503345033550336503375033850339503405034150342503435034450345503465034750348503495035050351503525035350354503555035650357503585035950360503615036250363503645036550366503675036850369503705037150372503735037450375503765037750378503795038050381503825038350384503855038650387503885038950390503915039250393503945039550396503975039850399504005040150402504035040450405504065040750408504095041050411504125041350414504155041650417504185041950420504215042250423504245042550426504275042850429504305043150432504335043450435504365043750438504395044050441504425044350444504455044650447504485044950450504515045250453504545045550456504575045850459504605046150462504635046450465504665046750468504695047050471504725047350474504755047650477504785047950480504815048250483504845048550486504875048850489504905049150492504935049450495504965049750498504995050050501505025050350504505055050650507505085050950510505115051250513505145051550516505175051850519505205052150522505235052450525505265052750528505295053050531505325053350534505355053650537505385053950540505415054250543505445054550546505475054850549505505055150552505535055450555505565055750558505595056050561505625056350564505655056650567505685056950570505715057250573505745057550576505775057850579505805058150582505835058450585505865058750588505895059050591505925059350594505955059650597505985059950600506015060250603506045060550606506075060850609506105061150612506135061450615506165061750618506195062050621506225062350624506255062650627506285062950630506315063250633506345063550636506375063850639506405064150642506435064450645506465064750648506495065050651506525065350654506555065650657506585065950660506615066250663506645066550666506675066850669506705067150672506735067450675506765067750678506795068050681506825068350684506855068650687506885068950690506915069250693506945069550696506975069850699507005070150702507035070450705507065070750708507095071050711507125071350714507155071650717507185071950720507215072250723507245072550726507275072850729507305073150732507335073450735507365073750738507395074050741507425074350744507455074650747507485074950750507515075250753507545075550756507575075850759507605076150762507635076450765507665076750768507695077050771507725077350774507755077650777507785077950780507815078250783507845078550786507875078850789507905079150792507935079450795507965079750798507995080050801508025080350804508055080650807508085080950810508115081250813508145081550816508175081850819508205082150822508235082450825508265082750828508295083050831508325083350834508355083650837508385083950840508415084250843508445084550846508475084850849508505085150852508535085450855508565085750858508595086050861508625086350864508655086650867508685086950870508715087250873508745087550876508775087850879508805088150882508835088450885508865088750888508895089050891508925089350894508955089650897508985089950900509015090250903509045090550906509075090850909509105091150912509135091450915509165091750918509195092050921509225092350924509255092650927509285092950930509315093250933509345093550936509375093850939509405094150942509435094450945509465094750948509495095050951509525095350954509555095650957509585095950960509615096250963509645096550966509675096850969509705097150972509735097450975509765097750978509795098050981509825098350984509855098650987509885098950990509915099250993509945099550996509975099850999510005100151002510035100451005510065100751008510095101051011510125101351014510155101651017510185101951020510215102251023510245102551026510275102851029510305103151032510335103451035510365103751038510395104051041510425104351044510455104651047510485104951050510515105251053510545105551056510575105851059510605106151062510635106451065510665106751068510695107051071510725107351074510755107651077510785107951080510815108251083510845108551086510875108851089510905109151092510935109451095510965109751098510995110051101511025110351104511055110651107511085110951110511115111251113511145111551116511175111851119511205112151122511235112451125511265112751128511295113051131511325113351134511355113651137511385113951140511415114251143511445114551146511475114851149511505115151152511535115451155511565115751158511595116051161511625116351164511655116651167511685116951170511715117251173511745117551176511775117851179511805118151182511835118451185511865118751188511895119051191511925119351194511955119651197511985119951200512015120251203512045120551206512075120851209512105121151212512135121451215512165121751218512195122051221512225122351224512255122651227512285122951230512315123251233512345123551236512375123851239512405124151242512435124451245512465124751248512495125051251512525125351254512555125651257512585125951260512615126251263512645126551266512675126851269512705127151272512735127451275512765127751278512795128051281512825128351284512855128651287512885128951290512915129251293512945129551296512975129851299513005130151302513035130451305513065130751308513095131051311513125131351314513155131651317513185131951320513215132251323513245132551326513275132851329513305133151332513335133451335513365133751338513395134051341513425134351344513455134651347513485134951350513515135251353513545135551356513575135851359513605136151362513635136451365513665136751368513695137051371513725137351374513755137651377513785137951380513815138251383513845138551386513875138851389513905139151392513935139451395513965139751398513995140051401514025140351404514055140651407514085140951410514115141251413514145141551416514175141851419514205142151422514235142451425514265142751428514295143051431514325143351434514355143651437514385143951440514415144251443514445144551446514475144851449514505145151452514535145451455514565145751458514595146051461514625146351464514655146651467514685146951470514715147251473514745147551476514775147851479514805148151482514835148451485514865148751488514895149051491514925149351494514955149651497514985149951500515015150251503515045150551506515075150851509515105151151512515135151451515515165151751518515195152051521515225152351524515255152651527515285152951530515315153251533515345153551536515375153851539515405154151542515435154451545515465154751548515495155051551515525155351554515555155651557515585155951560515615156251563515645156551566515675156851569515705157151572515735157451575515765157751578515795158051581515825158351584515855158651587515885158951590515915159251593515945159551596515975159851599516005160151602516035160451605516065160751608516095161051611516125161351614516155161651617516185161951620516215162251623516245162551626516275162851629516305163151632516335163451635516365163751638516395164051641516425164351644516455164651647516485164951650516515165251653516545165551656516575165851659516605166151662516635166451665516665166751668516695167051671516725167351674516755167651677516785167951680516815168251683516845168551686516875168851689516905169151692516935169451695516965169751698516995170051701517025170351704517055170651707517085170951710517115171251713517145171551716517175171851719517205172151722517235172451725517265172751728517295173051731517325173351734517355173651737517385173951740517415174251743517445174551746517475174851749517505175151752517535175451755517565175751758517595176051761517625176351764517655176651767517685176951770517715177251773517745177551776517775177851779517805178151782517835178451785517865178751788517895179051791517925179351794517955179651797517985179951800518015180251803518045180551806518075180851809518105181151812518135181451815518165181751818518195182051821518225182351824518255182651827518285182951830518315183251833518345183551836518375183851839518405184151842518435184451845518465184751848518495185051851518525185351854518555185651857518585185951860518615186251863518645186551866518675186851869518705187151872518735187451875518765187751878518795188051881518825188351884518855188651887518885188951890518915189251893518945189551896518975189851899519005190151902519035190451905519065190751908519095191051911519125191351914519155191651917519185191951920519215192251923519245192551926519275192851929519305193151932519335193451935519365193751938519395194051941519425194351944519455194651947519485194951950519515195251953519545195551956519575195851959519605196151962519635196451965519665196751968519695197051971519725197351974519755197651977519785197951980519815198251983519845198551986519875198851989519905199151992519935199451995519965199751998519995200052001520025200352004520055200652007520085200952010520115201252013520145201552016520175201852019520205202152022520235202452025520265202752028520295203052031520325203352034520355203652037520385203952040520415204252043520445204552046520475204852049520505205152052520535205452055520565205752058520595206052061520625206352064520655206652067520685206952070520715207252073520745207552076520775207852079520805208152082520835208452085520865208752088520895209052091520925209352094520955209652097520985209952100521015210252103521045210552106521075210852109521105211152112521135211452115521165211752118521195212052121521225212352124521255212652127521285212952130521315213252133521345213552136521375213852139521405214152142521435214452145521465214752148521495215052151521525215352154521555215652157521585215952160521615216252163521645216552166521675216852169521705217152172521735217452175521765217752178521795218052181521825218352184521855218652187521885218952190521915219252193521945219552196521975219852199522005220152202522035220452205522065220752208522095221052211522125221352214522155221652217522185221952220522215222252223522245222552226522275222852229522305223152232522335223452235522365223752238522395224052241522425224352244522455224652247522485224952250522515225252253522545225552256522575225852259522605226152262522635226452265522665226752268522695227052271522725227352274522755227652277522785227952280522815228252283522845228552286522875228852289522905229152292522935229452295522965229752298522995230052301523025230352304523055230652307523085230952310523115231252313523145231552316523175231852319523205232152322523235232452325523265232752328523295233052331523325233352334523355233652337523385233952340523415234252343523445234552346523475234852349523505235152352523535235452355523565235752358523595236052361523625236352364523655236652367523685236952370523715237252373523745237552376523775237852379523805238152382523835238452385523865238752388523895239052391523925239352394523955239652397523985239952400524015240252403524045240552406524075240852409524105241152412524135241452415524165241752418524195242052421524225242352424524255242652427524285242952430524315243252433524345243552436524375243852439524405244152442524435244452445524465244752448524495245052451524525245352454524555245652457524585245952460524615246252463524645246552466524675246852469524705247152472524735247452475524765247752478524795248052481524825248352484524855248652487524885248952490524915249252493524945249552496524975249852499525005250152502525035250452505525065250752508525095251052511525125251352514525155251652517525185251952520525215252252523525245252552526525275252852529525305253152532525335253452535525365253752538525395254052541525425254352544525455254652547525485254952550525515255252553525545255552556525575255852559525605256152562525635256452565525665256752568525695257052571525725257352574525755257652577525785257952580525815258252583525845258552586525875258852589525905259152592525935259452595525965259752598525995260052601526025260352604526055260652607526085260952610526115261252613526145261552616526175261852619526205262152622526235262452625526265262752628526295263052631526325263352634526355263652637526385263952640526415264252643526445264552646526475264852649526505265152652526535265452655526565265752658526595266052661526625266352664526655266652667526685266952670526715267252673526745267552676526775267852679526805268152682526835268452685526865268752688526895269052691526925269352694526955269652697526985269952700527015270252703527045270552706527075270852709527105271152712527135271452715527165271752718527195272052721527225272352724527255272652727527285272952730527315273252733527345273552736527375273852739527405274152742527435274452745527465274752748527495275052751527525275352754527555275652757527585275952760527615276252763527645276552766527675276852769527705277152772527735277452775527765277752778527795278052781527825278352784527855278652787527885278952790527915279252793527945279552796527975279852799528005280152802528035280452805528065280752808528095281052811528125281352814528155281652817528185281952820528215282252823528245282552826528275282852829528305283152832528335283452835528365283752838528395284052841528425284352844528455284652847528485284952850528515285252853528545285552856528575285852859528605286152862528635286452865528665286752868528695287052871528725287352874528755287652877528785287952880528815288252883528845288552886528875288852889528905289152892528935289452895528965289752898528995290052901529025290352904529055290652907529085290952910529115291252913529145291552916529175291852919529205292152922529235292452925529265292752928529295293052931529325293352934529355293652937529385293952940529415294252943529445294552946529475294852949529505295152952529535295452955529565295752958529595296052961529625296352964529655296652967529685296952970529715297252973529745297552976529775297852979529805298152982529835298452985529865298752988529895299052991529925299352994529955299652997529985299953000530015300253003530045300553006530075300853009530105301153012530135301453015530165301753018530195302053021530225302353024530255302653027530285302953030530315303253033530345303553036530375303853039530405304153042530435304453045530465304753048530495305053051530525305353054530555305653057530585305953060530615306253063530645306553066530675306853069530705307153072530735307453075530765307753078530795308053081530825308353084530855308653087530885308953090530915309253093530945309553096530975309853099531005310153102531035310453105531065310753108531095311053111531125311353114531155311653117531185311953120531215312253123531245312553126531275312853129531305313153132531335313453135531365313753138531395314053141531425314353144531455314653147531485314953150531515315253153531545315553156531575315853159531605316153162531635316453165531665316753168531695317053171531725317353174531755317653177531785317953180531815318253183531845318553186531875318853189531905319153192531935319453195531965319753198531995320053201532025320353204532055320653207532085320953210532115321253213532145321553216532175321853219532205322153222532235322453225532265322753228532295323053231532325323353234532355323653237532385323953240532415324253243532445324553246532475324853249532505325153252532535325453255532565325753258532595326053261532625326353264532655326653267532685326953270532715327253273532745327553276532775327853279532805328153282532835328453285532865328753288532895329053291532925329353294532955329653297532985329953300533015330253303533045330553306533075330853309533105331153312533135331453315533165331753318533195332053321533225332353324533255332653327533285332953330533315333253333533345333553336533375333853339533405334153342533435334453345533465334753348533495335053351533525335353354533555335653357533585335953360533615336253363533645336553366533675336853369533705337153372533735337453375533765337753378533795338053381533825338353384533855338653387533885338953390533915339253393533945339553396533975339853399534005340153402534035340453405534065340753408534095341053411534125341353414534155341653417534185341953420534215342253423534245342553426534275342853429534305343153432534335343453435534365343753438534395344053441534425344353444534455344653447534485344953450534515345253453534545345553456534575345853459534605346153462534635346453465534665346753468534695347053471534725347353474534755347653477534785347953480534815348253483534845348553486534875348853489534905349153492534935349453495534965349753498534995350053501535025350353504535055350653507535085350953510535115351253513535145351553516535175351853519535205352153522535235352453525535265352753528535295353053531535325353353534535355353653537535385353953540535415354253543535445354553546535475354853549535505355153552535535355453555535565355753558535595356053561535625356353564535655356653567535685356953570535715357253573535745357553576535775357853579535805358153582535835358453585535865358753588535895359053591535925359353594535955359653597535985359953600536015360253603536045360553606536075360853609536105361153612536135361453615536165361753618536195362053621536225362353624536255362653627536285362953630536315363253633536345363553636536375363853639536405364153642536435364453645536465364753648536495365053651536525365353654536555365653657536585365953660536615366253663536645366553666536675366853669536705367153672536735367453675536765367753678536795368053681536825368353684536855368653687536885368953690536915369253693536945369553696536975369853699537005370153702537035370453705537065370753708537095371053711537125371353714537155371653717537185371953720537215372253723537245372553726537275372853729537305373153732537335373453735537365373753738537395374053741537425374353744537455374653747537485374953750537515375253753537545375553756537575375853759537605376153762537635376453765537665376753768537695377053771537725377353774537755377653777537785377953780537815378253783537845378553786537875378853789537905379153792537935379453795537965379753798537995380053801538025380353804538055380653807538085380953810538115381253813538145381553816538175381853819538205382153822538235382453825538265382753828538295383053831538325383353834538355383653837538385383953840538415384253843538445384553846538475384853849538505385153852538535385453855538565385753858538595386053861538625386353864538655386653867538685386953870538715387253873538745387553876538775387853879538805388153882538835388453885538865388753888538895389053891538925389353894538955389653897538985389953900539015390253903539045390553906539075390853909539105391153912539135391453915539165391753918539195392053921539225392353924539255392653927539285392953930539315393253933539345393553936539375393853939539405394153942539435394453945539465394753948539495395053951539525395353954539555395653957539585395953960539615396253963539645396553966539675396853969539705397153972539735397453975539765397753978539795398053981539825398353984539855398653987539885398953990539915399253993539945399553996539975399853999540005400154002540035400454005540065400754008540095401054011540125401354014540155401654017540185401954020540215402254023540245402554026540275402854029540305403154032540335403454035540365403754038540395404054041540425404354044540455404654047540485404954050540515405254053540545405554056540575405854059540605406154062540635406454065540665406754068540695407054071540725407354074540755407654077540785407954080540815408254083540845408554086540875408854089540905409154092540935409454095540965409754098540995410054101541025410354104541055410654107541085410954110541115411254113541145411554116541175411854119541205412154122541235412454125541265412754128541295413054131541325413354134541355413654137541385413954140541415414254143541445414554146541475414854149541505415154152541535415454155541565415754158541595416054161541625416354164541655416654167541685416954170541715417254173541745417554176541775417854179541805418154182541835418454185541865418754188541895419054191541925419354194541955419654197541985419954200542015420254203542045420554206542075420854209542105421154212542135421454215542165421754218542195422054221542225422354224542255422654227542285422954230542315423254233542345423554236542375423854239542405424154242542435424454245542465424754248542495425054251542525425354254542555425654257542585425954260542615426254263542645426554266542675426854269542705427154272542735427454275542765427754278542795428054281542825428354284542855428654287542885428954290542915429254293542945429554296542975429854299543005430154302543035430454305543065430754308543095431054311543125431354314543155431654317543185431954320543215432254323543245432554326543275432854329543305433154332543335433454335543365433754338543395434054341543425434354344543455434654347543485434954350543515435254353543545435554356543575435854359543605436154362543635436454365543665436754368543695437054371543725437354374543755437654377543785437954380543815438254383543845438554386543875438854389543905439154392543935439454395543965439754398543995440054401544025440354404544055440654407544085440954410544115441254413544145441554416544175441854419544205442154422544235442454425544265442754428544295443054431544325443354434544355443654437544385443954440544415444254443544445444554446544475444854449544505445154452544535445454455544565445754458544595446054461544625446354464544655446654467544685446954470544715447254473544745447554476544775447854479544805448154482544835448454485544865448754488544895449054491544925449354494544955449654497544985449954500545015450254503545045450554506545075450854509545105451154512545135451454515545165451754518545195452054521545225452354524545255452654527545285452954530545315453254533545345453554536545375453854539545405454154542545435454454545545465454754548545495455054551545525455354554545555455654557545585455954560545615456254563545645456554566545675456854569545705457154572545735457454575545765457754578545795458054581545825458354584545855458654587545885458954590545915459254593545945459554596545975459854599546005460154602546035460454605546065460754608546095461054611546125461354614546155461654617546185461954620546215462254623546245462554626546275462854629546305463154632546335463454635546365463754638546395464054641546425464354644546455464654647546485464954650546515465254653546545465554656546575465854659546605466154662546635466454665546665466754668546695467054671546725467354674546755467654677546785467954680546815468254683546845468554686546875468854689546905469154692546935469454695546965469754698546995470054701547025470354704547055470654707547085470954710547115471254713547145471554716547175471854719547205472154722547235472454725547265472754728547295473054731547325473354734547355473654737547385473954740547415474254743547445474554746547475474854749547505475154752547535475454755547565475754758547595476054761547625476354764547655476654767547685476954770547715477254773547745477554776547775477854779547805478154782547835478454785547865478754788547895479054791547925479354794547955479654797547985479954800548015480254803548045480554806548075480854809548105481154812548135481454815548165481754818548195482054821548225482354824548255482654827548285482954830548315483254833548345483554836548375483854839548405484154842548435484454845548465484754848548495485054851548525485354854548555485654857548585485954860548615486254863548645486554866548675486854869548705487154872548735487454875548765487754878548795488054881548825488354884548855488654887548885488954890548915489254893548945489554896548975489854899549005490154902549035490454905549065490754908549095491054911549125491354914549155491654917549185491954920549215492254923549245492554926549275492854929549305493154932549335493454935549365493754938549395494054941549425494354944549455494654947549485494954950549515495254953549545495554956549575495854959549605496154962549635496454965549665496754968549695497054971549725497354974549755497654977549785497954980549815498254983549845498554986549875498854989549905499154992549935499454995549965499754998549995500055001550025500355004550055500655007550085500955010550115501255013550145501555016550175501855019550205502155022550235502455025550265502755028550295503055031550325503355034550355503655037550385503955040550415504255043550445504555046550475504855049550505505155052550535505455055550565505755058550595506055061550625506355064550655506655067550685506955070550715507255073550745507555076550775507855079550805508155082550835508455085550865508755088550895509055091550925509355094550955509655097550985509955100551015510255103551045510555106551075510855109551105511155112551135511455115551165511755118551195512055121551225512355124551255512655127551285512955130551315513255133551345513555136551375513855139551405514155142551435514455145551465514755148551495515055151551525515355154551555515655157551585515955160551615516255163551645516555166551675516855169551705517155172551735517455175551765517755178551795518055181551825518355184551855518655187551885518955190551915519255193551945519555196551975519855199552005520155202552035520455205552065520755208552095521055211552125521355214552155521655217552185521955220552215522255223552245522555226552275522855229552305523155232552335523455235552365523755238552395524055241552425524355244552455524655247552485524955250552515525255253552545525555256552575525855259552605526155262552635526455265552665526755268552695527055271552725527355274552755527655277552785527955280552815528255283552845528555286552875528855289552905529155292552935529455295552965529755298552995530055301553025530355304553055530655307553085530955310553115531255313553145531555316553175531855319553205532155322553235532455325553265532755328553295533055331553325533355334553355533655337553385533955340553415534255343553445534555346553475534855349553505535155352553535535455355553565535755358553595536055361553625536355364553655536655367553685536955370553715537255373553745537555376553775537855379553805538155382553835538455385553865538755388553895539055391553925539355394553955539655397553985539955400554015540255403554045540555406554075540855409554105541155412554135541455415554165541755418554195542055421554225542355424554255542655427554285542955430554315543255433554345543555436554375543855439554405544155442554435544455445554465544755448554495545055451554525545355454554555545655457554585545955460554615546255463554645546555466554675546855469554705547155472554735547455475554765547755478554795548055481554825548355484554855548655487554885548955490554915549255493554945549555496554975549855499555005550155502555035550455505555065550755508555095551055511555125551355514555155551655517555185551955520555215552255523555245552555526555275552855529555305553155532555335553455535555365553755538555395554055541555425554355544555455554655547555485554955550555515555255553555545555555556555575555855559555605556155562555635556455565555665556755568555695557055571555725557355574555755557655577555785557955580555815558255583555845558555586555875558855589555905559155592555935559455595555965559755598555995560055601556025560355604556055560655607556085560955610556115561255613556145561555616556175561855619556205562155622556235562455625556265562755628556295563055631556325563355634556355563655637556385563955640556415564255643556445564555646556475564855649556505565155652556535565455655556565565755658556595566055661556625566355664556655566655667556685566955670556715567255673556745567555676556775567855679556805568155682556835568455685556865568755688556895569055691556925569355694556955569655697556985569955700557015570255703557045570555706557075570855709557105571155712557135571455715557165571755718557195572055721557225572355724557255572655727557285572955730557315573255733557345573555736557375573855739557405574155742557435574455745557465574755748557495575055751557525575355754557555575655757557585575955760557615576255763557645576555766557675576855769557705577155772557735577455775557765577755778557795578055781557825578355784557855578655787557885578955790557915579255793557945579555796557975579855799558005580155802558035580455805558065580755808558095581055811558125581355814558155581655817558185581955820558215582255823558245582555826558275582855829558305583155832558335583455835558365583755838558395584055841558425584355844558455584655847558485584955850558515585255853558545585555856558575585855859558605586155862558635586455865558665586755868558695587055871558725587355874558755587655877558785587955880558815588255883558845588555886558875588855889558905589155892558935589455895558965589755898558995590055901559025590355904559055590655907559085590955910559115591255913559145591555916559175591855919559205592155922559235592455925559265592755928559295593055931559325593355934559355593655937559385593955940559415594255943559445594555946559475594855949559505595155952559535595455955559565595755958559595596055961559625596355964559655596655967559685596955970559715597255973559745597555976559775597855979559805598155982559835598455985559865598755988559895599055991559925599355994559955599655997559985599956000560015600256003560045600556006560075600856009560105601156012560135601456015560165601756018560195602056021560225602356024560255602656027560285602956030560315603256033560345603556036560375603856039560405604156042560435604456045560465604756048560495605056051560525605356054560555605656057560585605956060560615606256063560645606556066560675606856069560705607156072560735607456075560765607756078560795608056081560825608356084560855608656087560885608956090560915609256093560945609556096560975609856099561005610156102561035610456105561065610756108561095611056111561125611356114561155611656117561185611956120561215612256123561245612556126561275612856129561305613156132561335613456135561365613756138561395614056141561425614356144561455614656147561485614956150561515615256153561545615556156561575615856159561605616156162561635616456165561665616756168561695617056171561725617356174561755617656177561785617956180561815618256183561845618556186561875618856189561905619156192561935619456195561965619756198561995620056201562025620356204562055620656207562085620956210562115621256213562145621556216562175621856219562205622156222562235622456225562265622756228562295623056231562325623356234562355623656237562385623956240562415624256243562445624556246562475624856249562505625156252562535625456255562565625756258562595626056261562625626356264562655626656267562685626956270562715627256273562745627556276562775627856279562805628156282562835628456285562865628756288562895629056291562925629356294562955629656297562985629956300563015630256303563045630556306563075630856309563105631156312563135631456315563165631756318563195632056321563225632356324563255632656327563285632956330563315633256333563345633556336563375633856339563405634156342563435634456345563465634756348563495635056351563525635356354563555635656357563585635956360563615636256363563645636556366563675636856369563705637156372563735637456375563765637756378563795638056381563825638356384563855638656387563885638956390563915639256393563945639556396563975639856399564005640156402564035640456405564065640756408564095641056411564125641356414564155641656417564185641956420564215642256423564245642556426564275642856429564305643156432564335643456435564365643756438564395644056441564425644356444564455644656447564485644956450564515645256453564545645556456564575645856459564605646156462564635646456465564665646756468564695647056471564725647356474564755647656477564785647956480564815648256483564845648556486564875648856489564905649156492564935649456495564965649756498564995650056501565025650356504565055650656507565085650956510565115651256513565145651556516565175651856519565205652156522565235652456525565265652756528565295653056531565325653356534565355653656537565385653956540565415654256543565445654556546565475654856549565505655156552565535655456555565565655756558565595656056561565625656356564565655656656567565685656956570565715657256573565745657556576565775657856579565805658156582565835658456585565865658756588565895659056591565925659356594565955659656597565985659956600566015660256603566045660556606566075660856609566105661156612566135661456615566165661756618566195662056621566225662356624566255662656627566285662956630566315663256633566345663556636566375663856639566405664156642566435664456645566465664756648566495665056651566525665356654566555665656657566585665956660566615666256663566645666556666566675666856669566705667156672566735667456675566765667756678566795668056681566825668356684566855668656687566885668956690566915669256693566945669556696566975669856699567005670156702567035670456705567065670756708567095671056711567125671356714567155671656717567185671956720567215672256723567245672556726567275672856729567305673156732567335673456735567365673756738567395674056741567425674356744567455674656747567485674956750567515675256753567545675556756567575675856759567605676156762567635676456765567665676756768567695677056771567725677356774567755677656777567785677956780567815678256783567845678556786567875678856789567905679156792567935679456795567965679756798567995680056801568025680356804568055680656807568085680956810568115681256813568145681556816568175681856819568205682156822568235682456825568265682756828568295683056831568325683356834568355683656837568385683956840568415684256843568445684556846568475684856849568505685156852568535685456855568565685756858568595686056861568625686356864568655686656867568685686956870568715687256873568745687556876568775687856879568805688156882568835688456885568865688756888568895689056891568925689356894568955689656897568985689956900569015690256903569045690556906569075690856909569105691156912569135691456915569165691756918569195692056921569225692356924569255692656927569285692956930569315693256933569345693556936569375693856939569405694156942569435694456945569465694756948569495695056951569525695356954569555695656957569585695956960569615696256963569645696556966569675696856969569705697156972569735697456975569765697756978569795698056981569825698356984569855698656987569885698956990569915699256993569945699556996569975699856999570005700157002570035700457005570065700757008570095701057011570125701357014570155701657017570185701957020570215702257023570245702557026570275702857029570305703157032570335703457035570365703757038570395704057041570425704357044570455704657047570485704957050570515705257053570545705557056570575705857059570605706157062570635706457065570665706757068570695707057071570725707357074570755707657077570785707957080570815708257083570845708557086570875708857089570905709157092570935709457095570965709757098570995710057101571025710357104571055710657107571085710957110571115711257113571145711557116571175711857119571205712157122571235712457125571265712757128571295713057131571325713357134571355713657137571385713957140571415714257143571445714557146571475714857149571505715157152571535715457155571565715757158571595716057161571625716357164571655716657167571685716957170571715717257173571745717557176571775717857179571805718157182571835718457185571865718757188571895719057191571925719357194571955719657197571985719957200572015720257203572045720557206572075720857209572105721157212572135721457215572165721757218572195722057221572225722357224572255722657227572285722957230572315723257233572345723557236572375723857239572405724157242572435724457245572465724757248572495725057251572525725357254572555725657257572585725957260572615726257263572645726557266572675726857269572705727157272572735727457275572765727757278572795728057281572825728357284572855728657287572885728957290572915729257293572945729557296572975729857299573005730157302573035730457305573065730757308573095731057311573125731357314573155731657317573185731957320573215732257323573245732557326573275732857329573305733157332573335733457335573365733757338573395734057341573425734357344573455734657347573485734957350573515735257353573545735557356573575735857359573605736157362573635736457365573665736757368573695737057371573725737357374573755737657377573785737957380573815738257383573845738557386573875738857389573905739157392573935739457395573965739757398573995740057401574025740357404574055740657407574085740957410574115741257413574145741557416574175741857419574205742157422574235742457425574265742757428574295743057431574325743357434574355743657437574385743957440574415744257443574445744557446574475744857449574505745157452574535745457455574565745757458574595746057461574625746357464574655746657467574685746957470574715747257473574745747557476574775747857479574805748157482574835748457485574865748757488574895749057491574925749357494574955749657497574985749957500575015750257503575045750557506575075750857509575105751157512575135751457515575165751757518575195752057521575225752357524575255752657527575285752957530575315753257533575345753557536575375753857539575405754157542575435754457545575465754757548575495755057551575525755357554575555755657557575585755957560575615756257563575645756557566575675756857569575705757157572575735757457575575765757757578575795758057581575825758357584575855758657587575885758957590575915759257593575945759557596575975759857599576005760157602576035760457605576065760757608576095761057611576125761357614576155761657617576185761957620576215762257623576245762557626576275762857629576305763157632576335763457635576365763757638576395764057641576425764357644576455764657647576485764957650576515765257653576545765557656576575765857659576605766157662576635766457665576665766757668576695767057671576725767357674576755767657677576785767957680576815768257683576845768557686576875768857689576905769157692576935769457695576965769757698576995770057701577025770357704577055770657707577085770957710577115771257713577145771557716577175771857719577205772157722577235772457725577265772757728577295773057731577325773357734577355773657737577385773957740577415774257743577445774557746577475774857749577505775157752577535775457755577565775757758577595776057761577625776357764577655776657767577685776957770577715777257773577745777557776577775777857779577805778157782577835778457785577865778757788577895779057791577925779357794577955779657797577985779957800578015780257803578045780557806578075780857809578105781157812578135781457815578165781757818578195782057821578225782357824578255782657827578285782957830578315783257833578345783557836578375783857839578405784157842578435784457845578465784757848578495785057851578525785357854578555785657857578585785957860578615786257863578645786557866578675786857869578705787157872578735787457875578765787757878578795788057881578825788357884578855788657887578885788957890578915789257893578945789557896578975789857899579005790157902579035790457905579065790757908579095791057911579125791357914579155791657917579185791957920579215792257923579245792557926579275792857929579305793157932579335793457935579365793757938579395794057941579425794357944579455794657947579485794957950579515795257953579545795557956579575795857959579605796157962579635796457965579665796757968579695797057971579725797357974579755797657977579785797957980579815798257983579845798557986579875798857989579905799157992579935799457995579965799757998579995800058001580025800358004580055800658007580085800958010580115801258013580145801558016580175801858019580205802158022580235802458025580265802758028580295803058031580325803358034580355803658037580385803958040580415804258043580445804558046580475804858049580505805158052580535805458055580565805758058580595806058061580625806358064580655806658067580685806958070580715807258073580745807558076580775807858079580805808158082580835808458085580865808758088580895809058091580925809358094580955809658097580985809958100581015810258103581045810558106581075810858109581105811158112581135811458115581165811758118581195812058121581225812358124581255812658127581285812958130581315813258133581345813558136581375813858139581405814158142581435814458145581465814758148581495815058151581525815358154581555815658157581585815958160581615816258163581645816558166581675816858169581705817158172581735817458175581765817758178581795818058181581825818358184581855818658187581885818958190581915819258193581945819558196581975819858199582005820158202582035820458205582065820758208582095821058211582125821358214582155821658217582185821958220582215822258223582245822558226582275822858229582305823158232582335823458235582365823758238582395824058241582425824358244582455824658247582485824958250582515825258253582545825558256582575825858259582605826158262582635826458265582665826758268582695827058271582725827358274582755827658277582785827958280582815828258283582845828558286582875828858289582905829158292582935829458295582965829758298582995830058301583025830358304583055830658307583085830958310583115831258313583145831558316583175831858319583205832158322583235832458325583265832758328583295833058331583325833358334583355833658337583385833958340583415834258343583445834558346583475834858349583505835158352583535835458355583565835758358583595836058361583625836358364583655836658367583685836958370583715837258373583745837558376583775837858379583805838158382583835838458385583865838758388583895839058391583925839358394583955839658397583985839958400584015840258403584045840558406584075840858409584105841158412584135841458415584165841758418584195842058421584225842358424584255842658427584285842958430584315843258433584345843558436584375843858439584405844158442584435844458445584465844758448584495845058451584525845358454584555845658457584585845958460584615846258463584645846558466584675846858469584705847158472584735847458475584765847758478584795848058481584825848358484584855848658487584885848958490584915849258493584945849558496584975849858499585005850158502585035850458505585065850758508585095851058511585125851358514585155851658517585185851958520585215852258523585245852558526585275852858529585305853158532585335853458535585365853758538585395854058541585425854358544585455854658547585485854958550585515855258553585545855558556585575855858559585605856158562585635856458565585665856758568585695857058571585725857358574585755857658577585785857958580585815858258583585845858558586585875858858589585905859158592585935859458595585965859758598585995860058601586025860358604586055860658607586085860958610586115861258613586145861558616586175861858619586205862158622586235862458625586265862758628586295863058631586325863358634586355863658637586385863958640586415864258643586445864558646586475864858649586505865158652586535865458655586565865758658586595866058661586625866358664586655866658667586685866958670586715867258673586745867558676586775867858679586805868158682586835868458685586865868758688586895869058691586925869358694586955869658697586985869958700587015870258703587045870558706587075870858709587105871158712587135871458715587165871758718587195872058721587225872358724587255872658727587285872958730587315873258733587345873558736587375873858739587405874158742587435874458745587465874758748587495875058751587525875358754587555875658757587585875958760587615876258763587645876558766587675876858769587705877158772587735877458775587765877758778587795878058781587825878358784587855878658787587885878958790587915879258793587945879558796587975879858799588005880158802588035880458805588065880758808588095881058811588125881358814588155881658817588185881958820588215882258823588245882558826588275882858829588305883158832588335883458835588365883758838588395884058841588425884358844588455884658847588485884958850588515885258853588545885558856588575885858859588605886158862588635886458865588665886758868588695887058871588725887358874588755887658877588785887958880588815888258883588845888558886588875888858889588905889158892588935889458895588965889758898588995890058901589025890358904589055890658907589085890958910589115891258913589145891558916589175891858919589205892158922589235892458925589265892758928589295893058931589325893358934589355893658937589385893958940589415894258943589445894558946589475894858949589505895158952589535895458955589565895758958589595896058961589625896358964589655896658967589685896958970589715897258973589745897558976589775897858979589805898158982589835898458985589865898758988589895899058991589925899358994589955899658997589985899959000590015900259003590045900559006590075900859009590105901159012590135901459015590165901759018590195902059021590225902359024590255902659027590285902959030590315903259033590345903559036590375903859039590405904159042590435904459045590465904759048590495905059051590525905359054590555905659057590585905959060590615906259063590645906559066590675906859069590705907159072590735907459075590765907759078590795908059081590825908359084590855908659087590885908959090590915909259093590945909559096590975909859099591005910159102591035910459105591065910759108591095911059111591125911359114591155911659117591185911959120591215912259123591245912559126591275912859129591305913159132591335913459135591365913759138591395914059141591425914359144591455914659147591485914959150591515915259153591545915559156591575915859159591605916159162591635916459165591665916759168591695917059171591725917359174591755917659177591785917959180591815918259183591845918559186591875918859189591905919159192591935919459195591965919759198591995920059201592025920359204592055920659207592085920959210592115921259213592145921559216592175921859219592205922159222592235922459225592265922759228592295923059231592325923359234592355923659237592385923959240592415924259243592445924559246592475924859249592505925159252592535925459255592565925759258592595926059261592625926359264592655926659267592685926959270592715927259273592745927559276592775927859279592805928159282592835928459285592865928759288592895929059291592925929359294592955929659297592985929959300593015930259303593045930559306593075930859309593105931159312593135931459315593165931759318593195932059321593225932359324593255932659327593285932959330593315933259333593345933559336593375933859339593405934159342593435934459345593465934759348593495935059351593525935359354593555935659357593585935959360593615936259363593645936559366593675936859369593705937159372593735937459375593765937759378593795938059381593825938359384593855938659387593885938959390593915939259393593945939559396593975939859399594005940159402594035940459405594065940759408594095941059411594125941359414594155941659417594185941959420594215942259423594245942559426594275942859429594305943159432594335943459435594365943759438594395944059441594425944359444594455944659447594485944959450594515945259453594545945559456594575945859459594605946159462594635946459465594665946759468594695947059471594725947359474594755947659477594785947959480594815948259483594845948559486594875948859489594905949159492594935949459495594965949759498594995950059501595025950359504595055950659507595085950959510595115951259513595145951559516595175951859519595205952159522595235952459525595265952759528595295953059531595325953359534595355953659537595385953959540595415954259543595445954559546595475954859549595505955159552595535955459555595565955759558595595956059561595625956359564595655956659567595685956959570595715957259573595745957559576595775957859579595805958159582595835958459585595865958759588595895959059591595925959359594595955959659597595985959959600596015960259603596045960559606596075960859609596105961159612596135961459615596165961759618596195962059621596225962359624596255962659627596285962959630596315963259633596345963559636596375963859639596405964159642596435964459645596465964759648596495965059651596525965359654596555965659657596585965959660596615966259663596645966559666596675966859669596705967159672596735967459675596765967759678596795968059681596825968359684596855968659687596885968959690596915969259693596945969559696596975969859699597005970159702597035970459705597065970759708597095971059711597125971359714597155971659717597185971959720597215972259723597245972559726597275972859729597305973159732597335973459735597365973759738597395974059741597425974359744597455974659747597485974959750597515975259753597545975559756597575975859759597605976159762597635976459765597665976759768597695977059771597725977359774597755977659777597785977959780597815978259783597845978559786597875978859789597905979159792597935979459795597965979759798597995980059801598025980359804598055980659807598085980959810598115981259813598145981559816598175981859819598205982159822598235982459825598265982759828598295983059831598325983359834598355983659837598385983959840598415984259843598445984559846598475984859849598505985159852598535985459855598565985759858598595986059861598625986359864598655986659867598685986959870598715987259873598745987559876598775987859879598805988159882598835988459885598865988759888598895989059891598925989359894598955989659897598985989959900599015990259903599045990559906599075990859909599105991159912599135991459915599165991759918599195992059921599225992359924599255992659927599285992959930599315993259933599345993559936599375993859939599405994159942599435994459945599465994759948599495995059951599525995359954599555995659957599585995959960599615996259963599645996559966599675996859969599705997159972599735997459975599765997759978599795998059981599825998359984599855998659987599885998959990599915999259993599945999559996599975999859999600006000160002600036000460005600066000760008600096001060011600126001360014600156001660017600186001960020600216002260023600246002560026600276002860029600306003160032600336003460035600366003760038600396004060041600426004360044600456004660047600486004960050600516005260053600546005560056600576005860059600606006160062600636006460065600666006760068600696007060071600726007360074600756007660077600786007960080600816008260083600846008560086600876008860089600906009160092600936009460095600966009760098600996010060101601026010360104601056010660107601086010960110601116011260113601146011560116601176011860119601206012160122601236012460125601266012760128601296013060131601326013360134601356013660137601386013960140601416014260143601446014560146601476014860149601506015160152601536015460155601566015760158601596016060161601626016360164601656016660167601686016960170601716017260173601746017560176601776017860179601806018160182601836018460185601866018760188601896019060191601926019360194601956019660197601986019960200602016020260203602046020560206602076020860209602106021160212602136021460215602166021760218602196022060221602226022360224602256022660227602286022960230602316023260233602346023560236602376023860239602406024160242602436024460245602466024760248602496025060251602526025360254602556025660257602586025960260602616026260263602646026560266602676026860269602706027160272602736027460275602766027760278602796028060281602826028360284602856028660287602886028960290602916029260293602946029560296602976029860299603006030160302603036030460305603066030760308603096031060311603126031360314603156031660317603186031960320603216032260323603246032560326603276032860329603306033160332603336033460335603366033760338603396034060341603426034360344603456034660347603486034960350603516035260353603546035560356603576035860359603606036160362603636036460365603666036760368603696037060371603726037360374603756037660377603786037960380603816038260383603846038560386603876038860389603906039160392603936039460395603966039760398603996040060401604026040360404604056040660407604086040960410604116041260413604146041560416604176041860419604206042160422604236042460425604266042760428604296043060431604326043360434604356043660437604386043960440604416044260443604446044560446604476044860449604506045160452604536045460455604566045760458604596046060461604626046360464604656046660467604686046960470604716047260473604746047560476604776047860479604806048160482604836048460485604866048760488604896049060491604926049360494604956049660497604986049960500605016050260503605046050560506605076050860509605106051160512605136051460515605166051760518605196052060521605226052360524605256052660527605286052960530605316053260533605346053560536605376053860539605406054160542605436054460545605466054760548605496055060551605526055360554605556055660557605586055960560605616056260563605646056560566605676056860569605706057160572605736057460575605766057760578605796058060581605826058360584605856058660587605886058960590605916059260593605946059560596605976059860599606006060160602606036060460605606066060760608606096061060611606126061360614606156061660617606186061960620606216062260623606246062560626606276062860629606306063160632606336063460635606366063760638606396064060641606426064360644606456064660647606486064960650606516065260653606546065560656606576065860659606606066160662606636066460665606666066760668606696067060671606726067360674606756067660677606786067960680606816068260683606846068560686606876068860689606906069160692606936069460695606966069760698606996070060701607026070360704607056070660707607086070960710607116071260713607146071560716607176071860719607206072160722607236072460725607266072760728607296073060731607326073360734607356073660737607386073960740607416074260743607446074560746607476074860749607506075160752607536075460755607566075760758607596076060761607626076360764607656076660767607686076960770607716077260773607746077560776607776077860779607806078160782607836078460785607866078760788607896079060791607926079360794607956079660797607986079960800608016080260803608046080560806608076080860809608106081160812608136081460815608166081760818608196082060821608226082360824608256082660827608286082960830608316083260833608346083560836608376083860839608406084160842608436084460845608466084760848608496085060851608526085360854608556085660857608586085960860608616086260863608646086560866608676086860869608706087160872608736087460875608766087760878608796088060881608826088360884608856088660887608886088960890608916089260893608946089560896608976089860899609006090160902609036090460905609066090760908609096091060911609126091360914609156091660917609186091960920609216092260923609246092560926609276092860929609306093160932609336093460935609366093760938609396094060941609426094360944609456094660947609486094960950609516095260953609546095560956609576095860959609606096160962609636096460965609666096760968609696097060971609726097360974609756097660977609786097960980609816098260983609846098560986609876098860989609906099160992609936099460995609966099760998609996100061001610026100361004610056100661007610086100961010610116101261013610146101561016610176101861019610206102161022610236102461025610266102761028610296103061031610326103361034610356103661037610386103961040610416104261043610446104561046610476104861049610506105161052610536105461055610566105761058610596106061061610626106361064610656106661067610686106961070610716107261073610746107561076610776107861079610806108161082610836108461085610866108761088610896109061091610926109361094610956109661097610986109961100611016110261103611046110561106611076110861109611106111161112611136111461115611166111761118611196112061121611226112361124611256112661127611286112961130611316113261133611346113561136611376113861139611406114161142611436114461145611466114761148611496115061151611526115361154611556115661157611586115961160611616116261163611646116561166611676116861169611706117161172611736117461175611766117761178611796118061181611826118361184611856118661187611886118961190611916119261193611946119561196611976119861199612006120161202612036120461205612066120761208612096121061211612126121361214612156121661217612186121961220612216122261223612246122561226612276122861229612306123161232612336123461235612366123761238612396124061241612426124361244612456124661247612486124961250612516125261253612546125561256612576125861259612606126161262612636126461265612666126761268612696127061271612726127361274612756127661277612786127961280612816128261283612846128561286612876128861289612906129161292612936129461295612966129761298612996130061301613026130361304613056130661307613086130961310613116131261313613146131561316613176131861319613206132161322613236132461325613266132761328613296133061331613326133361334613356133661337613386133961340613416134261343613446134561346613476134861349613506135161352613536135461355613566135761358613596136061361613626136361364613656136661367613686136961370613716137261373613746137561376613776137861379613806138161382613836138461385613866138761388613896139061391613926139361394613956139661397613986139961400614016140261403614046140561406614076140861409614106141161412614136141461415614166141761418614196142061421614226142361424614256142661427614286142961430614316143261433614346143561436614376143861439614406144161442614436144461445614466144761448614496145061451614526145361454614556145661457614586145961460614616146261463614646146561466614676146861469614706147161472614736147461475614766147761478614796148061481614826148361484614856148661487614886148961490614916149261493614946149561496614976149861499615006150161502615036150461505615066150761508615096151061511615126151361514615156151661517615186151961520615216152261523615246152561526615276152861529615306153161532615336153461535615366153761538615396154061541615426154361544615456154661547615486154961550615516155261553615546155561556615576155861559615606156161562615636156461565615666156761568615696157061571615726157361574615756157661577615786157961580615816158261583615846158561586615876158861589615906159161592615936159461595615966159761598615996160061601616026160361604616056160661607616086160961610616116161261613616146161561616616176161861619616206162161622616236162461625616266162761628616296163061631616326163361634616356163661637616386163961640616416164261643616446164561646616476164861649616506165161652616536165461655616566165761658616596166061661616626166361664616656166661667616686166961670616716167261673616746167561676616776167861679616806168161682616836168461685616866168761688616896169061691616926169361694616956169661697616986169961700617016170261703617046170561706617076170861709617106171161712617136171461715617166171761718617196172061721617226172361724617256172661727617286172961730617316173261733617346173561736617376173861739617406174161742617436174461745617466174761748617496175061751617526175361754617556175661757617586175961760617616176261763617646176561766617676176861769617706177161772617736177461775617766177761778617796178061781617826178361784617856178661787617886178961790617916179261793617946179561796617976179861799618006180161802618036180461805618066180761808618096181061811618126181361814618156181661817618186181961820618216182261823618246182561826618276182861829618306183161832618336183461835618366183761838618396184061841618426184361844618456184661847618486184961850618516185261853618546185561856618576185861859618606186161862618636186461865618666186761868618696187061871618726187361874618756187661877618786187961880618816188261883618846188561886618876188861889618906189161892618936189461895618966189761898618996190061901619026190361904619056190661907619086190961910619116191261913619146191561916619176191861919619206192161922619236192461925619266192761928619296193061931619326193361934619356193661937619386193961940619416194261943619446194561946619476194861949619506195161952619536195461955619566195761958619596196061961619626196361964619656196661967619686196961970619716197261973619746197561976619776197861979619806198161982619836198461985619866198761988619896199061991619926199361994619956199661997619986199962000620016200262003620046200562006620076200862009620106201162012620136201462015620166201762018620196202062021620226202362024620256202662027620286202962030620316203262033620346203562036620376203862039620406204162042620436204462045620466204762048620496205062051620526205362054620556205662057620586205962060620616206262063620646206562066620676206862069620706207162072620736207462075620766207762078620796208062081620826208362084620856208662087620886208962090620916209262093620946209562096620976209862099621006210162102621036210462105621066210762108621096211062111621126211362114621156211662117621186211962120621216212262123621246212562126621276212862129621306213162132621336213462135621366213762138621396214062141621426214362144621456214662147621486214962150621516215262153621546215562156621576215862159621606216162162621636216462165621666216762168621696217062171621726217362174621756217662177621786217962180621816218262183621846218562186621876218862189621906219162192621936219462195621966219762198621996220062201622026220362204622056220662207622086220962210622116221262213622146221562216622176221862219622206222162222622236222462225622266222762228622296223062231622326223362234622356223662237622386223962240622416224262243622446224562246622476224862249622506225162252622536225462255622566225762258622596226062261622626226362264622656226662267622686226962270622716227262273622746227562276622776227862279622806228162282622836228462285622866228762288622896229062291622926229362294622956229662297622986229962300623016230262303623046230562306623076230862309623106231162312623136231462315623166231762318623196232062321623226232362324623256232662327623286232962330623316233262333623346233562336623376233862339623406234162342623436234462345623466234762348623496235062351623526235362354623556235662357623586235962360623616236262363623646236562366623676236862369623706237162372623736237462375623766237762378623796238062381623826238362384623856238662387623886238962390623916239262393623946239562396623976239862399624006240162402624036240462405624066240762408624096241062411624126241362414624156241662417624186241962420624216242262423624246242562426624276242862429624306243162432624336243462435624366243762438624396244062441624426244362444624456244662447624486244962450624516245262453624546245562456624576245862459624606246162462624636246462465624666246762468624696247062471624726247362474624756247662477624786247962480624816248262483624846248562486624876248862489624906249162492624936249462495624966249762498624996250062501625026250362504625056250662507625086250962510625116251262513625146251562516625176251862519625206252162522625236252462525625266252762528625296253062531625326253362534625356253662537625386253962540625416254262543625446254562546625476254862549625506255162552625536255462555625566255762558625596256062561625626256362564625656256662567625686256962570625716257262573625746257562576625776257862579625806258162582625836258462585625866258762588625896259062591625926259362594625956259662597625986259962600626016260262603626046260562606626076260862609626106261162612626136261462615626166261762618626196262062621626226262362624626256262662627626286262962630626316263262633626346263562636626376263862639626406264162642626436264462645626466264762648626496265062651626526265362654626556265662657626586265962660626616266262663626646266562666626676266862669626706267162672626736267462675626766267762678626796268062681626826268362684626856268662687626886268962690626916269262693626946269562696626976269862699627006270162702627036270462705627066270762708627096271062711627126271362714627156271662717627186271962720627216272262723627246272562726627276272862729627306273162732627336273462735627366273762738627396274062741627426274362744627456274662747627486274962750627516275262753627546275562756627576275862759627606276162762627636276462765627666276762768627696277062771627726277362774627756277662777627786277962780627816278262783627846278562786627876278862789627906279162792627936279462795627966279762798627996280062801628026280362804628056280662807628086280962810628116281262813628146281562816628176281862819628206282162822628236282462825628266282762828628296283062831628326283362834628356283662837628386283962840628416284262843628446284562846628476284862849628506285162852628536285462855628566285762858628596286062861628626286362864628656286662867628686286962870628716287262873628746287562876628776287862879628806288162882628836288462885628866288762888628896289062891628926289362894628956289662897628986289962900629016290262903629046290562906629076290862909629106291162912629136291462915629166291762918629196292062921629226292362924629256292662927629286292962930629316293262933629346293562936629376293862939629406294162942629436294462945629466294762948629496295062951629526295362954629556295662957629586295962960629616296262963629646296562966629676296862969629706297162972629736297462975629766297762978629796298062981629826298362984629856298662987629886298962990629916299262993629946299562996629976299862999630006300163002630036300463005630066300763008630096301063011630126301363014630156301663017630186301963020630216302263023630246302563026630276302863029630306303163032630336303463035630366303763038630396304063041630426304363044630456304663047630486304963050630516305263053630546305563056630576305863059630606306163062630636306463065630666306763068630696307063071630726307363074630756307663077630786307963080630816308263083630846308563086630876308863089630906309163092630936309463095630966309763098630996310063101631026310363104631056310663107631086310963110631116311263113631146311563116631176311863119631206312163122631236312463125631266312763128631296313063131631326313363134631356313663137631386313963140631416314263143631446314563146631476314863149631506315163152631536315463155631566315763158631596316063161631626316363164631656316663167631686316963170631716317263173631746317563176631776317863179631806318163182631836318463185631866318763188631896319063191631926319363194631956319663197631986319963200632016320263203632046320563206632076320863209632106321163212632136321463215632166321763218632196322063221632226322363224632256322663227632286322963230632316323263233632346323563236632376323863239632406324163242632436324463245632466324763248632496325063251632526325363254632556325663257632586325963260632616326263263632646326563266632676326863269632706327163272632736327463275632766327763278632796328063281632826328363284632856328663287632886328963290632916329263293632946329563296632976329863299633006330163302633036330463305633066330763308633096331063311633126331363314633156331663317633186331963320633216332263323633246332563326633276332863329633306333163332633336333463335633366333763338633396334063341633426334363344633456334663347633486334963350633516335263353633546335563356633576335863359633606336163362633636336463365633666336763368633696337063371633726337363374633756337663377633786337963380633816338263383633846338563386633876338863389633906339163392633936339463395633966339763398633996340063401634026340363404634056340663407634086340963410634116341263413634146341563416634176341863419634206342163422634236342463425634266342763428634296343063431634326343363434634356343663437634386343963440634416344263443634446344563446634476344863449634506345163452634536345463455634566345763458634596346063461634626346363464634656346663467634686346963470634716347263473634746347563476634776347863479634806348163482634836348463485634866348763488634896349063491634926349363494634956349663497634986349963500635016350263503635046350563506635076350863509635106351163512635136351463515635166351763518635196352063521635226352363524635256352663527635286352963530635316353263533635346353563536635376353863539635406354163542635436354463545635466354763548635496355063551635526355363554635556355663557635586355963560635616356263563635646356563566635676356863569635706357163572635736357463575635766357763578635796358063581635826358363584635856358663587635886358963590635916359263593635946359563596635976359863599636006360163602636036360463605636066360763608636096361063611636126361363614636156361663617636186361963620636216362263623636246362563626636276362863629636306363163632636336363463635636366363763638636396364063641636426364363644636456364663647636486364963650636516365263653636546365563656636576365863659636606366163662636636366463665636666366763668636696367063671636726367363674636756367663677636786367963680636816368263683636846368563686636876368863689636906369163692636936369463695636966369763698636996370063701637026370363704637056370663707637086370963710637116371263713637146371563716637176371863719637206372163722637236372463725637266372763728637296373063731637326373363734637356373663737637386373963740637416374263743637446374563746637476374863749637506375163752637536375463755637566375763758637596376063761637626376363764637656376663767637686376963770637716377263773637746377563776637776377863779637806378163782637836378463785637866378763788637896379063791637926379363794637956379663797637986379963800638016380263803638046380563806638076380863809638106381163812638136381463815638166381763818638196382063821638226382363824638256382663827638286382963830638316383263833638346383563836638376383863839638406384163842638436384463845638466384763848638496385063851638526385363854638556385663857638586385963860638616386263863638646386563866638676386863869638706387163872638736387463875638766387763878638796388063881638826388363884638856388663887638886388963890638916389263893638946389563896638976389863899639006390163902639036390463905639066390763908639096391063911639126391363914639156391663917639186391963920639216392263923639246392563926639276392863929639306393163932639336393463935639366393763938639396394063941639426394363944639456394663947639486394963950639516395263953639546395563956639576395863959639606396163962639636396463965639666396763968639696397063971639726397363974639756397663977639786397963980639816398263983639846398563986639876398863989639906399163992639936399463995639966399763998639996400064001640026400364004640056400664007640086400964010640116401264013640146401564016640176401864019640206402164022640236402464025640266402764028640296403064031640326403364034640356403664037640386403964040640416404264043640446404564046640476404864049640506405164052640536405464055640566405764058640596406064061640626406364064640656406664067640686406964070640716407264073640746407564076640776407864079640806408164082640836408464085640866408764088640896409064091640926409364094640956409664097640986409964100641016410264103641046410564106641076410864109641106411164112641136411464115641166411764118641196412064121641226412364124641256412664127641286412964130641316413264133641346413564136641376413864139641406414164142641436414464145641466414764148641496415064151641526415364154641556415664157641586415964160641616416264163641646416564166641676416864169641706417164172641736417464175641766417764178641796418064181641826418364184641856418664187641886418964190641916419264193641946419564196641976419864199642006420164202642036420464205642066420764208642096421064211642126421364214642156421664217642186421964220642216422264223642246422564226642276422864229642306423164232642336423464235642366423764238642396424064241642426424364244642456424664247642486424964250642516425264253642546425564256642576425864259642606426164262642636426464265642666426764268642696427064271642726427364274642756427664277642786427964280642816428264283642846428564286642876428864289642906429164292642936429464295642966429764298642996430064301643026430364304643056430664307643086430964310643116431264313643146431564316643176431864319643206432164322643236432464325643266432764328643296433064331643326433364334643356433664337643386433964340643416434264343643446434564346643476434864349643506435164352643536435464355643566435764358643596436064361643626436364364643656436664367643686436964370643716437264373643746437564376643776437864379643806438164382643836438464385643866438764388643896439064391643926439364394643956439664397643986439964400644016440264403644046440564406644076440864409644106441164412644136441464415644166441764418644196442064421644226442364424644256442664427644286442964430644316443264433644346443564436644376443864439644406444164442644436444464445644466444764448644496445064451644526445364454644556445664457644586445964460644616446264463644646446564466644676446864469644706447164472644736447464475644766447764478644796448064481644826448364484644856448664487644886448964490644916449264493644946449564496644976449864499645006450164502645036450464505645066450764508645096451064511645126451364514645156451664517645186451964520645216452264523645246452564526645276452864529645306453164532645336453464535645366453764538645396454064541645426454364544645456454664547645486454964550645516455264553645546455564556645576455864559645606456164562645636456464565645666456764568645696457064571645726457364574645756457664577645786457964580645816458264583645846458564586645876458864589645906459164592645936459464595645966459764598645996460064601646026460364604646056460664607646086460964610646116461264613646146461564616646176461864619646206462164622646236462464625646266462764628646296463064631646326463364634646356463664637646386463964640646416464264643646446464564646646476464864649646506465164652646536465464655646566465764658646596466064661646626466364664646656466664667646686466964670646716467264673646746467564676646776467864679646806468164682646836468464685646866468764688646896469064691646926469364694646956469664697646986469964700647016470264703647046470564706647076470864709647106471164712647136471464715647166471764718647196472064721647226472364724647256472664727647286472964730647316473264733647346473564736647376473864739647406474164742647436474464745647466474764748647496475064751647526475364754647556475664757647586475964760647616476264763647646476564766647676476864769647706477164772647736477464775647766477764778647796478064781647826478364784647856478664787647886478964790647916479264793647946479564796647976479864799648006480164802648036480464805648066480764808648096481064811648126481364814648156481664817648186481964820648216482264823648246482564826648276482864829648306483164832648336483464835648366483764838648396484064841648426484364844648456484664847648486484964850648516485264853648546485564856648576485864859648606486164862648636486464865648666486764868648696487064871648726487364874648756487664877648786487964880648816488264883648846488564886648876488864889648906489164892648936489464895648966489764898648996490064901649026490364904649056490664907649086490964910649116491264913649146491564916649176491864919649206492164922649236492464925649266492764928649296493064931649326493364934649356493664937649386493964940649416494264943649446494564946649476494864949649506495164952649536495464955649566495764958649596496064961649626496364964649656496664967649686496964970649716497264973649746497564976649776497864979649806498164982649836498464985649866498764988649896499064991649926499364994649956499664997649986499965000650016500265003650046500565006650076500865009650106501165012650136501465015650166501765018650196502065021650226502365024650256502665027650286502965030650316503265033650346503565036650376503865039650406504165042650436504465045650466504765048650496505065051650526505365054650556505665057650586505965060650616506265063650646506565066650676506865069650706507165072650736507465075650766507765078650796508065081650826508365084650856508665087650886508965090650916509265093650946509565096650976509865099651006510165102651036510465105651066510765108651096511065111651126511365114651156511665117651186511965120651216512265123651246512565126651276512865129651306513165132651336513465135651366513765138651396514065141651426514365144651456514665147651486514965150651516515265153651546515565156651576515865159651606516165162651636516465165651666516765168651696517065171651726517365174651756517665177651786517965180651816518265183651846518565186651876518865189651906519165192651936519465195651966519765198651996520065201652026520365204652056520665207652086520965210652116521265213652146521565216652176521865219652206522165222652236522465225652266522765228652296523065231652326523365234652356523665237652386523965240652416524265243652446524565246652476524865249652506525165252652536525465255652566525765258652596526065261652626526365264652656526665267652686526965270652716527265273652746527565276652776527865279652806528165282652836528465285652866528765288652896529065291652926529365294652956529665297652986529965300653016530265303653046530565306653076530865309653106531165312653136531465315653166531765318653196532065321653226532365324653256532665327653286532965330653316533265333653346533565336653376533865339653406534165342653436534465345653466534765348653496535065351653526535365354653556535665357653586535965360653616536265363653646536565366653676536865369653706537165372653736537465375653766537765378653796538065381653826538365384653856538665387653886538965390653916539265393653946539565396653976539865399654006540165402654036540465405654066540765408654096541065411654126541365414654156541665417654186541965420654216542265423654246542565426654276542865429654306543165432654336543465435654366543765438654396544065441654426544365444654456544665447654486544965450654516545265453654546545565456654576545865459654606546165462654636546465465654666546765468654696547065471654726547365474654756547665477654786547965480654816548265483654846548565486654876548865489654906549165492654936549465495654966549765498654996550065501655026550365504655056550665507655086550965510655116551265513655146551565516655176551865519655206552165522655236552465525655266552765528655296553065531655326553365534655356553665537655386553965540655416554265543655446554565546655476554865549655506555165552655536555465555655566555765558655596556065561655626556365564655656556665567655686556965570655716557265573655746557565576655776557865579655806558165582655836558465585655866558765588655896559065591655926559365594655956559665597655986559965600656016560265603656046560565606656076560865609656106561165612656136561465615656166561765618656196562065621656226562365624656256562665627656286562965630656316563265633656346563565636656376563865639656406564165642656436564465645656466564765648656496565065651656526565365654656556565665657656586565965660656616566265663656646566565666656676566865669656706567165672656736567465675656766567765678656796568065681656826568365684656856568665687656886568965690656916569265693656946569565696656976569865699657006570165702657036570465705657066570765708657096571065711657126571365714657156571665717657186571965720657216572265723657246572565726657276572865729657306573165732657336573465735657366573765738657396574065741657426574365744657456574665747657486574965750657516575265753657546575565756657576575865759657606576165762657636576465765657666576765768657696577065771657726577365774657756577665777657786577965780657816578265783657846578565786657876578865789657906579165792657936579465795657966579765798657996580065801658026580365804658056580665807658086580965810658116581265813658146581565816658176581865819658206582165822658236582465825658266582765828658296583065831658326583365834658356583665837658386583965840658416584265843658446584565846658476584865849658506585165852658536585465855658566585765858658596586065861658626586365864658656586665867658686586965870658716587265873658746587565876658776587865879658806588165882658836588465885658866588765888658896589065891658926589365894658956589665897658986589965900659016590265903659046590565906659076590865909659106591165912659136591465915659166591765918659196592065921659226592365924659256592665927659286592965930659316593265933659346593565936659376593865939659406594165942659436594465945659466594765948659496595065951659526595365954659556595665957659586595965960659616596265963659646596565966659676596865969659706597165972659736597465975659766597765978659796598065981659826598365984659856598665987659886598965990659916599265993659946599565996659976599865999660006600166002660036600466005660066600766008660096601066011660126601366014660156601666017660186601966020660216602266023660246602566026660276602866029660306603166032660336603466035660366603766038660396604066041660426604366044660456604666047660486604966050660516605266053660546605566056660576605866059660606606166062660636606466065660666606766068660696607066071660726607366074660756607666077660786607966080660816608266083660846608566086660876608866089660906609166092660936609466095660966609766098660996610066101661026610366104661056610666107661086610966110661116611266113661146611566116661176611866119661206612166122661236612466125661266612766128661296613066131661326613366134661356613666137661386613966140661416614266143661446614566146661476614866149661506615166152661536615466155661566615766158661596616066161661626616366164661656616666167661686616966170661716617266173661746617566176661776617866179661806618166182661836618466185661866618766188661896619066191661926619366194661956619666197661986619966200662016620266203662046620566206662076620866209662106621166212662136621466215662166621766218662196622066221662226622366224662256622666227662286622966230662316623266233662346623566236662376623866239662406624166242662436624466245662466624766248662496625066251662526625366254662556625666257662586625966260662616626266263662646626566266662676626866269662706627166272662736627466275662766627766278662796628066281662826628366284662856628666287662886628966290662916629266293662946629566296662976629866299663006630166302663036630466305663066630766308663096631066311663126631366314663156631666317663186631966320663216632266323663246632566326663276632866329663306633166332663336633466335663366633766338663396634066341663426634366344663456634666347663486634966350663516635266353663546635566356663576635866359663606636166362663636636466365663666636766368663696637066371663726637366374663756637666377663786637966380663816638266383663846638566386663876638866389663906639166392663936639466395663966639766398663996640066401664026640366404664056640666407664086640966410664116641266413664146641566416664176641866419664206642166422664236642466425664266642766428664296643066431664326643366434664356643666437664386643966440664416644266443664446644566446664476644866449664506645166452664536645466455664566645766458664596646066461664626646366464664656646666467664686646966470664716647266473664746647566476664776647866479664806648166482664836648466485664866648766488664896649066491664926649366494664956649666497664986649966500665016650266503665046650566506665076650866509665106651166512665136651466515665166651766518665196652066521665226652366524665256652666527665286652966530665316653266533665346653566536665376653866539665406654166542665436654466545665466654766548665496655066551665526655366554665556655666557665586655966560665616656266563665646656566566665676656866569665706657166572665736657466575665766657766578665796658066581665826658366584665856658666587665886658966590665916659266593665946659566596665976659866599666006660166602666036660466605666066660766608666096661066611666126661366614666156661666617666186661966620666216662266623666246662566626666276662866629666306663166632666336663466635666366663766638666396664066641666426664366644666456664666647666486664966650666516665266653666546665566656666576665866659666606666166662666636666466665666666666766668666696667066671666726667366674666756667666677666786667966680666816668266683666846668566686666876668866689666906669166692666936669466695666966669766698666996670066701667026670366704667056670666707667086670966710667116671266713667146671566716667176671866719667206672166722667236672466725667266672766728667296673066731667326673366734667356673666737667386673966740667416674266743667446674566746667476674866749667506675166752667536675466755667566675766758667596676066761667626676366764667656676666767667686676966770667716677266773667746677566776667776677866779667806678166782667836678466785667866678766788667896679066791667926679366794667956679666797667986679966800668016680266803668046680566806668076680866809668106681166812668136681466815668166681766818668196682066821668226682366824668256682666827668286682966830668316683266833668346683566836668376683866839668406684166842668436684466845668466684766848668496685066851668526685366854668556685666857668586685966860668616686266863668646686566866668676686866869668706687166872668736687466875668766687766878668796688066881668826688366884668856688666887668886688966890668916689266893668946689566896668976689866899669006690166902669036690466905669066690766908669096691066911669126691366914669156691666917669186691966920669216692266923669246692566926669276692866929669306693166932669336693466935669366693766938669396694066941669426694366944669456694666947669486694966950669516695266953669546695566956669576695866959669606696166962669636696466965669666696766968669696697066971669726697366974669756697666977669786697966980669816698266983669846698566986669876698866989669906699166992669936699466995669966699766998669996700067001670026700367004670056700667007670086700967010670116701267013670146701567016670176701867019670206702167022670236702467025670266702767028670296703067031670326703367034670356703667037670386703967040670416704267043670446704567046670476704867049670506705167052670536705467055670566705767058670596706067061670626706367064670656706667067670686706967070670716707267073670746707567076670776707867079670806708167082670836708467085670866708767088670896709067091670926709367094670956709667097670986709967100671016710267103671046710567106671076710867109671106711167112671136711467115671166711767118671196712067121671226712367124671256712667127671286712967130671316713267133671346713567136671376713867139671406714167142671436714467145671466714767148671496715067151671526715367154671556715667157671586715967160671616716267163671646716567166671676716867169671706717167172671736717467175671766717767178671796718067181671826718367184671856718667187671886718967190671916719267193671946719567196671976719867199672006720167202672036720467205672066720767208672096721067211672126721367214672156721667217672186721967220672216722267223672246722567226672276722867229672306723167232672336723467235672366723767238672396724067241672426724367244672456724667247672486724967250672516725267253672546725567256672576725867259672606726167262672636726467265672666726767268672696727067271672726727367274672756727667277672786727967280672816728267283672846728567286672876728867289672906729167292672936729467295672966729767298672996730067301673026730367304673056730667307673086730967310673116731267313673146731567316673176731867319673206732167322673236732467325673266732767328673296733067331673326733367334673356733667337673386733967340673416734267343673446734567346673476734867349673506735167352673536735467355673566735767358673596736067361673626736367364673656736667367673686736967370673716737267373673746737567376673776737867379673806738167382673836738467385673866738767388673896739067391673926739367394673956739667397673986739967400674016740267403674046740567406674076740867409674106741167412674136741467415674166741767418674196742067421674226742367424674256742667427674286742967430674316743267433674346743567436674376743867439674406744167442674436744467445674466744767448674496745067451674526745367454674556745667457674586745967460674616746267463674646746567466674676746867469674706747167472674736747467475674766747767478674796748067481674826748367484674856748667487674886748967490674916749267493674946749567496674976749867499675006750167502675036750467505675066750767508675096751067511675126751367514675156751667517675186751967520675216752267523675246752567526675276752867529675306753167532675336753467535675366753767538675396754067541675426754367544675456754667547675486754967550675516755267553675546755567556675576755867559675606756167562675636756467565675666756767568675696757067571675726757367574675756757667577675786757967580675816758267583675846758567586675876758867589675906759167592675936759467595675966759767598675996760067601676026760367604676056760667607676086760967610676116761267613676146761567616676176761867619676206762167622676236762467625676266762767628676296763067631676326763367634676356763667637676386763967640676416764267643676446764567646676476764867649676506765167652676536765467655676566765767658676596766067661676626766367664676656766667667676686766967670676716767267673676746767567676676776767867679676806768167682676836768467685676866768767688676896769067691676926769367694676956769667697676986769967700677016770267703677046770567706677076770867709677106771167712677136771467715677166771767718677196772067721677226772367724677256772667727677286772967730677316773267733677346773567736677376773867739677406774167742677436774467745677466774767748677496775067751677526775367754677556775667757677586775967760677616776267763677646776567766677676776867769677706777167772677736777467775677766777767778677796778067781677826778367784677856778667787677886778967790677916779267793677946779567796677976779867799678006780167802678036780467805678066780767808678096781067811678126781367814678156781667817678186781967820678216782267823678246782567826678276782867829678306783167832678336783467835678366783767838678396784067841678426784367844678456784667847678486784967850678516785267853678546785567856678576785867859678606786167862678636786467865678666786767868678696787067871678726787367874678756787667877678786787967880678816788267883678846788567886678876788867889678906789167892678936789467895678966789767898678996790067901679026790367904679056790667907679086790967910679116791267913679146791567916679176791867919679206792167922679236792467925679266792767928679296793067931679326793367934679356793667937679386793967940679416794267943679446794567946679476794867949679506795167952679536795467955679566795767958679596796067961679626796367964679656796667967679686796967970679716797267973679746797567976679776797867979679806798167982679836798467985679866798767988679896799067991679926799367994679956799667997679986799968000680016800268003680046800568006680076800868009680106801168012680136801468015680166801768018680196802068021680226802368024680256802668027680286802968030680316803268033680346803568036680376803868039680406804168042680436804468045680466804768048680496805068051680526805368054680556805668057680586805968060680616806268063680646806568066680676806868069680706807168072680736807468075680766807768078680796808068081680826808368084680856808668087680886808968090680916809268093680946809568096680976809868099681006810168102681036810468105681066810768108681096811068111681126811368114681156811668117681186811968120681216812268123681246812568126681276812868129681306813168132681336813468135681366813768138681396814068141681426814368144681456814668147681486814968150681516815268153681546815568156681576815868159681606816168162681636816468165681666816768168681696817068171681726817368174681756817668177681786817968180681816818268183681846818568186681876818868189681906819168192681936819468195681966819768198681996820068201682026820368204682056820668207682086820968210682116821268213682146821568216682176821868219682206822168222682236822468225682266822768228682296823068231682326823368234682356823668237682386823968240682416824268243682446824568246682476824868249682506825168252682536825468255682566825768258682596826068261682626826368264682656826668267682686826968270682716827268273682746827568276682776827868279682806828168282682836828468285682866828768288682896829068291682926829368294682956829668297682986829968300683016830268303683046830568306683076830868309683106831168312683136831468315683166831768318683196832068321683226832368324683256832668327683286832968330683316833268333683346833568336683376833868339683406834168342683436834468345683466834768348683496835068351683526835368354683556835668357683586835968360683616836268363683646836568366683676836868369683706837168372683736837468375683766837768378683796838068381683826838368384683856838668387683886838968390683916839268393683946839568396683976839868399684006840168402684036840468405684066840768408684096841068411684126841368414684156841668417684186841968420684216842268423684246842568426684276842868429684306843168432684336843468435684366843768438684396844068441684426844368444684456844668447684486844968450684516845268453684546845568456684576845868459684606846168462684636846468465684666846768468684696847068471684726847368474684756847668477684786847968480684816848268483684846848568486684876848868489684906849168492684936849468495684966849768498684996850068501685026850368504685056850668507685086850968510685116851268513685146851568516685176851868519685206852168522685236852468525685266852768528685296853068531685326853368534685356853668537685386853968540685416854268543685446854568546685476854868549685506855168552685536855468555685566855768558685596856068561685626856368564685656856668567685686856968570685716857268573685746857568576685776857868579685806858168582685836858468585685866858768588685896859068591685926859368594685956859668597685986859968600686016860268603686046860568606686076860868609686106861168612686136861468615686166861768618686196862068621686226862368624686256862668627686286862968630686316863268633686346863568636686376863868639686406864168642686436864468645686466864768648686496865068651686526865368654686556865668657686586865968660686616866268663686646866568666686676866868669686706867168672686736867468675686766867768678686796868068681686826868368684686856868668687686886868968690686916869268693686946869568696686976869868699687006870168702687036870468705687066870768708687096871068711687126871368714687156871668717687186871968720687216872268723687246872568726687276872868729687306873168732687336873468735687366873768738687396874068741687426874368744687456874668747687486874968750687516875268753687546875568756687576875868759687606876168762687636876468765687666876768768687696877068771687726877368774687756877668777687786877968780687816878268783687846878568786687876878868789687906879168792687936879468795687966879768798687996880068801688026880368804688056880668807688086880968810688116881268813688146881568816688176881868819688206882168822688236882468825688266882768828688296883068831688326883368834688356883668837688386883968840688416884268843688446884568846688476884868849688506885168852688536885468855688566885768858688596886068861688626886368864688656886668867688686886968870688716887268873688746887568876688776887868879688806888168882688836888468885688866888768888688896889068891688926889368894688956889668897688986889968900689016890268903689046890568906689076890868909689106891168912689136891468915689166891768918689196892068921689226892368924689256892668927689286892968930689316893268933689346893568936689376893868939689406894168942689436894468945689466894768948689496895068951689526895368954689556895668957689586895968960689616896268963689646896568966689676896868969689706897168972689736897468975689766897768978689796898068981689826898368984689856898668987689886898968990689916899268993689946899568996689976899868999690006900169002690036900469005690066900769008690096901069011690126901369014690156901669017690186901969020690216902269023690246902569026690276902869029690306903169032690336903469035690366903769038690396904069041690426904369044690456904669047690486904969050690516905269053690546905569056690576905869059690606906169062690636906469065690666906769068690696907069071690726907369074690756907669077690786907969080690816908269083690846908569086690876908869089690906909169092690936909469095690966909769098690996910069101691026910369104691056910669107691086910969110691116911269113691146911569116691176911869119691206912169122691236912469125691266912769128691296913069131691326913369134691356913669137691386913969140691416914269143691446914569146691476914869149691506915169152691536915469155691566915769158691596916069161691626916369164691656916669167691686916969170691716917269173691746917569176691776917869179691806918169182691836918469185691866918769188691896919069191691926919369194691956919669197691986919969200692016920269203692046920569206692076920869209692106921169212692136921469215692166921769218692196922069221692226922369224692256922669227692286922969230692316923269233692346923569236692376923869239692406924169242692436924469245692466924769248692496925069251692526925369254692556925669257692586925969260692616926269263692646926569266692676926869269692706927169272692736927469275692766927769278692796928069281692826928369284692856928669287692886928969290692916929269293692946929569296692976929869299693006930169302693036930469305693066930769308693096931069311693126931369314693156931669317693186931969320693216932269323693246932569326693276932869329693306933169332693336933469335693366933769338693396934069341693426934369344693456934669347693486934969350693516935269353693546935569356693576935869359693606936169362693636936469365693666936769368693696937069371693726937369374693756937669377693786937969380693816938269383693846938569386693876938869389693906939169392693936939469395693966939769398693996940069401694026940369404694056940669407694086940969410694116941269413694146941569416694176941869419694206942169422694236942469425694266942769428694296943069431694326943369434694356943669437694386943969440694416944269443694446944569446694476944869449694506945169452694536945469455694566945769458694596946069461694626946369464694656946669467694686946969470694716947269473694746947569476694776947869479694806948169482694836948469485694866948769488694896949069491694926949369494694956949669497694986949969500695016950269503695046950569506695076950869509695106951169512695136951469515695166951769518695196952069521695226952369524695256952669527695286952969530695316953269533695346953569536695376953869539695406954169542695436954469545695466954769548695496955069551695526955369554695556955669557695586955969560695616956269563695646956569566695676956869569695706957169572695736957469575695766957769578695796958069581695826958369584695856958669587695886958969590695916959269593695946959569596695976959869599696006960169602696036960469605696066960769608696096961069611696126961369614696156961669617696186961969620696216962269623696246962569626696276962869629696306963169632696336963469635696366963769638696396964069641696426964369644696456964669647696486964969650696516965269653696546965569656696576965869659696606966169662696636966469665696666966769668696696967069671696726967369674696756967669677696786967969680696816968269683696846968569686696876968869689696906969169692696936969469695696966969769698696996970069701697026970369704697056970669707697086970969710697116971269713697146971569716697176971869719697206972169722697236972469725697266972769728697296973069731697326973369734697356973669737697386973969740697416974269743697446974569746697476974869749697506975169752697536975469755697566975769758697596976069761697626976369764697656976669767697686976969770697716977269773697746977569776697776977869779697806978169782697836978469785697866978769788697896979069791697926979369794697956979669797697986979969800698016980269803698046980569806698076980869809698106981169812698136981469815698166981769818698196982069821698226982369824698256982669827698286982969830698316983269833698346983569836698376983869839698406984169842698436984469845698466984769848698496985069851698526985369854698556985669857698586985969860698616986269863698646986569866698676986869869698706987169872698736987469875698766987769878698796988069881698826988369884698856988669887698886988969890698916989269893698946989569896698976989869899699006990169902699036990469905699066990769908699096991069911699126991369914699156991669917699186991969920699216992269923699246992569926699276992869929699306993169932699336993469935699366993769938699396994069941699426994369944699456994669947699486994969950699516995269953699546995569956699576995869959699606996169962699636996469965699666996769968699696997069971699726997369974699756997669977699786997969980699816998269983699846998569986699876998869989699906999169992699936999469995699966999769998699997000070001700027000370004700057000670007700087000970010700117001270013700147001570016700177001870019700207002170022700237002470025700267002770028700297003070031700327003370034700357003670037700387003970040700417004270043700447004570046700477004870049700507005170052700537005470055700567005770058700597006070061700627006370064700657006670067700687006970070700717007270073700747007570076700777007870079700807008170082700837008470085700867008770088700897009070091700927009370094700957009670097700987009970100701017010270103701047010570106701077010870109701107011170112701137011470115701167011770118701197012070121701227012370124701257012670127701287012970130701317013270133701347013570136701377013870139701407014170142701437014470145701467014770148701497015070151701527015370154701557015670157701587015970160701617016270163701647016570166701677016870169701707017170172701737017470175701767017770178701797018070181701827018370184701857018670187701887018970190701917019270193701947019570196701977019870199702007020170202702037020470205702067020770208702097021070211702127021370214702157021670217702187021970220702217022270223702247022570226702277022870229702307023170232702337023470235702367023770238702397024070241702427024370244702457024670247702487024970250702517025270253702547025570256702577025870259702607026170262702637026470265702667026770268702697027070271702727027370274702757027670277702787027970280702817028270283702847028570286702877028870289702907029170292702937029470295702967029770298702997030070301703027030370304703057030670307703087030970310703117031270313703147031570316703177031870319703207032170322703237032470325703267032770328703297033070331703327033370334703357033670337703387033970340703417034270343703447034570346703477034870349703507035170352703537035470355703567035770358703597036070361703627036370364703657036670367703687036970370703717037270373703747037570376703777037870379703807038170382703837038470385703867038770388703897039070391703927039370394703957039670397703987039970400704017040270403704047040570406704077040870409704107041170412704137041470415704167041770418704197042070421704227042370424704257042670427704287042970430704317043270433704347043570436704377043870439704407044170442704437044470445704467044770448704497045070451704527045370454704557045670457704587045970460704617046270463704647046570466704677046870469704707047170472704737047470475704767047770478704797048070481704827048370484704857048670487704887048970490704917049270493704947049570496704977049870499705007050170502705037050470505705067050770508705097051070511705127051370514705157051670517705187051970520705217052270523705247052570526705277052870529705307053170532705337053470535705367053770538705397054070541705427054370544705457054670547705487054970550705517055270553705547055570556705577055870559705607056170562705637056470565705667056770568705697057070571705727057370574705757057670577705787057970580705817058270583705847058570586705877058870589705907059170592705937059470595705967059770598705997060070601706027060370604706057060670607706087060970610706117061270613706147061570616706177061870619706207062170622706237062470625706267062770628706297063070631706327063370634706357063670637706387063970640706417064270643706447064570646706477064870649706507065170652706537065470655706567065770658706597066070661706627066370664706657066670667706687066970670706717067270673706747067570676706777067870679706807068170682706837068470685706867068770688706897069070691706927069370694706957069670697706987069970700707017070270703707047070570706707077070870709707107071170712707137071470715707167071770718707197072070721707227072370724707257072670727707287072970730707317073270733707347073570736707377073870739707407074170742707437074470745707467074770748707497075070751707527075370754707557075670757707587075970760707617076270763707647076570766707677076870769707707077170772707737077470775707767077770778707797078070781707827078370784707857078670787707887078970790707917079270793707947079570796707977079870799708007080170802708037080470805708067080770808708097081070811708127081370814708157081670817708187081970820708217082270823708247082570826708277082870829708307083170832708337083470835708367083770838708397084070841708427084370844708457084670847708487084970850708517085270853708547085570856708577085870859708607086170862708637086470865708667086770868708697087070871708727087370874708757087670877708787087970880708817088270883708847088570886708877088870889708907089170892708937089470895708967089770898708997090070901709027090370904709057090670907709087090970910709117091270913709147091570916709177091870919709207092170922709237092470925709267092770928709297093070931709327093370934709357093670937709387093970940709417094270943709447094570946709477094870949709507095170952709537095470955709567095770958709597096070961709627096370964709657096670967709687096970970709717097270973709747097570976709777097870979709807098170982709837098470985709867098770988709897099070991709927099370994709957099670997709987099971000710017100271003710047100571006710077100871009710107101171012710137101471015710167101771018710197102071021710227102371024710257102671027710287102971030710317103271033710347103571036710377103871039710407104171042710437104471045710467104771048710497105071051710527105371054710557105671057710587105971060710617106271063710647106571066710677106871069710707107171072710737107471075710767107771078710797108071081710827108371084710857108671087710887108971090710917109271093710947109571096710977109871099711007110171102711037110471105711067110771108711097111071111711127111371114711157111671117711187111971120711217112271123711247112571126711277112871129711307113171132711337113471135711367113771138711397114071141711427114371144711457114671147711487114971150711517115271153711547115571156711577115871159711607116171162711637116471165711667116771168711697117071171711727117371174711757117671177711787117971180711817118271183711847118571186711877118871189711907119171192711937119471195711967119771198711997120071201712027120371204712057120671207712087120971210712117121271213712147121571216712177121871219712207122171222712237122471225712267122771228712297123071231712327123371234712357123671237712387123971240712417124271243712447124571246712477124871249712507125171252712537125471255712567125771258712597126071261712627126371264712657126671267712687126971270712717127271273712747127571276712777127871279712807128171282712837128471285712867128771288712897129071291712927129371294712957129671297712987129971300713017130271303713047130571306713077130871309713107131171312713137131471315713167131771318713197132071321713227132371324713257132671327713287132971330713317133271333713347133571336713377133871339713407134171342713437134471345713467134771348713497135071351713527135371354713557135671357713587135971360713617136271363713647136571366713677136871369713707137171372713737137471375713767137771378713797138071381713827138371384713857138671387713887138971390713917139271393713947139571396713977139871399714007140171402714037140471405714067140771408714097141071411714127141371414714157141671417714187141971420714217142271423714247142571426714277142871429714307143171432714337143471435714367143771438714397144071441714427144371444714457144671447714487144971450714517145271453714547145571456714577145871459714607146171462714637146471465714667146771468714697147071471714727147371474714757147671477714787147971480714817148271483714847148571486714877148871489714907149171492714937149471495714967149771498714997150071501715027150371504715057150671507715087150971510715117151271513715147151571516715177151871519715207152171522715237152471525715267152771528715297153071531715327153371534715357153671537715387153971540715417154271543715447154571546715477154871549715507155171552715537155471555715567155771558715597156071561715627156371564715657156671567715687156971570715717157271573715747157571576715777157871579715807158171582715837158471585715867158771588715897159071591715927159371594715957159671597715987159971600716017160271603716047160571606716077160871609716107161171612716137161471615716167161771618716197162071621716227162371624716257162671627716287162971630716317163271633716347163571636716377163871639716407164171642716437164471645716467164771648716497165071651716527165371654716557165671657716587165971660716617166271663716647166571666716677166871669716707167171672716737167471675716767167771678716797168071681716827168371684716857168671687716887168971690716917169271693716947169571696716977169871699717007170171702717037170471705717067170771708717097171071711717127171371714717157171671717717187171971720717217172271723717247172571726717277172871729717307173171732717337173471735717367173771738717397174071741717427174371744717457174671747717487174971750717517175271753717547175571756717577175871759717607176171762717637176471765717667176771768717697177071771717727177371774717757177671777717787177971780717817178271783717847178571786717877178871789717907179171792717937179471795717967179771798717997180071801718027180371804718057180671807718087180971810718117181271813718147181571816718177181871819718207182171822718237182471825718267182771828718297183071831718327183371834718357183671837718387183971840718417184271843718447184571846718477184871849718507185171852718537185471855718567185771858718597186071861718627186371864718657186671867718687186971870718717187271873718747187571876718777187871879718807188171882718837188471885718867188771888718897189071891718927189371894718957189671897718987189971900719017190271903719047190571906719077190871909719107191171912719137191471915719167191771918719197192071921719227192371924719257192671927719287192971930719317193271933719347193571936719377193871939719407194171942719437194471945719467194771948719497195071951719527195371954719557195671957719587195971960719617196271963719647196571966719677196871969719707197171972719737197471975719767197771978719797198071981719827198371984719857198671987719887198971990719917199271993719947199571996719977199871999720007200172002720037200472005720067200772008720097201072011720127201372014720157201672017720187201972020720217202272023720247202572026720277202872029720307203172032720337203472035720367203772038720397204072041720427204372044720457204672047720487204972050720517205272053720547205572056720577205872059720607206172062720637206472065720667206772068720697207072071720727207372074720757207672077720787207972080720817208272083720847208572086720877208872089720907209172092720937209472095720967209772098720997210072101721027210372104721057210672107721087210972110721117211272113721147211572116721177211872119721207212172122721237212472125721267212772128721297213072131721327213372134721357213672137721387213972140721417214272143721447214572146721477214872149721507215172152721537215472155721567215772158721597216072161721627216372164721657216672167721687216972170721717217272173721747217572176721777217872179721807218172182721837218472185721867218772188721897219072191721927219372194721957219672197721987219972200722017220272203722047220572206722077220872209722107221172212722137221472215722167221772218722197222072221722227222372224722257222672227722287222972230722317223272233722347223572236722377223872239722407224172242722437224472245722467224772248722497225072251722527225372254722557225672257722587225972260722617226272263722647226572266722677226872269722707227172272722737227472275722767227772278722797228072281722827228372284722857228672287722887228972290722917229272293722947229572296722977229872299723007230172302723037230472305723067230772308723097231072311723127231372314723157231672317723187231972320723217232272323723247232572326723277232872329723307233172332723337233472335723367233772338723397234072341723427234372344723457234672347723487234972350723517235272353723547235572356723577235872359723607236172362723637236472365723667236772368723697237072371723727237372374723757237672377723787237972380723817238272383723847238572386723877238872389723907239172392723937239472395723967239772398723997240072401724027240372404724057240672407724087240972410724117241272413724147241572416724177241872419724207242172422724237242472425724267242772428724297243072431724327243372434724357243672437724387243972440724417244272443724447244572446724477244872449724507245172452724537245472455724567245772458724597246072461724627246372464724657246672467724687246972470724717247272473724747247572476724777247872479724807248172482724837248472485724867248772488724897249072491724927249372494724957249672497724987249972500725017250272503725047250572506725077250872509725107251172512725137251472515725167251772518725197252072521725227252372524725257252672527725287252972530725317253272533725347253572536725377253872539725407254172542725437254472545725467254772548725497255072551725527255372554725557255672557725587255972560725617256272563725647256572566725677256872569725707257172572725737257472575725767257772578725797258072581725827258372584725857258672587725887258972590725917259272593725947259572596725977259872599726007260172602726037260472605726067260772608726097261072611726127261372614726157261672617726187261972620726217262272623726247262572626726277262872629726307263172632726337263472635726367263772638726397264072641726427264372644726457264672647726487264972650726517265272653726547265572656726577265872659726607266172662726637266472665726667266772668726697267072671726727267372674726757267672677726787267972680726817268272683726847268572686726877268872689726907269172692726937269472695726967269772698726997270072701727027270372704727057270672707727087270972710727117271272713727147271572716727177271872719727207272172722727237272472725727267272772728727297273072731727327273372734727357273672737727387273972740727417274272743727447274572746727477274872749727507275172752727537275472755727567275772758727597276072761727627276372764727657276672767727687276972770727717277272773727747277572776727777277872779727807278172782727837278472785727867278772788727897279072791727927279372794727957279672797727987279972800728017280272803728047280572806728077280872809728107281172812728137281472815728167281772818728197282072821728227282372824728257282672827728287282972830728317283272833728347283572836728377283872839728407284172842728437284472845728467284772848728497285072851728527285372854728557285672857728587285972860728617286272863728647286572866728677286872869728707287172872728737287472875728767287772878728797288072881728827288372884728857288672887728887288972890728917289272893728947289572896728977289872899729007290172902729037290472905729067290772908729097291072911729127291372914729157291672917729187291972920729217292272923729247292572926729277292872929729307293172932729337293472935729367293772938729397294072941729427294372944729457294672947729487294972950729517295272953729547295572956729577295872959729607296172962729637296472965729667296772968729697297072971729727297372974729757297672977729787297972980729817298272983729847298572986729877298872989729907299172992729937299472995729967299772998729997300073001730027300373004730057300673007730087300973010730117301273013730147301573016730177301873019730207302173022730237302473025730267302773028730297303073031730327303373034730357303673037730387303973040730417304273043730447304573046730477304873049730507305173052730537305473055730567305773058730597306073061730627306373064730657306673067730687306973070730717307273073730747307573076730777307873079730807308173082730837308473085730867308773088730897309073091730927309373094730957309673097730987309973100731017310273103731047310573106731077310873109731107311173112731137311473115731167311773118731197312073121731227312373124731257312673127731287312973130731317313273133731347313573136731377313873139731407314173142731437314473145731467314773148731497315073151731527315373154731557315673157731587315973160731617316273163731647316573166731677316873169731707317173172731737317473175731767317773178731797318073181731827318373184731857318673187731887318973190731917319273193731947319573196731977319873199732007320173202732037320473205732067320773208732097321073211732127321373214732157321673217732187321973220732217322273223732247322573226732277322873229732307323173232732337323473235732367323773238732397324073241732427324373244732457324673247732487324973250732517325273253732547325573256732577325873259732607326173262732637326473265732667326773268732697327073271732727327373274732757327673277732787327973280732817328273283732847328573286732877328873289732907329173292732937329473295732967329773298732997330073301733027330373304733057330673307733087330973310733117331273313733147331573316733177331873319733207332173322733237332473325733267332773328733297333073331733327333373334733357333673337733387333973340733417334273343733447334573346733477334873349733507335173352733537335473355733567335773358733597336073361733627336373364733657336673367733687336973370733717337273373733747337573376733777337873379733807338173382733837338473385733867338773388733897339073391733927339373394733957339673397733987339973400734017340273403734047340573406734077340873409734107341173412734137341473415734167341773418734197342073421734227342373424734257342673427734287342973430734317343273433734347343573436734377343873439734407344173442734437344473445734467344773448734497345073451734527345373454734557345673457734587345973460734617346273463734647346573466734677346873469734707347173472734737347473475734767347773478734797348073481734827348373484734857348673487734887348973490734917349273493734947349573496734977349873499735007350173502735037350473505735067350773508735097351073511735127351373514735157351673517735187351973520735217352273523735247352573526735277352873529735307353173532735337353473535735367353773538735397354073541735427354373544735457354673547735487354973550735517355273553735547355573556735577355873559735607356173562735637356473565735667356773568735697357073571735727357373574735757357673577735787357973580735817358273583735847358573586735877358873589735907359173592735937359473595735967359773598735997360073601736027360373604736057360673607736087360973610736117361273613736147361573616736177361873619736207362173622736237362473625736267362773628736297363073631736327363373634736357363673637736387363973640736417364273643736447364573646736477364873649736507365173652736537365473655736567365773658736597366073661736627366373664736657366673667736687366973670736717367273673736747367573676736777367873679736807368173682736837368473685736867368773688736897369073691736927369373694736957369673697736987369973700737017370273703737047370573706737077370873709737107371173712737137371473715737167371773718737197372073721737227372373724737257372673727737287372973730737317373273733737347373573736737377373873739737407374173742737437374473745737467374773748737497375073751737527375373754737557375673757737587375973760737617376273763737647376573766737677376873769737707377173772737737377473775737767377773778737797378073781737827378373784737857378673787737887378973790737917379273793737947379573796737977379873799738007380173802738037380473805738067380773808738097381073811738127381373814738157381673817738187381973820738217382273823738247382573826738277382873829738307383173832738337383473835738367383773838738397384073841738427384373844738457384673847738487384973850738517385273853738547385573856738577385873859738607386173862738637386473865738667386773868738697387073871738727387373874738757387673877738787387973880738817388273883738847388573886738877388873889738907389173892738937389473895738967389773898738997390073901739027390373904739057390673907739087390973910739117391273913739147391573916739177391873919739207392173922739237392473925739267392773928739297393073931739327393373934739357393673937739387393973940739417394273943739447394573946739477394873949739507395173952739537395473955739567395773958739597396073961739627396373964739657396673967739687396973970739717397273973739747397573976739777397873979739807398173982739837398473985739867398773988739897399073991739927399373994739957399673997739987399974000740017400274003740047400574006740077400874009740107401174012740137401474015740167401774018740197402074021740227402374024740257402674027740287402974030740317403274033740347403574036740377403874039740407404174042740437404474045740467404774048740497405074051740527405374054740557405674057740587405974060740617406274063740647406574066740677406874069740707407174072740737407474075740767407774078740797408074081740827408374084740857408674087740887408974090740917409274093740947409574096740977409874099741007410174102741037410474105741067410774108741097411074111741127411374114741157411674117741187411974120741217412274123741247412574126741277412874129741307413174132741337413474135741367413774138741397414074141741427414374144741457414674147741487414974150741517415274153741547415574156741577415874159741607416174162741637416474165741667416774168741697417074171741727417374174741757417674177741787417974180741817418274183741847418574186741877418874189741907419174192741937419474195741967419774198741997420074201742027420374204742057420674207742087420974210742117421274213742147421574216742177421874219742207422174222742237422474225742267422774228742297423074231742327423374234742357423674237742387423974240742417424274243742447424574246742477424874249742507425174252742537425474255742567425774258742597426074261742627426374264742657426674267742687426974270742717427274273742747427574276742777427874279742807428174282742837428474285742867428774288742897429074291742927429374294742957429674297742987429974300743017430274303743047430574306743077430874309743107431174312743137431474315743167431774318743197432074321743227432374324743257432674327743287432974330743317433274333743347433574336743377433874339743407434174342743437434474345743467434774348743497435074351743527435374354743557435674357743587435974360743617436274363743647436574366743677436874369743707437174372743737437474375743767437774378743797438074381743827438374384743857438674387743887438974390743917439274393743947439574396743977439874399744007440174402744037440474405744067440774408744097441074411744127441374414744157441674417744187441974420744217442274423744247442574426744277442874429744307443174432744337443474435744367443774438744397444074441744427444374444744457444674447744487444974450744517445274453744547445574456744577445874459744607446174462744637446474465744667446774468744697447074471744727447374474744757447674477744787447974480744817448274483744847448574486744877448874489744907449174492744937449474495744967449774498744997450074501745027450374504745057450674507745087450974510745117451274513745147451574516745177451874519745207452174522745237452474525745267452774528745297453074531745327453374534745357453674537745387453974540745417454274543745447454574546745477454874549745507455174552745537455474555745567455774558745597456074561745627456374564745657456674567745687456974570745717457274573745747457574576745777457874579745807458174582745837458474585745867458774588745897459074591745927459374594745957459674597745987459974600746017460274603746047460574606746077460874609746107461174612746137461474615746167461774618746197462074621746227462374624746257462674627746287462974630746317463274633746347463574636746377463874639746407464174642746437464474645746467464774648746497465074651746527465374654746557465674657746587465974660746617466274663746647466574666746677466874669746707467174672746737467474675746767467774678746797468074681746827468374684746857468674687746887468974690746917469274693746947469574696746977469874699747007470174702747037470474705747067470774708747097471074711747127471374714747157471674717747187471974720747217472274723747247472574726747277472874729747307473174732747337473474735747367473774738747397474074741747427474374744747457474674747747487474974750747517475274753747547475574756747577475874759747607476174762747637476474765747667476774768747697477074771747727477374774747757477674777747787477974780747817478274783747847478574786747877478874789747907479174792747937479474795747967479774798747997480074801748027480374804748057480674807748087480974810748117481274813748147481574816748177481874819748207482174822748237482474825748267482774828748297483074831748327483374834748357483674837748387483974840748417484274843748447484574846748477484874849748507485174852748537485474855748567485774858748597486074861748627486374864748657486674867748687486974870748717487274873748747487574876748777487874879748807488174882748837488474885748867488774888748897489074891748927489374894748957489674897748987489974900749017490274903749047490574906749077490874909749107491174912749137491474915749167491774918749197492074921749227492374924749257492674927749287492974930749317493274933749347493574936749377493874939749407494174942749437494474945749467494774948749497495074951749527495374954749557495674957749587495974960749617496274963749647496574966749677496874969749707497174972749737497474975749767497774978749797498074981749827498374984749857498674987749887498974990749917499274993749947499574996749977499874999750007500175002750037500475005750067500775008750097501075011750127501375014750157501675017750187501975020750217502275023750247502575026750277502875029750307503175032750337503475035750367503775038750397504075041750427504375044750457504675047750487504975050750517505275053750547505575056750577505875059750607506175062750637506475065750667506775068750697507075071750727507375074750757507675077750787507975080750817508275083750847508575086750877508875089750907509175092750937509475095750967509775098750997510075101751027510375104751057510675107751087510975110751117511275113751147511575116751177511875119751207512175122751237512475125751267512775128751297513075131751327513375134751357513675137751387513975140751417514275143751447514575146751477514875149751507515175152751537515475155751567515775158751597516075161751627516375164751657516675167751687516975170751717517275173751747517575176751777517875179751807518175182751837518475185751867518775188751897519075191751927519375194751957519675197751987519975200752017520275203752047520575206752077520875209752107521175212752137521475215752167521775218752197522075221752227522375224752257522675227752287522975230752317523275233752347523575236752377523875239752407524175242752437524475245752467524775248752497525075251752527525375254752557525675257752587525975260752617526275263752647526575266752677526875269752707527175272752737527475275752767527775278752797528075281752827528375284752857528675287752887528975290752917529275293752947529575296752977529875299753007530175302753037530475305753067530775308753097531075311753127531375314753157531675317753187531975320753217532275323753247532575326753277532875329753307533175332753337533475335753367533775338753397534075341753427534375344753457534675347753487534975350753517535275353753547535575356753577535875359753607536175362753637536475365753667536775368753697537075371753727537375374753757537675377753787537975380753817538275383753847538575386753877538875389753907539175392753937539475395753967539775398753997540075401754027540375404754057540675407754087540975410754117541275413754147541575416754177541875419754207542175422754237542475425754267542775428754297543075431754327543375434754357543675437754387543975440754417544275443754447544575446754477544875449754507545175452754537545475455754567545775458754597546075461754627546375464754657546675467754687546975470754717547275473754747547575476754777547875479754807548175482754837548475485754867548775488754897549075491754927549375494754957549675497754987549975500755017550275503755047550575506755077550875509755107551175512755137551475515755167551775518755197552075521755227552375524755257552675527755287552975530755317553275533755347553575536755377553875539755407554175542755437554475545755467554775548755497555075551755527555375554755557555675557755587555975560755617556275563755647556575566755677556875569755707557175572755737557475575755767557775578755797558075581755827558375584755857558675587755887558975590755917559275593755947559575596755977559875599756007560175602756037560475605756067560775608756097561075611756127561375614756157561675617756187561975620756217562275623756247562575626756277562875629756307563175632756337563475635756367563775638756397564075641756427564375644756457564675647756487564975650756517565275653756547565575656756577565875659756607566175662756637566475665756667566775668756697567075671756727567375674756757567675677756787567975680756817568275683756847568575686756877568875689756907569175692756937569475695756967569775698756997570075701757027570375704757057570675707757087570975710757117571275713757147571575716757177571875719757207572175722757237572475725757267572775728757297573075731757327573375734757357573675737757387573975740757417574275743757447574575746757477574875749757507575175752757537575475755757567575775758757597576075761757627576375764757657576675767757687576975770757717577275773757747577575776757777577875779757807578175782757837578475785757867578775788757897579075791757927579375794757957579675797757987579975800758017580275803758047580575806758077580875809758107581175812758137581475815758167581775818758197582075821758227582375824758257582675827758287582975830758317583275833758347583575836758377583875839758407584175842758437584475845758467584775848758497585075851758527585375854758557585675857758587585975860758617586275863758647586575866758677586875869758707587175872758737587475875758767587775878758797588075881758827588375884758857588675887758887588975890758917589275893758947589575896758977589875899759007590175902759037590475905759067590775908759097591075911759127591375914759157591675917759187591975920759217592275923759247592575926759277592875929759307593175932759337593475935759367593775938759397594075941759427594375944759457594675947759487594975950759517595275953759547595575956759577595875959759607596175962759637596475965759667596775968759697597075971759727597375974759757597675977759787597975980759817598275983759847598575986759877598875989759907599175992759937599475995759967599775998759997600076001760027600376004760057600676007760087600976010760117601276013760147601576016760177601876019760207602176022760237602476025760267602776028760297603076031760327603376034760357603676037760387603976040760417604276043760447604576046760477604876049760507605176052760537605476055760567605776058760597606076061760627606376064760657606676067760687606976070760717607276073760747607576076760777607876079760807608176082760837608476085760867608776088760897609076091760927609376094760957609676097760987609976100761017610276103761047610576106761077610876109761107611176112761137611476115761167611776118761197612076121761227612376124761257612676127761287612976130761317613276133761347613576136761377613876139761407614176142761437614476145761467614776148761497615076151761527615376154761557615676157761587615976160761617616276163761647616576166761677616876169761707617176172761737617476175761767617776178761797618076181761827618376184761857618676187761887618976190761917619276193761947619576196761977619876199762007620176202762037620476205762067620776208762097621076211762127621376214762157621676217762187621976220762217622276223762247622576226762277622876229762307623176232762337623476235762367623776238762397624076241762427624376244762457624676247762487624976250762517625276253762547625576256762577625876259762607626176262762637626476265762667626776268762697627076271762727627376274762757627676277762787627976280762817628276283762847628576286762877628876289762907629176292762937629476295762967629776298762997630076301763027630376304763057630676307763087630976310763117631276313763147631576316763177631876319763207632176322763237632476325763267632776328763297633076331763327633376334763357633676337763387633976340763417634276343763447634576346763477634876349763507635176352763537635476355763567635776358763597636076361763627636376364763657636676367763687636976370763717637276373763747637576376763777637876379763807638176382763837638476385763867638776388763897639076391763927639376394763957639676397763987639976400764017640276403764047640576406764077640876409764107641176412764137641476415764167641776418764197642076421764227642376424764257642676427764287642976430764317643276433764347643576436764377643876439764407644176442764437644476445764467644776448764497645076451764527645376454764557645676457764587645976460764617646276463764647646576466764677646876469764707647176472764737647476475764767647776478764797648076481764827648376484764857648676487764887648976490764917649276493764947649576496764977649876499765007650176502765037650476505765067650776508765097651076511765127651376514765157651676517765187651976520765217652276523765247652576526765277652876529765307653176532765337653476535765367653776538765397654076541765427654376544765457654676547765487654976550765517655276553765547655576556765577655876559765607656176562765637656476565765667656776568765697657076571765727657376574765757657676577765787657976580765817658276583765847658576586765877658876589765907659176592765937659476595765967659776598765997660076601766027660376604766057660676607766087660976610766117661276613766147661576616766177661876619766207662176622766237662476625766267662776628766297663076631766327663376634766357663676637766387663976640766417664276643766447664576646766477664876649766507665176652766537665476655766567665776658766597666076661766627666376664766657666676667766687666976670766717667276673766747667576676766777667876679766807668176682766837668476685766867668776688766897669076691766927669376694766957669676697766987669976700767017670276703767047670576706767077670876709767107671176712767137671476715767167671776718767197672076721767227672376724767257672676727767287672976730767317673276733767347673576736767377673876739767407674176742767437674476745767467674776748767497675076751767527675376754767557675676757767587675976760767617676276763767647676576766767677676876769767707677176772767737677476775767767677776778767797678076781767827678376784767857678676787767887678976790767917679276793767947679576796767977679876799768007680176802768037680476805768067680776808768097681076811768127681376814768157681676817768187681976820768217682276823768247682576826768277682876829768307683176832768337683476835768367683776838768397684076841768427684376844768457684676847768487684976850768517685276853768547685576856768577685876859768607686176862768637686476865768667686776868768697687076871768727687376874768757687676877768787687976880768817688276883768847688576886768877688876889768907689176892768937689476895768967689776898768997690076901769027690376904769057690676907769087690976910769117691276913769147691576916769177691876919769207692176922769237692476925769267692776928769297693076931769327693376934769357693676937769387693976940769417694276943769447694576946769477694876949769507695176952769537695476955769567695776958769597696076961769627696376964769657696676967769687696976970769717697276973769747697576976769777697876979769807698176982769837698476985769867698776988769897699076991769927699376994769957699676997769987699977000770017700277003770047700577006770077700877009770107701177012770137701477015770167701777018770197702077021770227702377024770257702677027770287702977030770317703277033770347703577036770377703877039770407704177042770437704477045770467704777048770497705077051770527705377054770557705677057770587705977060770617706277063770647706577066770677706877069770707707177072770737707477075770767707777078770797708077081770827708377084770857708677087770887708977090770917709277093770947709577096770977709877099771007710177102771037710477105771067710777108771097711077111771127711377114771157711677117771187711977120771217712277123771247712577126771277712877129771307713177132771337713477135771367713777138771397714077141771427714377144771457714677147771487714977150771517715277153771547715577156771577715877159771607716177162771637716477165771667716777168771697717077171771727717377174771757717677177771787717977180771817718277183771847718577186771877718877189771907719177192771937719477195771967719777198771997720077201772027720377204772057720677207772087720977210772117721277213772147721577216772177721877219772207722177222772237722477225772267722777228772297723077231772327723377234772357723677237772387723977240772417724277243772447724577246772477724877249772507725177252772537725477255772567725777258772597726077261772627726377264772657726677267772687726977270772717727277273772747727577276772777727877279772807728177282772837728477285772867728777288772897729077291772927729377294772957729677297772987729977300773017730277303773047730577306773077730877309773107731177312773137731477315773167731777318773197732077321773227732377324773257732677327773287732977330773317733277333773347733577336773377733877339773407734177342773437734477345773467734777348773497735077351773527735377354773557735677357773587735977360773617736277363773647736577366773677736877369773707737177372773737737477375773767737777378773797738077381773827738377384773857738677387773887738977390773917739277393773947739577396773977739877399774007740177402774037740477405774067740777408774097741077411774127741377414774157741677417774187741977420774217742277423774247742577426774277742877429774307743177432774337743477435774367743777438774397744077441774427744377444774457744677447774487744977450774517745277453774547745577456774577745877459774607746177462774637746477465774667746777468774697747077471774727747377474774757747677477774787747977480774817748277483774847748577486774877748877489774907749177492774937749477495774967749777498774997750077501775027750377504775057750677507775087750977510775117751277513775147751577516775177751877519775207752177522775237752477525775267752777528775297753077531775327753377534775357753677537775387753977540775417754277543775447754577546775477754877549775507755177552775537755477555775567755777558775597756077561775627756377564775657756677567775687756977570775717757277573775747757577576775777757877579775807758177582775837758477585775867758777588775897759077591775927759377594775957759677597775987759977600776017760277603776047760577606776077760877609776107761177612776137761477615776167761777618776197762077621776227762377624776257762677627776287762977630776317763277633776347763577636776377763877639776407764177642776437764477645776467764777648776497765077651776527765377654776557765677657776587765977660776617766277663776647766577666776677766877669776707767177672776737767477675776767767777678776797768077681776827768377684776857768677687776887768977690776917769277693776947769577696776977769877699777007770177702777037770477705777067770777708777097771077711777127771377714777157771677717777187771977720777217772277723777247772577726777277772877729777307773177732777337773477735777367773777738777397774077741777427774377744777457774677747777487774977750777517775277753777547775577756777577775877759777607776177762777637776477765777667776777768777697777077771777727777377774777757777677777777787777977780777817778277783777847778577786777877778877789777907779177792777937779477795777967779777798777997780077801778027780377804778057780677807778087780977810778117781277813778147781577816778177781877819778207782177822778237782477825778267782777828778297783077831778327783377834778357783677837778387783977840778417784277843778447784577846778477784877849778507785177852778537785477855778567785777858778597786077861778627786377864778657786677867778687786977870778717787277873778747787577876778777787877879778807788177882778837788477885778867788777888778897789077891778927789377894778957789677897778987789977900779017790277903779047790577906779077790877909779107791177912779137791477915779167791777918779197792077921779227792377924779257792677927779287792977930779317793277933779347793577936779377793877939779407794177942779437794477945779467794777948779497795077951779527795377954779557795677957779587795977960779617796277963779647796577966779677796877969779707797177972779737797477975779767797777978779797798077981779827798377984779857798677987779887798977990779917799277993779947799577996779977799877999780007800178002780037800478005780067800778008780097801078011780127801378014780157801678017780187801978020780217802278023780247802578026780277802878029780307803178032780337803478035780367803778038780397804078041780427804378044780457804678047780487804978050780517805278053780547805578056780577805878059780607806178062780637806478065780667806778068780697807078071780727807378074780757807678077780787807978080780817808278083780847808578086780877808878089780907809178092780937809478095780967809778098780997810078101781027810378104781057810678107781087810978110781117811278113781147811578116781177811878119781207812178122781237812478125781267812778128781297813078131781327813378134781357813678137781387813978140781417814278143781447814578146781477814878149781507815178152781537815478155781567815778158781597816078161781627816378164781657816678167781687816978170781717817278173781747817578176781777817878179781807818178182781837818478185781867818778188781897819078191781927819378194781957819678197781987819978200782017820278203782047820578206782077820878209782107821178212782137821478215782167821778218782197822078221782227822378224782257822678227782287822978230782317823278233782347823578236782377823878239782407824178242782437824478245782467824778248782497825078251782527825378254782557825678257782587825978260782617826278263782647826578266782677826878269782707827178272782737827478275782767827778278782797828078281782827828378284782857828678287782887828978290782917829278293782947829578296782977829878299783007830178302783037830478305783067830778308783097831078311783127831378314783157831678317783187831978320783217832278323783247832578326783277832878329783307833178332783337833478335783367833778338783397834078341783427834378344783457834678347783487834978350783517835278353783547835578356783577835878359783607836178362783637836478365783667836778368783697837078371783727837378374783757837678377783787837978380783817838278383783847838578386783877838878389783907839178392783937839478395783967839778398783997840078401784027840378404784057840678407784087840978410784117841278413784147841578416784177841878419784207842178422784237842478425784267842778428784297843078431784327843378434784357843678437784387843978440784417844278443784447844578446784477844878449784507845178452784537845478455784567845778458784597846078461784627846378464784657846678467784687846978470784717847278473784747847578476784777847878479784807848178482784837848478485784867848778488784897849078491784927849378494784957849678497784987849978500785017850278503785047850578506785077850878509785107851178512785137851478515785167851778518785197852078521785227852378524785257852678527785287852978530785317853278533785347853578536785377853878539785407854178542785437854478545785467854778548785497855078551785527855378554785557855678557785587855978560785617856278563785647856578566785677856878569785707857178572785737857478575785767857778578785797858078581785827858378584785857858678587785887858978590785917859278593785947859578596785977859878599786007860178602786037860478605786067860778608786097861078611786127861378614786157861678617786187861978620786217862278623786247862578626786277862878629786307863178632786337863478635786367863778638786397864078641786427864378644786457864678647786487864978650786517865278653786547865578656786577865878659786607866178662786637866478665786667866778668786697867078671786727867378674786757867678677786787867978680786817868278683786847868578686786877868878689786907869178692786937869478695786967869778698786997870078701787027870378704787057870678707787087870978710787117871278713787147871578716787177871878719787207872178722787237872478725787267872778728787297873078731787327873378734787357873678737787387873978740787417874278743787447874578746787477874878749787507875178752787537875478755787567875778758787597876078761787627876378764787657876678767787687876978770787717877278773787747877578776787777877878779787807878178782787837878478785787867878778788787897879078791787927879378794787957879678797787987879978800788017880278803788047880578806788077880878809788107881178812788137881478815788167881778818788197882078821788227882378824788257882678827788287882978830788317883278833788347883578836788377883878839788407884178842788437884478845788467884778848788497885078851788527885378854788557885678857788587885978860788617886278863788647886578866788677886878869788707887178872788737887478875788767887778878788797888078881788827888378884788857888678887788887888978890788917889278893788947889578896788977889878899789007890178902789037890478905789067890778908789097891078911789127891378914789157891678917789187891978920789217892278923789247892578926789277892878929789307893178932789337893478935789367893778938789397894078941789427894378944789457894678947789487894978950789517895278953789547895578956789577895878959789607896178962789637896478965789667896778968789697897078971789727897378974789757897678977789787897978980789817898278983789847898578986789877898878989789907899178992789937899478995789967899778998789997900079001790027900379004790057900679007790087900979010790117901279013790147901579016790177901879019790207902179022790237902479025790267902779028790297903079031790327903379034790357903679037790387903979040790417904279043790447904579046790477904879049790507905179052790537905479055790567905779058790597906079061790627906379064790657906679067790687906979070790717907279073790747907579076790777907879079790807908179082790837908479085790867908779088790897909079091790927909379094790957909679097790987909979100791017910279103791047910579106791077910879109791107911179112791137911479115791167911779118791197912079121791227912379124791257912679127791287912979130791317913279133791347913579136791377913879139791407914179142791437914479145791467914779148791497915079151791527915379154791557915679157791587915979160791617916279163791647916579166791677916879169791707917179172791737917479175791767917779178791797918079181791827918379184791857918679187791887918979190791917919279193791947919579196791977919879199792007920179202792037920479205792067920779208792097921079211792127921379214792157921679217792187921979220792217922279223792247922579226792277922879229792307923179232792337923479235792367923779238792397924079241792427924379244792457924679247792487924979250792517925279253792547925579256792577925879259792607926179262792637926479265792667926779268792697927079271792727927379274792757927679277792787927979280792817928279283792847928579286792877928879289792907929179292792937929479295792967929779298792997930079301793027930379304793057930679307793087930979310793117931279313793147931579316793177931879319793207932179322793237932479325793267932779328793297933079331793327933379334793357933679337793387933979340793417934279343793447934579346793477934879349793507935179352793537935479355793567935779358793597936079361793627936379364793657936679367793687936979370793717937279373793747937579376793777937879379793807938179382793837938479385793867938779388793897939079391793927939379394793957939679397793987939979400794017940279403794047940579406794077940879409794107941179412794137941479415794167941779418794197942079421794227942379424794257942679427794287942979430794317943279433794347943579436794377943879439794407944179442794437944479445794467944779448794497945079451794527945379454794557945679457794587945979460794617946279463794647946579466794677946879469794707947179472794737947479475794767947779478794797948079481794827948379484794857948679487794887948979490794917949279493794947949579496794977949879499795007950179502795037950479505795067950779508795097951079511795127951379514795157951679517795187951979520795217952279523795247952579526795277952879529795307953179532795337953479535795367953779538795397954079541795427954379544795457954679547795487954979550795517955279553795547955579556795577955879559795607956179562795637956479565795667956779568795697957079571795727957379574795757957679577795787957979580795817958279583795847958579586795877958879589795907959179592795937959479595795967959779598795997960079601796027960379604796057960679607796087960979610796117961279613796147961579616796177961879619796207962179622796237962479625796267962779628796297963079631796327963379634796357963679637796387963979640796417964279643796447964579646796477964879649796507965179652796537965479655796567965779658796597966079661796627966379664796657966679667796687966979670796717967279673796747967579676796777967879679796807968179682796837968479685796867968779688796897969079691796927969379694796957969679697796987969979700797017970279703797047970579706797077970879709797107971179712797137971479715797167971779718797197972079721797227972379724797257972679727797287972979730797317973279733797347973579736797377973879739797407974179742797437974479745797467974779748797497975079751797527975379754797557975679757797587975979760797617976279763797647976579766797677976879769797707977179772797737977479775797767977779778797797978079781797827978379784797857978679787797887978979790797917979279793797947979579796797977979879799798007980179802798037980479805798067980779808798097981079811798127981379814798157981679817798187981979820798217982279823798247982579826798277982879829798307983179832798337983479835798367983779838798397984079841798427984379844798457984679847798487984979850798517985279853798547985579856798577985879859798607986179862798637986479865798667986779868798697987079871798727987379874798757987679877798787987979880798817988279883798847988579886798877988879889798907989179892798937989479895798967989779898798997990079901799027990379904799057990679907799087990979910799117991279913799147991579916799177991879919799207992179922799237992479925799267992779928799297993079931799327993379934799357993679937799387993979940799417994279943799447994579946799477994879949799507995179952799537995479955799567995779958799597996079961799627996379964799657996679967799687996979970799717997279973799747997579976799777997879979799807998179982799837998479985799867998779988799897999079991799927999379994799957999679997799987999980000800018000280003800048000580006800078000880009800108001180012800138001480015800168001780018800198002080021800228002380024800258002680027800288002980030800318003280033800348003580036800378003880039800408004180042800438004480045800468004780048800498005080051800528005380054800558005680057800588005980060800618006280063800648006580066800678006880069800708007180072800738007480075800768007780078800798008080081800828008380084800858008680087800888008980090800918009280093800948009580096800978009880099801008010180102801038010480105801068010780108801098011080111801128011380114801158011680117801188011980120801218012280123801248012580126801278012880129801308013180132801338013480135801368013780138801398014080141801428014380144801458014680147801488014980150801518015280153801548015580156801578015880159801608016180162801638016480165801668016780168801698017080171801728017380174801758017680177801788017980180801818018280183801848018580186801878018880189801908019180192801938019480195801968019780198801998020080201802028020380204802058020680207802088020980210802118021280213802148021580216802178021880219802208022180222802238022480225802268022780228802298023080231802328023380234802358023680237802388023980240802418024280243802448024580246802478024880249802508025180252802538025480255802568025780258802598026080261802628026380264802658026680267802688026980270802718027280273802748027580276802778027880279802808028180282802838028480285802868028780288802898029080291802928029380294802958029680297802988029980300803018030280303803048030580306803078030880309803108031180312803138031480315803168031780318803198032080321803228032380324803258032680327803288032980330803318033280333803348033580336803378033880339803408034180342803438034480345803468034780348803498035080351803528035380354803558035680357803588035980360803618036280363803648036580366803678036880369803708037180372803738037480375803768037780378803798038080381803828038380384803858038680387803888038980390803918039280393803948039580396803978039880399804008040180402804038040480405804068040780408804098041080411804128041380414804158041680417804188041980420804218042280423804248042580426804278042880429804308043180432804338043480435804368043780438804398044080441804428044380444804458044680447804488044980450804518045280453804548045580456804578045880459804608046180462804638046480465804668046780468804698047080471804728047380474804758047680477804788047980480804818048280483804848048580486804878048880489804908049180492804938049480495804968049780498804998050080501805028050380504805058050680507805088050980510805118051280513805148051580516805178051880519805208052180522805238052480525805268052780528805298053080531805328053380534805358053680537805388053980540805418054280543805448054580546805478054880549805508055180552805538055480555805568055780558805598056080561805628056380564805658056680567805688056980570805718057280573805748057580576805778057880579805808058180582805838058480585805868058780588805898059080591805928059380594805958059680597805988059980600806018060280603806048060580606806078060880609806108061180612806138061480615806168061780618806198062080621806228062380624806258062680627806288062980630806318063280633806348063580636806378063880639806408064180642806438064480645806468064780648806498065080651806528065380654806558065680657806588065980660806618066280663806648066580666806678066880669806708067180672806738067480675806768067780678806798068080681806828068380684806858068680687806888068980690806918069280693806948069580696806978069880699807008070180702807038070480705807068070780708807098071080711807128071380714807158071680717807188071980720807218072280723807248072580726807278072880729807308073180732807338073480735807368073780738807398074080741807428074380744807458074680747807488074980750807518075280753807548075580756807578075880759807608076180762807638076480765807668076780768807698077080771807728077380774807758077680777807788077980780807818078280783807848078580786807878078880789807908079180792807938079480795807968079780798807998080080801808028080380804808058080680807808088080980810808118081280813808148081580816808178081880819808208082180822808238082480825808268082780828808298083080831808328083380834808358083680837808388083980840808418084280843808448084580846808478084880849808508085180852808538085480855808568085780858808598086080861808628086380864808658086680867808688086980870808718087280873808748087580876808778087880879808808088180882808838088480885808868088780888808898089080891808928089380894808958089680897808988089980900809018090280903809048090580906809078090880909809108091180912809138091480915809168091780918809198092080921809228092380924809258092680927809288092980930809318093280933809348093580936809378093880939809408094180942809438094480945809468094780948809498095080951809528095380954809558095680957809588095980960809618096280963809648096580966809678096880969809708097180972809738097480975809768097780978809798098080981809828098380984809858098680987809888098980990809918099280993809948099580996809978099880999810008100181002810038100481005810068100781008810098101081011810128101381014810158101681017810188101981020810218102281023810248102581026810278102881029810308103181032810338103481035810368103781038810398104081041810428104381044810458104681047810488104981050810518105281053810548105581056810578105881059810608106181062810638106481065810668106781068810698107081071810728107381074810758107681077810788107981080810818108281083810848108581086810878108881089810908109181092810938109481095810968109781098810998110081101811028110381104811058110681107811088110981110811118111281113811148111581116811178111881119811208112181122811238112481125811268112781128811298113081131811328113381134811358113681137811388113981140811418114281143811448114581146811478114881149811508115181152811538115481155811568115781158811598116081161811628116381164811658116681167811688116981170811718117281173811748117581176811778117881179811808118181182811838118481185811868118781188811898119081191811928119381194811958119681197811988119981200812018120281203812048120581206812078120881209812108121181212812138121481215812168121781218812198122081221812228122381224812258122681227812288122981230812318123281233812348123581236812378123881239812408124181242812438124481245812468124781248812498125081251812528125381254812558125681257812588125981260812618126281263812648126581266812678126881269812708127181272812738127481275812768127781278812798128081281812828128381284812858128681287812888128981290812918129281293812948129581296812978129881299813008130181302813038130481305813068130781308813098131081311813128131381314813158131681317813188131981320813218132281323813248132581326813278132881329813308133181332813338133481335813368133781338813398134081341813428134381344813458134681347813488134981350813518135281353813548135581356813578135881359813608136181362813638136481365813668136781368813698137081371813728137381374813758137681377813788137981380813818138281383813848138581386813878138881389813908139181392813938139481395813968139781398813998140081401814028140381404814058140681407814088140981410814118141281413814148141581416814178141881419814208142181422814238142481425814268142781428814298143081431814328143381434814358143681437814388143981440814418144281443814448144581446814478144881449814508145181452814538145481455814568145781458814598146081461814628146381464814658146681467814688146981470814718147281473814748147581476814778147881479814808148181482814838148481485814868148781488814898149081491814928149381494814958149681497814988149981500815018150281503815048150581506815078150881509815108151181512815138151481515815168151781518815198152081521815228152381524815258152681527815288152981530815318153281533815348153581536815378153881539815408154181542815438154481545815468154781548815498155081551815528155381554815558155681557815588155981560815618156281563815648156581566815678156881569815708157181572815738157481575815768157781578815798158081581815828158381584815858158681587815888158981590815918159281593815948159581596815978159881599816008160181602816038160481605816068160781608816098161081611816128161381614816158161681617816188161981620816218162281623816248162581626816278162881629816308163181632816338163481635816368163781638816398164081641816428164381644816458164681647816488164981650816518165281653816548165581656816578165881659816608166181662816638166481665816668166781668816698167081671816728167381674816758167681677816788167981680816818168281683816848168581686816878168881689816908169181692816938169481695816968169781698816998170081701817028170381704817058170681707817088170981710817118171281713817148171581716817178171881719817208172181722817238172481725817268172781728817298173081731817328173381734817358173681737817388173981740817418174281743817448174581746817478174881749817508175181752817538175481755817568175781758817598176081761817628176381764817658176681767817688176981770817718177281773817748177581776817778177881779817808178181782817838178481785817868178781788817898179081791817928179381794817958179681797817988179981800818018180281803818048180581806818078180881809818108181181812818138181481815818168181781818818198182081821818228182381824818258182681827818288182981830818318183281833818348183581836818378183881839818408184181842818438184481845818468184781848818498185081851818528185381854818558185681857818588185981860818618186281863818648186581866818678186881869818708187181872818738187481875818768187781878818798188081881818828188381884818858188681887818888188981890818918189281893818948189581896818978189881899819008190181902819038190481905819068190781908819098191081911819128191381914819158191681917819188191981920819218192281923819248192581926819278192881929819308193181932819338193481935819368193781938819398194081941819428194381944819458194681947819488194981950819518195281953819548195581956819578195881959819608196181962819638196481965819668196781968819698197081971819728197381974819758197681977819788197981980819818198281983819848198581986819878198881989819908199181992819938199481995819968199781998819998200082001820028200382004820058200682007820088200982010820118201282013820148201582016820178201882019820208202182022820238202482025820268202782028820298203082031820328203382034820358203682037820388203982040820418204282043820448204582046820478204882049820508205182052820538205482055820568205782058820598206082061820628206382064820658206682067820688206982070820718207282073820748207582076820778207882079820808208182082820838208482085820868208782088820898209082091820928209382094820958209682097820988209982100821018210282103821048210582106821078210882109821108211182112821138211482115821168211782118821198212082121821228212382124821258212682127821288212982130821318213282133821348213582136821378213882139821408214182142821438214482145821468214782148821498215082151821528215382154821558215682157821588215982160821618216282163821648216582166821678216882169821708217182172821738217482175821768217782178821798218082181821828218382184821858218682187821888218982190821918219282193821948219582196821978219882199822008220182202822038220482205822068220782208822098221082211822128221382214822158221682217822188221982220822218222282223822248222582226822278222882229822308223182232822338223482235822368223782238822398224082241822428224382244822458224682247822488224982250822518225282253822548225582256822578225882259822608226182262822638226482265822668226782268822698227082271822728227382274822758227682277822788227982280822818228282283822848228582286822878228882289822908229182292822938229482295822968229782298822998230082301823028230382304823058230682307823088230982310823118231282313823148231582316823178231882319823208232182322823238232482325823268232782328823298233082331823328233382334823358233682337823388233982340823418234282343823448234582346823478234882349823508235182352823538235482355823568235782358823598236082361823628236382364823658236682367823688236982370823718237282373823748237582376823778237882379823808238182382823838238482385823868238782388823898239082391823928239382394823958239682397823988239982400824018240282403824048240582406824078240882409824108241182412824138241482415824168241782418824198242082421824228242382424824258242682427824288242982430824318243282433824348243582436824378243882439824408244182442824438244482445824468244782448824498245082451824528245382454824558245682457824588245982460824618246282463824648246582466824678246882469824708247182472824738247482475824768247782478824798248082481824828248382484824858248682487824888248982490824918249282493824948249582496824978249882499825008250182502825038250482505825068250782508825098251082511825128251382514825158251682517825188251982520825218252282523825248252582526825278252882529825308253182532825338253482535825368253782538825398254082541825428254382544825458254682547825488254982550825518255282553825548255582556825578255882559825608256182562825638256482565825668256782568825698257082571825728257382574825758257682577825788257982580825818258282583825848258582586825878258882589825908259182592825938259482595825968259782598825998260082601826028260382604826058260682607826088260982610826118261282613826148261582616826178261882619826208262182622826238262482625826268262782628826298263082631826328263382634826358263682637826388263982640826418264282643826448264582646826478264882649826508265182652826538265482655826568265782658826598266082661826628266382664826658266682667826688266982670826718267282673826748267582676826778267882679826808268182682826838268482685826868268782688826898269082691826928269382694826958269682697826988269982700827018270282703827048270582706827078270882709827108271182712827138271482715827168271782718827198272082721827228272382724827258272682727827288272982730827318273282733827348273582736827378273882739827408274182742827438274482745827468274782748827498275082751827528275382754827558275682757827588275982760827618276282763827648276582766827678276882769827708277182772827738277482775827768277782778827798278082781827828278382784827858278682787827888278982790827918279282793827948279582796827978279882799828008280182802828038280482805828068280782808828098281082811828128281382814828158281682817828188281982820828218282282823828248282582826828278282882829828308283182832828338283482835828368283782838828398284082841828428284382844828458284682847828488284982850828518285282853828548285582856828578285882859828608286182862828638286482865828668286782868828698287082871828728287382874828758287682877828788287982880828818288282883828848288582886828878288882889828908289182892828938289482895828968289782898828998290082901829028290382904829058290682907829088290982910829118291282913829148291582916829178291882919829208292182922829238292482925829268292782928829298293082931829328293382934829358293682937829388293982940829418294282943829448294582946829478294882949829508295182952829538295482955829568295782958829598296082961829628296382964829658296682967829688296982970829718297282973829748297582976829778297882979829808298182982829838298482985829868298782988829898299082991829928299382994829958299682997829988299983000830018300283003830048300583006830078300883009830108301183012830138301483015830168301783018830198302083021830228302383024830258302683027830288302983030830318303283033830348303583036830378303883039830408304183042830438304483045830468304783048830498305083051830528305383054830558305683057830588305983060830618306283063830648306583066830678306883069830708307183072830738307483075830768307783078830798308083081830828308383084830858308683087830888308983090830918309283093830948309583096830978309883099831008310183102831038310483105831068310783108831098311083111831128311383114831158311683117831188311983120831218312283123831248312583126831278312883129831308313183132831338313483135831368313783138831398314083141831428314383144831458314683147831488314983150831518315283153831548315583156831578315883159831608316183162831638316483165831668316783168831698317083171831728317383174831758317683177831788317983180831818318283183831848318583186831878318883189831908319183192831938319483195831968319783198831998320083201832028320383204832058320683207832088320983210832118321283213832148321583216832178321883219832208322183222832238322483225832268322783228832298323083231832328323383234832358323683237832388323983240832418324283243832448324583246832478324883249832508325183252832538325483255832568325783258832598326083261832628326383264832658326683267832688326983270832718327283273832748327583276832778327883279832808328183282832838328483285832868328783288832898329083291832928329383294832958329683297832988329983300833018330283303833048330583306833078330883309833108331183312833138331483315833168331783318833198332083321833228332383324833258332683327833288332983330833318333283333833348333583336833378333883339833408334183342833438334483345833468334783348833498335083351833528335383354833558335683357833588335983360833618336283363833648336583366833678336883369833708337183372833738337483375833768337783378833798338083381833828338383384833858338683387833888338983390833918339283393833948339583396833978339883399834008340183402834038340483405834068340783408834098341083411834128341383414834158341683417834188341983420834218342283423834248342583426834278342883429834308343183432834338343483435834368343783438834398344083441834428344383444834458344683447834488344983450834518345283453834548345583456834578345883459834608346183462834638346483465834668346783468834698347083471834728347383474834758347683477834788347983480834818348283483834848348583486834878348883489834908349183492834938349483495834968349783498834998350083501835028350383504835058350683507835088350983510835118351283513835148351583516835178351883519835208352183522835238352483525835268352783528835298353083531835328353383534835358353683537835388353983540835418354283543835448354583546835478354883549835508355183552835538355483555835568355783558835598356083561835628356383564835658356683567835688356983570835718357283573835748357583576835778357883579835808358183582835838358483585835868358783588835898359083591835928359383594835958359683597835988359983600836018360283603836048360583606836078360883609836108361183612836138361483615836168361783618836198362083621836228362383624836258362683627836288362983630836318363283633836348363583636836378363883639836408364183642836438364483645836468364783648836498365083651836528365383654836558365683657836588365983660836618366283663836648366583666836678366883669836708367183672836738367483675836768367783678836798368083681836828368383684836858368683687836888368983690836918369283693836948369583696836978369883699837008370183702837038370483705837068370783708837098371083711837128371383714837158371683717837188371983720837218372283723837248372583726837278372883729837308373183732837338373483735837368373783738837398374083741837428374383744837458374683747837488374983750837518375283753837548375583756837578375883759837608376183762837638376483765837668376783768837698377083771837728377383774837758377683777837788377983780837818378283783837848378583786837878378883789837908379183792837938379483795837968379783798837998380083801838028380383804838058380683807838088380983810838118381283813838148381583816838178381883819838208382183822838238382483825838268382783828838298383083831838328383383834838358383683837838388383983840838418384283843838448384583846838478384883849838508385183852838538385483855838568385783858838598386083861838628386383864838658386683867838688386983870838718387283873838748387583876838778387883879838808388183882838838388483885838868388783888838898389083891838928389383894838958389683897838988389983900839018390283903839048390583906839078390883909839108391183912839138391483915839168391783918839198392083921839228392383924839258392683927839288392983930839318393283933839348393583936839378393883939839408394183942839438394483945839468394783948839498395083951839528395383954839558395683957839588395983960839618396283963839648396583966839678396883969839708397183972839738397483975839768397783978839798398083981839828398383984839858398683987839888398983990839918399283993839948399583996839978399883999840008400184002840038400484005840068400784008840098401084011840128401384014840158401684017840188401984020840218402284023840248402584026840278402884029840308403184032840338403484035840368403784038840398404084041840428404384044840458404684047840488404984050840518405284053840548405584056840578405884059840608406184062840638406484065840668406784068840698407084071840728407384074840758407684077840788407984080840818408284083840848408584086840878408884089840908409184092840938409484095840968409784098840998410084101841028410384104841058410684107841088410984110841118411284113841148411584116841178411884119841208412184122841238412484125841268412784128841298413084131841328413384134841358413684137841388413984140841418414284143841448414584146841478414884149841508415184152841538415484155841568415784158841598416084161841628416384164841658416684167841688416984170841718417284173841748417584176841778417884179841808418184182841838418484185841868418784188841898419084191841928419384194841958419684197841988419984200842018420284203842048420584206842078420884209842108421184212842138421484215842168421784218842198422084221842228422384224842258422684227842288422984230842318423284233842348423584236842378423884239842408424184242842438424484245842468424784248842498425084251842528425384254842558425684257842588425984260842618426284263842648426584266842678426884269842708427184272842738427484275842768427784278842798428084281842828428384284842858428684287842888428984290842918429284293842948429584296842978429884299843008430184302843038430484305843068430784308843098431084311843128431384314843158431684317843188431984320843218432284323843248432584326843278432884329843308433184332843338433484335843368433784338843398434084341843428434384344843458434684347843488434984350843518435284353843548435584356843578435884359843608436184362843638436484365843668436784368843698437084371843728437384374843758437684377843788437984380843818438284383843848438584386843878438884389843908439184392843938439484395843968439784398843998440084401844028440384404844058440684407844088440984410844118441284413844148441584416844178441884419844208442184422844238442484425844268442784428844298443084431844328443384434844358443684437844388443984440844418444284443844448444584446844478444884449844508445184452844538445484455844568445784458844598446084461844628446384464844658446684467844688446984470844718447284473844748447584476844778447884479844808448184482844838448484485844868448784488844898449084491844928449384494844958449684497844988449984500845018450284503845048450584506845078450884509845108451184512845138451484515845168451784518845198452084521845228452384524845258452684527845288452984530845318453284533845348453584536845378453884539845408454184542845438454484545845468454784548845498455084551845528455384554845558455684557845588455984560845618456284563845648456584566845678456884569845708457184572845738457484575845768457784578845798458084581845828458384584845858458684587845888458984590845918459284593845948459584596845978459884599846008460184602846038460484605846068460784608846098461084611846128461384614846158461684617846188461984620846218462284623846248462584626846278462884629846308463184632846338463484635846368463784638846398464084641846428464384644846458464684647846488464984650846518465284653846548465584656846578465884659846608466184662846638466484665846668466784668846698467084671846728467384674846758467684677846788467984680846818468284683846848468584686846878468884689846908469184692846938469484695846968469784698846998470084701847028470384704847058470684707847088470984710847118471284713847148471584716847178471884719847208472184722847238472484725847268472784728847298473084731847328473384734847358473684737847388473984740847418474284743847448474584746847478474884749847508475184752847538475484755847568475784758847598476084761847628476384764847658476684767847688476984770847718477284773847748477584776847778477884779847808478184782847838478484785847868478784788847898479084791847928479384794847958479684797847988479984800848018480284803848048480584806848078480884809848108481184812848138481484815848168481784818848198482084821848228482384824848258482684827848288482984830848318483284833848348483584836848378483884839848408484184842848438484484845848468484784848848498485084851848528485384854848558485684857848588485984860848618486284863848648486584866848678486884869848708487184872848738487484875848768487784878848798488084881848828488384884848858488684887848888488984890848918489284893848948489584896848978489884899849008490184902849038490484905849068490784908849098491084911849128491384914849158491684917849188491984920849218492284923849248492584926849278492884929849308493184932849338493484935849368493784938849398494084941849428494384944849458494684947849488494984950849518495284953849548495584956849578495884959849608496184962849638496484965849668496784968849698497084971849728497384974849758497684977849788497984980849818498284983849848498584986849878498884989849908499184992849938499484995849968499784998849998500085001850028500385004850058500685007850088500985010850118501285013850148501585016850178501885019850208502185022850238502485025850268502785028850298503085031850328503385034850358503685037850388503985040850418504285043850448504585046850478504885049850508505185052850538505485055850568505785058850598506085061850628506385064850658506685067850688506985070850718507285073850748507585076850778507885079850808508185082850838508485085850868508785088850898509085091850928509385094850958509685097850988509985100851018510285103851048510585106851078510885109851108511185112851138511485115851168511785118851198512085121851228512385124851258512685127851288512985130851318513285133851348513585136851378513885139851408514185142851438514485145851468514785148851498515085151851528515385154851558515685157851588515985160851618516285163851648516585166851678516885169851708517185172851738517485175851768517785178851798518085181851828518385184851858518685187851888518985190851918519285193851948519585196851978519885199852008520185202852038520485205852068520785208852098521085211852128521385214852158521685217852188521985220852218522285223852248522585226852278522885229852308523185232852338523485235852368523785238852398524085241852428524385244852458524685247852488524985250852518525285253852548525585256852578525885259852608526185262852638526485265852668526785268852698527085271852728527385274852758527685277852788527985280852818528285283852848528585286852878528885289852908529185292852938529485295852968529785298852998530085301853028530385304853058530685307853088530985310853118531285313853148531585316853178531885319853208532185322853238532485325853268532785328853298533085331853328533385334853358533685337853388533985340853418534285343853448534585346853478534885349853508535185352853538535485355853568535785358853598536085361853628536385364853658536685367853688536985370853718537285373853748537585376853778537885379853808538185382853838538485385853868538785388853898539085391853928539385394853958539685397853988539985400854018540285403854048540585406854078540885409854108541185412854138541485415854168541785418854198542085421854228542385424854258542685427854288542985430854318543285433854348543585436854378543885439854408544185442854438544485445854468544785448854498545085451854528545385454854558545685457854588545985460854618546285463854648546585466854678546885469854708547185472854738547485475854768547785478854798548085481854828548385484854858548685487854888548985490854918549285493854948549585496854978549885499855008550185502855038550485505855068550785508855098551085511855128551385514855158551685517855188551985520855218552285523855248552585526855278552885529855308553185532855338553485535855368553785538855398554085541855428554385544855458554685547855488554985550855518555285553855548555585556855578555885559855608556185562855638556485565855668556785568855698557085571855728557385574855758557685577855788557985580855818558285583855848558585586855878558885589855908559185592855938559485595855968559785598855998560085601856028560385604856058560685607856088560985610856118561285613856148561585616856178561885619856208562185622856238562485625856268562785628856298563085631856328563385634856358563685637856388563985640856418564285643856448564585646856478564885649856508565185652856538565485655856568565785658856598566085661856628566385664856658566685667856688566985670856718567285673856748567585676856778567885679856808568185682856838568485685856868568785688856898569085691856928569385694856958569685697856988569985700857018570285703857048570585706857078570885709857108571185712857138571485715857168571785718857198572085721857228572385724857258572685727857288572985730857318573285733857348573585736857378573885739857408574185742857438574485745857468574785748857498575085751857528575385754857558575685757857588575985760857618576285763857648576585766857678576885769857708577185772857738577485775857768577785778857798578085781857828578385784857858578685787857888578985790857918579285793857948579585796857978579885799858008580185802858038580485805858068580785808858098581085811858128581385814858158581685817858188581985820858218582285823858248582585826858278582885829858308583185832858338583485835858368583785838858398584085841858428584385844858458584685847858488584985850858518585285853858548585585856858578585885859858608586185862858638586485865858668586785868858698587085871858728587385874858758587685877858788587985880858818588285883858848588585886858878588885889858908589185892858938589485895858968589785898858998590085901859028590385904859058590685907859088590985910859118591285913859148591585916859178591885919859208592185922859238592485925859268592785928859298593085931859328593385934859358593685937859388593985940859418594285943859448594585946859478594885949859508595185952859538595485955859568595785958859598596085961859628596385964859658596685967859688596985970859718597285973859748597585976859778597885979859808598185982859838598485985859868598785988859898599085991859928599385994859958599685997859988599986000860018600286003860048600586006860078600886009860108601186012860138601486015860168601786018860198602086021860228602386024860258602686027860288602986030860318603286033860348603586036860378603886039860408604186042860438604486045860468604786048860498605086051860528605386054860558605686057860588605986060860618606286063860648606586066860678606886069860708607186072860738607486075860768607786078860798608086081860828608386084860858608686087860888608986090860918609286093860948609586096860978609886099861008610186102861038610486105861068610786108861098611086111861128611386114861158611686117861188611986120861218612286123861248612586126861278612886129861308613186132861338613486135861368613786138861398614086141861428614386144861458614686147861488614986150861518615286153861548615586156861578615886159861608616186162861638616486165861668616786168861698617086171861728617386174861758617686177861788617986180861818618286183861848618586186861878618886189861908619186192861938619486195861968619786198861998620086201862028620386204862058620686207862088620986210862118621286213862148621586216862178621886219862208622186222862238622486225862268622786228862298623086231862328623386234862358623686237862388623986240862418624286243862448624586246862478624886249862508625186252862538625486255862568625786258862598626086261862628626386264862658626686267862688626986270862718627286273862748627586276862778627886279862808628186282862838628486285862868628786288862898629086291862928629386294862958629686297862988629986300863018630286303863048630586306863078630886309863108631186312863138631486315863168631786318863198632086321863228632386324863258632686327863288632986330863318633286333863348633586336863378633886339863408634186342863438634486345863468634786348863498635086351863528635386354863558635686357863588635986360863618636286363863648636586366863678636886369863708637186372863738637486375863768637786378863798638086381863828638386384863858638686387863888638986390863918639286393863948639586396863978639886399864008640186402864038640486405864068640786408864098641086411864128641386414864158641686417864188641986420864218642286423864248642586426864278642886429864308643186432864338643486435864368643786438864398644086441864428644386444864458644686447864488644986450864518645286453864548645586456864578645886459864608646186462864638646486465864668646786468864698647086471864728647386474864758647686477864788647986480864818648286483864848648586486864878648886489864908649186492864938649486495864968649786498864998650086501865028650386504865058650686507865088650986510865118651286513865148651586516865178651886519865208652186522865238652486525865268652786528865298653086531865328653386534865358653686537865388653986540865418654286543865448654586546865478654886549865508655186552865538655486555865568655786558865598656086561865628656386564865658656686567865688656986570865718657286573865748657586576865778657886579865808658186582865838658486585865868658786588865898659086591865928659386594865958659686597865988659986600866018660286603866048660586606866078660886609866108661186612866138661486615866168661786618866198662086621866228662386624866258662686627866288662986630866318663286633866348663586636866378663886639866408664186642866438664486645866468664786648866498665086651866528665386654866558665686657866588665986660866618666286663866648666586666866678666886669866708667186672866738667486675866768667786678866798668086681866828668386684866858668686687866888668986690866918669286693866948669586696866978669886699867008670186702867038670486705867068670786708867098671086711867128671386714867158671686717867188671986720867218672286723867248672586726867278672886729867308673186732867338673486735867368673786738867398674086741867428674386744867458674686747867488674986750867518675286753867548675586756867578675886759867608676186762867638676486765867668676786768867698677086771867728677386774867758677686777867788677986780867818678286783867848678586786867878678886789867908679186792867938679486795867968679786798867998680086801868028680386804868058680686807868088680986810868118681286813868148681586816868178681886819868208682186822868238682486825868268682786828868298683086831868328683386834868358683686837868388683986840868418684286843868448684586846868478684886849868508685186852868538685486855868568685786858868598686086861868628686386864868658686686867868688686986870868718687286873868748687586876868778687886879868808688186882868838688486885868868688786888868898689086891868928689386894868958689686897868988689986900869018690286903869048690586906869078690886909869108691186912869138691486915869168691786918869198692086921869228692386924869258692686927869288692986930869318693286933869348693586936869378693886939869408694186942869438694486945869468694786948869498695086951869528695386954869558695686957869588695986960869618696286963869648696586966869678696886969869708697186972869738697486975869768697786978869798698086981869828698386984869858698686987869888698986990869918699286993869948699586996869978699886999870008700187002870038700487005870068700787008870098701087011870128701387014870158701687017870188701987020870218702287023870248702587026870278702887029870308703187032870338703487035870368703787038870398704087041870428704387044870458704687047870488704987050870518705287053870548705587056870578705887059870608706187062870638706487065870668706787068870698707087071870728707387074870758707687077870788707987080870818708287083870848708587086870878708887089870908709187092870938709487095870968709787098870998710087101871028710387104871058710687107871088710987110871118711287113871148711587116871178711887119871208712187122871238712487125871268712787128871298713087131871328713387134871358713687137871388713987140871418714287143871448714587146871478714887149871508715187152871538715487155871568715787158871598716087161871628716387164871658716687167871688716987170871718717287173871748717587176871778717887179871808718187182871838718487185871868718787188871898719087191871928719387194871958719687197871988719987200872018720287203872048720587206872078720887209872108721187212872138721487215872168721787218872198722087221872228722387224872258722687227872288722987230872318723287233872348723587236872378723887239872408724187242872438724487245872468724787248872498725087251872528725387254872558725687257872588725987260872618726287263872648726587266872678726887269872708727187272872738727487275872768727787278872798728087281872828728387284872858728687287872888728987290872918729287293872948729587296872978729887299873008730187302873038730487305873068730787308873098731087311873128731387314873158731687317873188731987320873218732287323873248732587326873278732887329873308733187332873338733487335873368733787338873398734087341873428734387344873458734687347873488734987350873518735287353873548735587356873578735887359873608736187362873638736487365873668736787368873698737087371873728737387374873758737687377873788737987380873818738287383873848738587386873878738887389873908739187392873938739487395873968739787398873998740087401874028740387404874058740687407874088740987410874118741287413874148741587416874178741887419874208742187422874238742487425874268742787428874298743087431874328743387434874358743687437874388743987440874418744287443874448744587446874478744887449874508745187452874538745487455874568745787458874598746087461874628746387464874658746687467874688746987470874718747287473874748747587476874778747887479874808748187482874838748487485874868748787488874898749087491874928749387494874958749687497874988749987500875018750287503875048750587506875078750887509875108751187512875138751487515875168751787518875198752087521875228752387524875258752687527875288752987530875318753287533875348753587536875378753887539875408754187542875438754487545875468754787548875498755087551875528755387554875558755687557875588755987560875618756287563875648756587566875678756887569875708757187572875738757487575875768757787578875798758087581875828758387584875858758687587875888758987590875918759287593875948759587596875978759887599876008760187602876038760487605876068760787608876098761087611876128761387614876158761687617876188761987620876218762287623876248762587626876278762887629876308763187632876338763487635876368763787638876398764087641876428764387644876458764687647876488764987650876518765287653876548765587656876578765887659876608766187662876638766487665876668766787668876698767087671876728767387674876758767687677876788767987680876818768287683876848768587686876878768887689876908769187692876938769487695876968769787698876998770087701877028770387704877058770687707877088770987710877118771287713877148771587716877178771887719877208772187722877238772487725877268772787728877298773087731877328773387734877358773687737877388773987740877418774287743877448774587746877478774887749877508775187752877538775487755877568775787758877598776087761877628776387764877658776687767877688776987770877718777287773877748777587776877778777887779877808778187782877838778487785877868778787788877898779087791877928779387794877958779687797877988779987800878018780287803878048780587806878078780887809878108781187812878138781487815878168781787818878198782087821878228782387824878258782687827878288782987830878318783287833878348783587836878378783887839878408784187842878438784487845878468784787848878498785087851878528785387854878558785687857878588785987860878618786287863878648786587866878678786887869878708787187872878738787487875878768787787878878798788087881878828788387884878858788687887878888788987890878918789287893878948789587896878978789887899879008790187902879038790487905879068790787908879098791087911879128791387914879158791687917879188791987920879218792287923879248792587926879278792887929879308793187932879338793487935879368793787938879398794087941879428794387944879458794687947879488794987950879518795287953879548795587956879578795887959879608796187962879638796487965879668796787968879698797087971879728797387974879758797687977879788797987980879818798287983879848798587986879878798887989879908799187992879938799487995879968799787998879998800088001880028800388004880058800688007880088800988010880118801288013880148801588016880178801888019880208802188022880238802488025880268802788028880298803088031880328803388034880358803688037880388803988040880418804288043880448804588046880478804888049880508805188052880538805488055880568805788058880598806088061880628806388064880658806688067880688806988070880718807288073880748807588076880778807888079880808808188082880838808488085880868808788088880898809088091880928809388094880958809688097880988809988100881018810288103881048810588106881078810888109881108811188112881138811488115881168811788118881198812088121881228812388124881258812688127881288812988130881318813288133881348813588136881378813888139881408814188142881438814488145881468814788148881498815088151881528815388154881558815688157881588815988160881618816288163881648816588166881678816888169881708817188172881738817488175881768817788178881798818088181881828818388184881858818688187881888818988190881918819288193881948819588196881978819888199882008820188202882038820488205882068820788208882098821088211882128821388214882158821688217882188821988220882218822288223882248822588226882278822888229882308823188232882338823488235882368823788238882398824088241882428824388244882458824688247882488824988250882518825288253882548825588256882578825888259882608826188262882638826488265882668826788268882698827088271882728827388274882758827688277882788827988280882818828288283882848828588286882878828888289882908829188292882938829488295882968829788298882998830088301883028830388304883058830688307883088830988310883118831288313883148831588316883178831888319883208832188322883238832488325883268832788328883298833088331883328833388334883358833688337883388833988340883418834288343883448834588346883478834888349883508835188352883538835488355883568835788358883598836088361883628836388364883658836688367883688836988370883718837288373883748837588376883778837888379883808838188382883838838488385883868838788388883898839088391883928839388394883958839688397883988839988400884018840288403884048840588406884078840888409884108841188412884138841488415884168841788418884198842088421884228842388424884258842688427884288842988430884318843288433884348843588436884378843888439884408844188442884438844488445884468844788448884498845088451884528845388454884558845688457884588845988460884618846288463884648846588466884678846888469884708847188472884738847488475884768847788478884798848088481884828848388484884858848688487884888848988490884918849288493884948849588496884978849888499885008850188502885038850488505885068850788508885098851088511885128851388514885158851688517885188851988520885218852288523885248852588526885278852888529885308853188532885338853488535885368853788538885398854088541885428854388544885458854688547885488854988550885518855288553885548855588556885578855888559885608856188562885638856488565885668856788568885698857088571885728857388574885758857688577885788857988580885818858288583885848858588586885878858888589885908859188592885938859488595885968859788598885998860088601886028860388604886058860688607886088860988610886118861288613886148861588616886178861888619886208862188622886238862488625886268862788628886298863088631886328863388634886358863688637886388863988640886418864288643886448864588646886478864888649886508865188652886538865488655886568865788658886598866088661886628866388664886658866688667886688866988670886718867288673886748867588676886778867888679886808868188682886838868488685886868868788688886898869088691886928869388694886958869688697886988869988700887018870288703887048870588706887078870888709887108871188712887138871488715887168871788718887198872088721887228872388724887258872688727887288872988730887318873288733887348873588736887378873888739887408874188742887438874488745887468874788748887498875088751887528875388754887558875688757887588875988760887618876288763887648876588766887678876888769887708877188772887738877488775887768877788778887798878088781887828878388784887858878688787887888878988790887918879288793887948879588796887978879888799888008880188802888038880488805888068880788808888098881088811888128881388814888158881688817888188881988820888218882288823888248882588826888278882888829888308883188832888338883488835888368883788838888398884088841888428884388844888458884688847888488884988850888518885288853888548885588856888578885888859888608886188862888638886488865888668886788868888698887088871888728887388874888758887688877888788887988880888818888288883888848888588886888878888888889888908889188892888938889488895888968889788898888998890088901889028890388904889058890688907889088890988910889118891288913889148891588916889178891888919889208892188922889238892488925889268892788928889298893088931889328893388934889358893688937889388893988940889418894288943889448894588946889478894888949889508895188952889538895488955889568895788958889598896088961889628896388964889658896688967889688896988970889718897288973889748897588976889778897888979889808898188982889838898488985889868898788988889898899088991889928899388994889958899688997889988899989000890018900289003890048900589006890078900889009890108901189012890138901489015890168901789018890198902089021890228902389024890258902689027890288902989030890318903289033890348903589036890378903889039890408904189042890438904489045890468904789048890498905089051890528905389054890558905689057890588905989060890618906289063890648906589066890678906889069890708907189072890738907489075890768907789078890798908089081890828908389084890858908689087890888908989090890918909289093890948909589096890978909889099891008910189102891038910489105891068910789108891098911089111891128911389114891158911689117891188911989120891218912289123891248912589126891278912889129891308913189132891338913489135891368913789138891398914089141891428914389144891458914689147891488914989150891518915289153891548915589156891578915889159891608916189162891638916489165891668916789168891698917089171891728917389174891758917689177891788917989180891818918289183891848918589186891878918889189891908919189192891938919489195891968919789198891998920089201892028920389204892058920689207892088920989210892118921289213892148921589216892178921889219892208922189222892238922489225892268922789228892298923089231892328923389234892358923689237892388923989240892418924289243892448924589246892478924889249892508925189252892538925489255892568925789258892598926089261892628926389264892658926689267892688926989270892718927289273892748927589276892778927889279892808928189282892838928489285892868928789288892898929089291892928929389294892958929689297892988929989300893018930289303893048930589306893078930889309893108931189312893138931489315893168931789318893198932089321893228932389324893258932689327893288932989330893318933289333893348933589336893378933889339893408934189342893438934489345893468934789348893498935089351893528935389354893558935689357893588935989360893618936289363893648936589366893678936889369893708937189372893738937489375893768937789378893798938089381893828938389384893858938689387893888938989390893918939289393893948939589396893978939889399894008940189402894038940489405894068940789408894098941089411894128941389414894158941689417894188941989420894218942289423894248942589426894278942889429894308943189432894338943489435894368943789438894398944089441894428944389444894458944689447894488944989450894518945289453894548945589456894578945889459894608946189462894638946489465894668946789468894698947089471894728947389474894758947689477894788947989480894818948289483894848948589486894878948889489894908949189492894938949489495894968949789498894998950089501895028950389504895058950689507895088950989510895118951289513895148951589516895178951889519895208952189522895238952489525895268952789528895298953089531895328953389534895358953689537895388953989540895418954289543895448954589546895478954889549895508955189552895538955489555895568955789558895598956089561895628956389564895658956689567895688956989570895718957289573895748957589576895778957889579895808958189582895838958489585895868958789588895898959089591895928959389594895958959689597895988959989600896018960289603896048960589606896078960889609896108961189612896138961489615896168961789618896198962089621896228962389624896258962689627896288962989630896318963289633896348963589636896378963889639896408964189642896438964489645896468964789648896498965089651896528965389654896558965689657896588965989660896618966289663896648966589666896678966889669896708967189672896738967489675896768967789678896798968089681896828968389684896858968689687896888968989690896918969289693896948969589696896978969889699897008970189702897038970489705897068970789708897098971089711897128971389714897158971689717897188971989720897218972289723897248972589726897278972889729897308973189732897338973489735897368973789738897398974089741897428974389744897458974689747897488974989750897518975289753897548975589756897578975889759897608976189762897638976489765897668976789768897698977089771897728977389774897758977689777897788977989780897818978289783897848978589786897878978889789897908979189792897938979489795897968979789798897998980089801898028980389804898058980689807898088980989810898118981289813898148981589816898178981889819898208982189822898238982489825898268982789828898298983089831898328983389834898358983689837898388983989840898418984289843898448984589846898478984889849898508985189852898538985489855898568985789858898598986089861898628986389864898658986689867898688986989870898718987289873898748987589876898778987889879898808988189882898838988489885898868988789888898898989089891898928989389894898958989689897898988989989900899018990289903899048990589906899078990889909899108991189912899138991489915899168991789918899198992089921899228992389924899258992689927899288992989930899318993289933899348993589936899378993889939899408994189942899438994489945899468994789948899498995089951899528995389954899558995689957899588995989960899618996289963899648996589966899678996889969899708997189972899738997489975899768997789978899798998089981899828998389984899858998689987899888998989990899918999289993899948999589996899978999889999900009000190002900039000490005900069000790008900099001090011900129001390014900159001690017900189001990020900219002290023900249002590026900279002890029900309003190032900339003490035900369003790038900399004090041900429004390044900459004690047900489004990050900519005290053900549005590056900579005890059900609006190062900639006490065900669006790068900699007090071900729007390074900759007690077900789007990080900819008290083900849008590086900879008890089900909009190092900939009490095900969009790098900999010090101901029010390104901059010690107901089010990110901119011290113901149011590116901179011890119901209012190122901239012490125901269012790128901299013090131901329013390134901359013690137901389013990140901419014290143901449014590146901479014890149901509015190152901539015490155901569015790158901599016090161901629016390164901659016690167901689016990170901719017290173901749017590176901779017890179901809018190182901839018490185901869018790188901899019090191901929019390194901959019690197901989019990200902019020290203902049020590206902079020890209902109021190212902139021490215902169021790218902199022090221902229022390224902259022690227902289022990230902319023290233902349023590236902379023890239902409024190242902439024490245902469024790248902499025090251902529025390254902559025690257902589025990260902619026290263902649026590266902679026890269902709027190272902739027490275902769027790278902799028090281902829028390284902859028690287902889028990290902919029290293902949029590296902979029890299903009030190302903039030490305903069030790308903099031090311903129031390314903159031690317903189031990320903219032290323903249032590326903279032890329903309033190332903339033490335903369033790338903399034090341903429034390344903459034690347903489034990350903519035290353903549035590356903579035890359903609036190362903639036490365903669036790368903699037090371903729037390374903759037690377903789037990380903819038290383903849038590386903879038890389903909039190392903939039490395903969039790398903999040090401904029040390404904059040690407904089040990410904119041290413904149041590416904179041890419904209042190422904239042490425904269042790428904299043090431904329043390434904359043690437904389043990440904419044290443904449044590446904479044890449904509045190452904539045490455904569045790458904599046090461904629046390464904659046690467904689046990470904719047290473904749047590476904779047890479904809048190482904839048490485904869048790488904899049090491904929049390494904959049690497904989049990500905019050290503905049050590506905079050890509905109051190512905139051490515905169051790518905199052090521905229052390524905259052690527905289052990530905319053290533905349053590536905379053890539905409054190542905439054490545905469054790548905499055090551905529055390554905559055690557905589055990560905619056290563905649056590566905679056890569905709057190572905739057490575905769057790578905799058090581905829058390584905859058690587905889058990590905919059290593905949059590596905979059890599906009060190602906039060490605906069060790608906099061090611906129061390614906159061690617906189061990620906219062290623906249062590626906279062890629906309063190632906339063490635906369063790638906399064090641906429064390644906459064690647906489064990650906519065290653906549065590656906579065890659906609066190662906639066490665906669066790668906699067090671906729067390674906759067690677906789067990680906819068290683906849068590686906879068890689906909069190692906939069490695906969069790698906999070090701907029070390704907059070690707907089070990710907119071290713907149071590716907179071890719907209072190722907239072490725907269072790728907299073090731907329073390734907359073690737907389073990740907419074290743907449074590746907479074890749907509075190752907539075490755907569075790758907599076090761907629076390764907659076690767907689076990770907719077290773907749077590776907779077890779907809078190782907839078490785907869078790788907899079090791907929079390794907959079690797907989079990800908019080290803908049080590806908079080890809908109081190812908139081490815908169081790818908199082090821908229082390824908259082690827908289082990830908319083290833908349083590836908379083890839908409084190842908439084490845908469084790848908499085090851908529085390854908559085690857908589085990860908619086290863908649086590866908679086890869908709087190872908739087490875908769087790878908799088090881908829088390884908859088690887908889088990890908919089290893908949089590896908979089890899909009090190902909039090490905909069090790908909099091090911909129091390914909159091690917909189091990920909219092290923909249092590926909279092890929909309093190932909339093490935909369093790938909399094090941909429094390944909459094690947909489094990950909519095290953909549095590956909579095890959909609096190962909639096490965909669096790968909699097090971909729097390974909759097690977909789097990980909819098290983909849098590986909879098890989909909099190992909939099490995909969099790998909999100091001910029100391004910059100691007910089100991010910119101291013910149101591016910179101891019910209102191022910239102491025910269102791028910299103091031910329103391034910359103691037910389103991040910419104291043910449104591046910479104891049910509105191052910539105491055910569105791058910599106091061910629106391064910659106691067910689106991070910719107291073910749107591076910779107891079910809108191082910839108491085910869108791088910899109091091910929109391094910959109691097910989109991100911019110291103911049110591106911079110891109911109111191112911139111491115911169111791118911199112091121911229112391124911259112691127911289112991130911319113291133911349113591136911379113891139911409114191142911439114491145911469114791148911499115091151911529115391154911559115691157911589115991160911619116291163911649116591166911679116891169911709117191172911739117491175911769117791178911799118091181911829118391184911859118691187911889118991190911919119291193911949119591196911979119891199912009120191202912039120491205912069120791208912099121091211912129121391214912159121691217912189121991220912219122291223912249122591226912279122891229912309123191232912339123491235912369123791238912399124091241912429124391244912459124691247912489124991250912519125291253912549125591256912579125891259912609126191262912639126491265912669126791268912699127091271912729127391274912759127691277912789127991280912819128291283912849128591286912879128891289912909129191292912939129491295912969129791298912999130091301913029130391304913059130691307913089130991310913119131291313913149131591316913179131891319913209132191322913239132491325913269132791328913299133091331913329133391334913359133691337913389133991340913419134291343913449134591346913479134891349913509135191352913539135491355913569135791358913599136091361913629136391364913659136691367913689136991370913719137291373913749137591376913779137891379913809138191382913839138491385913869138791388913899139091391913929139391394913959139691397913989139991400914019140291403914049140591406914079140891409914109141191412914139141491415914169141791418914199142091421914229142391424914259142691427914289142991430914319143291433914349143591436914379143891439914409144191442914439144491445914469144791448914499145091451914529145391454914559145691457914589145991460914619146291463914649146591466914679146891469914709147191472914739147491475914769147791478914799148091481914829148391484914859148691487914889148991490914919149291493914949149591496914979149891499915009150191502915039150491505915069150791508915099151091511915129151391514915159151691517915189151991520915219152291523915249152591526915279152891529915309153191532915339153491535915369153791538915399154091541915429154391544915459154691547915489154991550915519155291553915549155591556915579155891559915609156191562915639156491565915669156791568915699157091571915729157391574915759157691577915789157991580915819158291583915849158591586915879158891589915909159191592915939159491595915969159791598915999160091601916029160391604916059160691607916089160991610916119161291613916149161591616916179161891619916209162191622916239162491625916269162791628916299163091631916329163391634916359163691637916389163991640916419164291643916449164591646916479164891649916509165191652916539165491655916569165791658916599166091661916629166391664916659166691667916689166991670916719167291673916749167591676916779167891679916809168191682916839168491685916869168791688916899169091691916929169391694916959169691697916989169991700917019170291703917049170591706917079170891709917109171191712917139171491715917169171791718917199172091721917229172391724917259172691727917289172991730917319173291733917349173591736917379173891739917409174191742917439174491745917469174791748917499175091751917529175391754917559175691757917589175991760917619176291763917649176591766917679176891769917709177191772917739177491775917769177791778917799178091781917829178391784917859178691787917889178991790917919179291793917949179591796917979179891799918009180191802918039180491805918069180791808918099181091811918129181391814918159181691817918189181991820918219182291823918249182591826918279182891829918309183191832918339183491835918369183791838918399184091841918429184391844918459184691847918489184991850918519185291853918549185591856918579185891859918609186191862918639186491865918669186791868918699187091871918729187391874918759187691877918789187991880918819188291883918849188591886918879188891889918909189191892918939189491895918969189791898918999190091901919029190391904919059190691907919089190991910919119191291913919149191591916919179191891919919209192191922919239192491925919269192791928919299193091931919329193391934919359193691937919389193991940919419194291943919449194591946919479194891949919509195191952919539195491955919569195791958919599196091961919629196391964919659196691967919689196991970919719197291973919749197591976919779197891979919809198191982919839198491985919869198791988919899199091991919929199391994919959199691997919989199992000920019200292003920049200592006920079200892009920109201192012920139201492015920169201792018920199202092021920229202392024920259202692027920289202992030920319203292033920349203592036920379203892039920409204192042920439204492045920469204792048920499205092051920529205392054920559205692057920589205992060920619206292063920649206592066920679206892069920709207192072920739207492075920769207792078920799208092081920829208392084920859208692087920889208992090920919209292093920949209592096920979209892099921009210192102921039210492105921069210792108921099211092111921129211392114921159211692117921189211992120921219212292123921249212592126921279212892129921309213192132921339213492135921369213792138921399214092141921429214392144921459214692147921489214992150921519215292153921549215592156921579215892159921609216192162921639216492165921669216792168921699217092171921729217392174921759217692177921789217992180921819218292183921849218592186921879218892189921909219192192921939219492195921969219792198921999220092201922029220392204922059220692207922089220992210922119221292213922149221592216922179221892219922209222192222922239222492225922269222792228922299223092231922329223392234922359223692237922389223992240922419224292243922449224592246922479224892249922509225192252922539225492255922569225792258922599226092261922629226392264922659226692267922689226992270922719227292273922749227592276922779227892279922809228192282922839228492285922869228792288922899229092291922929229392294922959229692297922989229992300923019230292303923049230592306923079230892309923109231192312923139231492315923169231792318923199232092321923229232392324923259232692327923289232992330923319233292333923349233592336923379233892339923409234192342923439234492345923469234792348923499235092351923529235392354923559235692357923589235992360923619236292363923649236592366923679236892369923709237192372923739237492375923769237792378923799238092381923829238392384923859238692387923889238992390923919239292393923949239592396923979239892399924009240192402924039240492405924069240792408924099241092411924129241392414924159241692417924189241992420924219242292423924249242592426924279242892429924309243192432924339243492435924369243792438924399244092441924429244392444924459244692447924489244992450924519245292453924549245592456924579245892459924609246192462924639246492465924669246792468924699247092471924729247392474924759247692477924789247992480924819248292483924849248592486924879248892489924909249192492924939249492495924969249792498924999250092501925029250392504925059250692507925089250992510925119251292513925149251592516925179251892519925209252192522925239252492525925269252792528925299253092531925329253392534925359253692537925389253992540925419254292543925449254592546925479254892549925509255192552925539255492555925569255792558925599256092561925629256392564925659256692567925689256992570925719257292573925749257592576925779257892579925809258192582925839258492585925869258792588925899259092591925929259392594925959259692597925989259992600926019260292603926049260592606926079260892609926109261192612926139261492615926169261792618926199262092621926229262392624926259262692627926289262992630926319263292633926349263592636926379263892639926409264192642926439264492645926469264792648926499265092651926529265392654926559265692657926589265992660926619266292663926649266592666926679266892669926709267192672926739267492675926769267792678926799268092681926829268392684926859268692687926889268992690926919269292693926949269592696926979269892699927009270192702927039270492705927069270792708927099271092711927129271392714927159271692717927189271992720927219272292723927249272592726927279272892729927309273192732927339273492735927369273792738927399274092741927429274392744927459274692747927489274992750927519275292753927549275592756927579275892759927609276192762927639276492765927669276792768927699277092771927729277392774927759277692777927789277992780927819278292783927849278592786927879278892789927909279192792927939279492795927969279792798927999280092801928029280392804928059280692807928089280992810928119281292813928149281592816928179281892819928209282192822928239282492825928269282792828928299283092831928329283392834928359283692837928389283992840928419284292843928449284592846928479284892849928509285192852928539285492855928569285792858928599286092861928629286392864928659286692867928689286992870928719287292873928749287592876928779287892879928809288192882928839288492885928869288792888928899289092891928929289392894928959289692897928989289992900929019290292903929049290592906929079290892909929109291192912929139291492915929169291792918929199292092921929229292392924929259292692927929289292992930929319293292933929349293592936929379293892939929409294192942929439294492945929469294792948929499295092951929529295392954929559295692957929589295992960929619296292963929649296592966929679296892969929709297192972929739297492975929769297792978929799298092981929829298392984929859298692987929889298992990929919299292993929949299592996929979299892999930009300193002930039300493005930069300793008930099301093011930129301393014930159301693017930189301993020930219302293023930249302593026930279302893029930309303193032930339303493035930369303793038930399304093041930429304393044930459304693047930489304993050930519305293053930549305593056930579305893059930609306193062930639306493065930669306793068930699307093071930729307393074930759307693077930789307993080930819308293083930849308593086930879308893089930909309193092930939309493095
  1. var __decorate=this&&this.__decorate||function(e,t,r,c){var o,f=arguments.length,n=f<3?t:null===c?c=Object.getOwnPropertyDescriptor(t,r):c;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)n=Reflect.decorate(e,t,r,c);else for(var l=e.length-1;l>=0;l--)(o=e[l])&&(n=(f<3?o(n):f>3?o(t,r,n):o(t,r))||n);return f>3&&n&&Object.defineProperty(t,r,n),n};
  2. var __extends=this&&this.__extends||function(){var t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,o){t.__proto__=o}||function(t,o){for(var n in o)o.hasOwnProperty(n)&&(t[n]=o[n])};return function(o,n){function r(){this.constructor=o}t(o,n),o.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();
  3. var BABYLON;
  4. (function (BABYLON) {
  5. /**
  6. * EffectFallbacks can be used to add fallbacks (properties to disable) to certain properties when desired to improve performance.
  7. * (Eg. Start at high quality with reflection and fog, if fps is low, remove reflection, if still low remove fog)
  8. */
  9. var EffectFallbacks = /** @class */ (function () {
  10. function EffectFallbacks() {
  11. this._defines = {};
  12. this._currentRank = 32;
  13. this._maxRank = -1;
  14. }
  15. /**
  16. * Removes the fallback from the bound mesh.
  17. */
  18. EffectFallbacks.prototype.unBindMesh = function () {
  19. this._mesh = null;
  20. };
  21. /**
  22. * Adds a fallback on the specified property.
  23. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  24. * @param define The name of the define in the shader
  25. */
  26. EffectFallbacks.prototype.addFallback = function (rank, define) {
  27. if (!this._defines[rank]) {
  28. if (rank < this._currentRank) {
  29. this._currentRank = rank;
  30. }
  31. if (rank > this._maxRank) {
  32. this._maxRank = rank;
  33. }
  34. this._defines[rank] = new Array();
  35. }
  36. this._defines[rank].push(define);
  37. };
  38. /**
  39. * Sets the mesh to use CPU skinning when needing to fallback.
  40. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  41. * @param mesh The mesh to use the fallbacks.
  42. */
  43. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  44. this._mesh = mesh;
  45. if (rank < this._currentRank) {
  46. this._currentRank = rank;
  47. }
  48. if (rank > this._maxRank) {
  49. this._maxRank = rank;
  50. }
  51. };
  52. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  53. /**
  54. * Checks to see if more fallbacks are still availible.
  55. */
  56. get: function () {
  57. return this._currentRank <= this._maxRank;
  58. },
  59. enumerable: true,
  60. configurable: true
  61. });
  62. /**
  63. * Removes the defines that shoould be removed when falling back.
  64. * @param currentDefines The current define statements for the shader.
  65. * @returns The resulting defines with defines of the current rank removed.
  66. */
  67. EffectFallbacks.prototype.reduce = function (currentDefines) {
  68. // First we try to switch to CPU skinning
  69. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0) {
  70. this._mesh.computeBonesUsingShaders = false;
  71. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  72. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  73. var scene = this._mesh.getScene();
  74. for (var index = 0; index < scene.meshes.length; index++) {
  75. var otherMesh = scene.meshes[index];
  76. if (otherMesh.material === this._mesh.material && otherMesh.computeBonesUsingShaders && otherMesh.numBoneInfluencers > 0) {
  77. otherMesh.computeBonesUsingShaders = false;
  78. }
  79. }
  80. }
  81. else {
  82. var currentFallbacks = this._defines[this._currentRank];
  83. if (currentFallbacks) {
  84. for (var index = 0; index < currentFallbacks.length; index++) {
  85. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  86. }
  87. }
  88. this._currentRank++;
  89. }
  90. return currentDefines;
  91. };
  92. return EffectFallbacks;
  93. }());
  94. BABYLON.EffectFallbacks = EffectFallbacks;
  95. /**
  96. * Options to be used when creating an effect.
  97. */
  98. var EffectCreationOptions = /** @class */ (function () {
  99. function EffectCreationOptions() {
  100. }
  101. return EffectCreationOptions;
  102. }());
  103. BABYLON.EffectCreationOptions = EffectCreationOptions;
  104. /**
  105. * Effect containing vertex and fragment shader that can be executed on an object.
  106. */
  107. var Effect = /** @class */ (function () {
  108. /**
  109. * Instantiates an effect.
  110. * An effect can be used to create/manage/execute vertex and fragment shaders.
  111. * @param baseName Name of the effect.
  112. * @param attributesNamesOrOptions List of attribute names that will be passed to the shader or set of all options to create the effect.
  113. * @param uniformsNamesOrEngine List of uniform variable names that will be passed to the shader or the engine that will be used to render effect.
  114. * @param samplers List of sampler variables that will be passed to the shader.
  115. * @param engine Engine to be used to render the effect
  116. * @param defines Define statements to be added to the shader.
  117. * @param fallbacks Possible fallbacks for this effect to improve performance when needed.
  118. * @param onCompiled Callback that will be called when the shader is compiled.
  119. * @param onError Callback that will be called if an error occurs during shader compilation.
  120. * @param indexParameters Parameters to be used with Babylons include syntax to iterate over an array (eg. {lights: 10})
  121. */
  122. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  123. if (samplers === void 0) { samplers = null; }
  124. if (defines === void 0) { defines = null; }
  125. if (fallbacks === void 0) { fallbacks = null; }
  126. if (onCompiled === void 0) { onCompiled = null; }
  127. if (onError === void 0) { onError = null; }
  128. var _this = this;
  129. /**
  130. * Unique ID of the effect.
  131. */
  132. this.uniqueId = 0;
  133. /**
  134. * Observable that will be called when the shader is compiled.
  135. */
  136. this.onCompileObservable = new BABYLON.Observable();
  137. /**
  138. * Observable that will be called if an error occurs during shader compilation.
  139. */
  140. this.onErrorObservable = new BABYLON.Observable();
  141. /**
  142. * Observable that will be called when effect is bound.
  143. */
  144. this.onBindObservable = new BABYLON.Observable();
  145. this._uniformBuffersNames = {};
  146. this._isReady = false;
  147. this._compilationError = "";
  148. this.name = baseName;
  149. if (attributesNamesOrOptions.attributes) {
  150. var options = attributesNamesOrOptions;
  151. this._engine = uniformsNamesOrEngine;
  152. this._attributesNames = options.attributes;
  153. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  154. this._samplers = options.samplers;
  155. this.defines = options.defines;
  156. this.onError = options.onError;
  157. this.onCompiled = options.onCompiled;
  158. this._fallbacks = options.fallbacks;
  159. this._indexParameters = options.indexParameters;
  160. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  161. if (options.uniformBuffersNames) {
  162. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  163. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  164. }
  165. }
  166. }
  167. else {
  168. this._engine = engine;
  169. this.defines = defines;
  170. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  171. this._samplers = samplers;
  172. this._attributesNames = attributesNamesOrOptions;
  173. this.onError = onError;
  174. this.onCompiled = onCompiled;
  175. this._indexParameters = indexParameters;
  176. this._fallbacks = fallbacks;
  177. }
  178. this.uniqueId = Effect._uniqueIdSeed++;
  179. var vertexSource;
  180. var fragmentSource;
  181. if (baseName.vertexElement) {
  182. vertexSource = document.getElementById(baseName.vertexElement);
  183. if (!vertexSource) {
  184. vertexSource = baseName.vertexElement;
  185. }
  186. }
  187. else {
  188. vertexSource = baseName.vertex || baseName;
  189. }
  190. if (baseName.fragmentElement) {
  191. fragmentSource = document.getElementById(baseName.fragmentElement);
  192. if (!fragmentSource) {
  193. fragmentSource = baseName.fragmentElement;
  194. }
  195. }
  196. else {
  197. fragmentSource = baseName.fragment || baseName;
  198. }
  199. var finalVertexCode;
  200. this._loadVertexShaderAsync(vertexSource)
  201. .then(function (vertexCode) {
  202. return _this._processIncludesAsync(vertexCode);
  203. })
  204. .then(function (vertexCodeWithIncludes) {
  205. finalVertexCode = _this._processShaderConversion(vertexCodeWithIncludes, false);
  206. return _this._loadFragmentShaderAsync(fragmentSource);
  207. })
  208. .then(function (fragmentCode) {
  209. return _this._processIncludesAsync(fragmentCode);
  210. })
  211. .then(function (fragmentCodeWithIncludes) {
  212. var migratedFragmentCode = _this._processShaderConversion(fragmentCodeWithIncludes, true);
  213. if (baseName) {
  214. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  215. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  216. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + finalVertexCode;
  217. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  218. }
  219. else {
  220. _this._vertexSourceCode = finalVertexCode;
  221. _this._fragmentSourceCode = migratedFragmentCode;
  222. }
  223. _this._prepareEffect();
  224. });
  225. }
  226. Object.defineProperty(Effect.prototype, "key", {
  227. /**
  228. * Unique key for this effect
  229. */
  230. get: function () {
  231. return this._key;
  232. },
  233. enumerable: true,
  234. configurable: true
  235. });
  236. /**
  237. * If the effect has been compiled and prepared.
  238. * @returns if the effect is compiled and prepared.
  239. */
  240. Effect.prototype.isReady = function () {
  241. return this._isReady;
  242. };
  243. /**
  244. * The engine the effect was initialized with.
  245. * @returns the engine.
  246. */
  247. Effect.prototype.getEngine = function () {
  248. return this._engine;
  249. };
  250. /**
  251. * The compiled webGL program for the effect
  252. * @returns the webGL program.
  253. */
  254. Effect.prototype.getProgram = function () {
  255. return this._program;
  256. };
  257. /**
  258. * The set of names of attribute variables for the shader.
  259. * @returns An array of attribute names.
  260. */
  261. Effect.prototype.getAttributesNames = function () {
  262. return this._attributesNames;
  263. };
  264. /**
  265. * Returns the attribute at the given index.
  266. * @param index The index of the attribute.
  267. * @returns The location of the attribute.
  268. */
  269. Effect.prototype.getAttributeLocation = function (index) {
  270. return this._attributes[index];
  271. };
  272. /**
  273. * Returns the attribute based on the name of the variable.
  274. * @param name of the attribute to look up.
  275. * @returns the attribute location.
  276. */
  277. Effect.prototype.getAttributeLocationByName = function (name) {
  278. var index = this._attributesNames.indexOf(name);
  279. return this._attributes[index];
  280. };
  281. /**
  282. * The number of attributes.
  283. * @returns the numnber of attributes.
  284. */
  285. Effect.prototype.getAttributesCount = function () {
  286. return this._attributes.length;
  287. };
  288. /**
  289. * Gets the index of a uniform variable.
  290. * @param uniformName of the uniform to look up.
  291. * @returns the index.
  292. */
  293. Effect.prototype.getUniformIndex = function (uniformName) {
  294. return this._uniformsNames.indexOf(uniformName);
  295. };
  296. /**
  297. * Returns the attribute based on the name of the variable.
  298. * @param uniformName of the uniform to look up.
  299. * @returns the location of the uniform.
  300. */
  301. Effect.prototype.getUniform = function (uniformName) {
  302. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  303. };
  304. /**
  305. * Returns an array of sampler variable names
  306. * @returns The array of sampler variable neames.
  307. */
  308. Effect.prototype.getSamplers = function () {
  309. return this._samplers;
  310. };
  311. /**
  312. * The error from the last compilation.
  313. * @returns the error string.
  314. */
  315. Effect.prototype.getCompilationError = function () {
  316. return this._compilationError;
  317. };
  318. /**
  319. * Adds a callback to the onCompiled observable and call the callback imediatly if already ready.
  320. * @param func The callback to be used.
  321. */
  322. Effect.prototype.executeWhenCompiled = function (func) {
  323. if (this.isReady()) {
  324. func(this);
  325. return;
  326. }
  327. this.onCompileObservable.add(function (effect) {
  328. func(effect);
  329. });
  330. };
  331. /** @ignore */
  332. Effect.prototype._loadVertexShaderAsync = function (vertex) {
  333. if (BABYLON.Tools.IsWindowObjectExist()) {
  334. // DOM element ?
  335. if (vertex instanceof HTMLElement) {
  336. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  337. return Promise.resolve(vertexCode);
  338. }
  339. }
  340. // Base64 encoded ?
  341. if (vertex.substr(0, 7) === "base64:") {
  342. var vertexBinary = window.atob(vertex.substr(7));
  343. return Promise.resolve(vertexBinary);
  344. }
  345. // Is in local store ?
  346. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  347. return Promise.resolve(Effect.ShadersStore[vertex + "VertexShader"]);
  348. }
  349. var vertexShaderUrl;
  350. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  351. vertexShaderUrl = vertex;
  352. }
  353. else {
  354. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  355. }
  356. // Vertex shader
  357. return this._engine._loadFileAsync(vertexShaderUrl + ".vertex.fx");
  358. };
  359. /** @ignore */
  360. Effect.prototype._loadFragmentShaderAsync = function (fragment) {
  361. if (BABYLON.Tools.IsWindowObjectExist()) {
  362. // DOM element ?
  363. if (fragment instanceof HTMLElement) {
  364. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  365. return Promise.resolve(fragmentCode);
  366. }
  367. }
  368. // Base64 encoded ?
  369. if (fragment.substr(0, 7) === "base64:") {
  370. var fragmentBinary = window.atob(fragment.substr(7));
  371. return Promise.resolve(fragmentBinary);
  372. }
  373. // Is in local store ?
  374. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  375. return Promise.resolve(Effect.ShadersStore[fragment + "PixelShader"]);
  376. }
  377. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  378. return Promise.resolve(Effect.ShadersStore[fragment + "FragmentShader"]);
  379. }
  380. var fragmentShaderUrl;
  381. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  382. fragmentShaderUrl = fragment;
  383. }
  384. else {
  385. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  386. }
  387. // Fragment shader
  388. return this._engine._loadFileAsync(fragmentShaderUrl + ".fragment.fx");
  389. };
  390. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  391. // Rebuild shaders source code
  392. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n" : "";
  393. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  394. vertexCode = prefix + vertexCode;
  395. fragmentCode = prefix + fragmentCode;
  396. // Number lines of shaders source code
  397. var i = 2;
  398. var regex = /\n/gm;
  399. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  400. i = 2;
  401. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  402. // Dump shaders name and formatted source code
  403. if (this.name.vertexElement) {
  404. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  405. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  406. }
  407. else if (this.name.vertex) {
  408. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  409. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  410. }
  411. else {
  412. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  413. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  414. }
  415. };
  416. ;
  417. Effect.prototype._processShaderConversion = function (sourceCode, isFragment) {
  418. var preparedSourceCode = this._processPrecision(sourceCode);
  419. if (this._engine.webGLVersion == 1) {
  420. return preparedSourceCode;
  421. }
  422. // Already converted
  423. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  424. return preparedSourceCode.replace("#version 300 es", "");
  425. }
  426. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  427. // Remove extensions
  428. // #extension GL_OES_standard_derivatives : enable
  429. // #extension GL_EXT_shader_texture_lod : enable
  430. // #extension GL_EXT_frag_depth : enable
  431. // #extension GL_EXT_draw_buffers : require
  432. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  433. var result = preparedSourceCode.replace(regex, "");
  434. // Migrate to GLSL v300
  435. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  436. result = result.replace(/attribute[ \t]/g, "in ");
  437. result = result.replace(/[ \t]attribute/g, " in");
  438. if (isFragment) {
  439. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  440. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  441. result = result.replace(/texture2D\s*\(/g, "texture(");
  442. result = result.replace(/textureCube\s*\(/g, "texture(");
  443. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  444. result = result.replace(/gl_FragColor/g, "glFragColor");
  445. result = result.replace(/gl_FragData/g, "glFragData");
  446. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  447. }
  448. return result;
  449. };
  450. Effect.prototype._processIncludesAsync = function (sourceCode) {
  451. var _this = this;
  452. return new Promise(function (resolve, reject) {
  453. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  454. var match = regex.exec(sourceCode);
  455. var returnValue = sourceCode;
  456. while (match != null) {
  457. var includeFile = match[1];
  458. // Uniform declaration
  459. if (includeFile.indexOf("__decl__") !== -1) {
  460. includeFile = includeFile.replace(/__decl__/, "");
  461. if (_this._engine.supportsUniformBuffers) {
  462. includeFile = includeFile.replace(/Vertex/, "Ubo");
  463. includeFile = includeFile.replace(/Fragment/, "Ubo");
  464. }
  465. includeFile = includeFile + "Declaration";
  466. }
  467. if (Effect.IncludesShadersStore[includeFile]) {
  468. // Substitution
  469. var includeContent = Effect.IncludesShadersStore[includeFile];
  470. if (match[2]) {
  471. var splits = match[3].split(",");
  472. for (var index = 0; index < splits.length; index += 2) {
  473. var source = new RegExp(splits[index], "g");
  474. var dest = splits[index + 1];
  475. includeContent = includeContent.replace(source, dest);
  476. }
  477. }
  478. if (match[4]) {
  479. var indexString = match[5];
  480. if (indexString.indexOf("..") !== -1) {
  481. var indexSplits = indexString.split("..");
  482. var minIndex = parseInt(indexSplits[0]);
  483. var maxIndex = parseInt(indexSplits[1]);
  484. var sourceIncludeContent = includeContent.slice(0);
  485. includeContent = "";
  486. if (isNaN(maxIndex)) {
  487. maxIndex = _this._indexParameters[indexSplits[1]];
  488. }
  489. for (var i = minIndex; i < maxIndex; i++) {
  490. if (!_this._engine.supportsUniformBuffers) {
  491. // Ubo replacement
  492. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  493. return p1 + "{X}";
  494. });
  495. }
  496. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  497. }
  498. }
  499. else {
  500. if (!_this._engine.supportsUniformBuffers) {
  501. // Ubo replacement
  502. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  503. return p1 + "{X}";
  504. });
  505. }
  506. includeContent = includeContent.replace(/\{X\}/g, indexString);
  507. }
  508. }
  509. // Replace
  510. returnValue = returnValue.replace(match[0], includeContent);
  511. }
  512. else {
  513. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  514. _this._engine._loadFileAsync(includeShaderUrl)
  515. .then(function (fileContent) {
  516. Effect.IncludesShadersStore[includeFile] = fileContent;
  517. return _this._processIncludesAsync(returnValue);
  518. })
  519. .then(function (returnValue) {
  520. resolve(returnValue);
  521. });
  522. return;
  523. }
  524. match = regex.exec(sourceCode);
  525. }
  526. resolve(returnValue);
  527. });
  528. };
  529. Effect.prototype._processPrecision = function (source) {
  530. if (source.indexOf("precision highp float") === -1) {
  531. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  532. source = "precision mediump float;\n" + source;
  533. }
  534. else {
  535. source = "precision highp float;\n" + source;
  536. }
  537. }
  538. else {
  539. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  540. source = source.replace("precision highp float", "precision mediump float");
  541. }
  542. }
  543. return source;
  544. };
  545. /**
  546. * Recompiles the webGL program
  547. * @param vertexSourceCode The source code for the vertex shader.
  548. * @param fragmentSourceCode The source code for the fragment shader.
  549. * @param onCompiled Callback called when completed.
  550. * @param onError Callback called on error.
  551. */
  552. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  553. var _this = this;
  554. this._isReady = false;
  555. this._vertexSourceCodeOverride = vertexSourceCode;
  556. this._fragmentSourceCodeOverride = fragmentSourceCode;
  557. this.onError = function (effect, error) {
  558. if (onError) {
  559. onError(error);
  560. }
  561. };
  562. this.onCompiled = function () {
  563. var scenes = _this.getEngine().scenes;
  564. for (var i = 0; i < scenes.length; i++) {
  565. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  566. }
  567. if (onCompiled) {
  568. onCompiled(_this._program);
  569. }
  570. };
  571. this._fallbacks = null;
  572. this._prepareEffect();
  573. };
  574. /**
  575. * Gets the uniform locations of the the specified variable names
  576. * @param names THe names of the variables to lookup.
  577. * @returns Array of locations in the same order as variable names.
  578. */
  579. Effect.prototype.getSpecificUniformLocations = function (names) {
  580. var engine = this._engine;
  581. return engine.getUniforms(this._program, names);
  582. };
  583. /**
  584. * Prepares the effect
  585. */
  586. Effect.prototype._prepareEffect = function () {
  587. var attributesNames = this._attributesNames;
  588. var defines = this.defines;
  589. var fallbacks = this._fallbacks;
  590. this._valueCache = {};
  591. var previousProgram = this._program;
  592. try {
  593. var engine = this._engine;
  594. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  595. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  596. }
  597. else {
  598. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  599. }
  600. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  601. if (engine.supportsUniformBuffers) {
  602. for (var name in this._uniformBuffersNames) {
  603. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  604. }
  605. }
  606. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  607. this._attributes = engine.getAttributes(this._program, attributesNames);
  608. var index;
  609. for (index = 0; index < this._samplers.length; index++) {
  610. var sampler = this.getUniform(this._samplers[index]);
  611. if (sampler == null) {
  612. this._samplers.splice(index, 1);
  613. index--;
  614. }
  615. }
  616. engine.bindSamplers(this);
  617. this._compilationError = "";
  618. this._isReady = true;
  619. if (this.onCompiled) {
  620. this.onCompiled(this);
  621. }
  622. this.onCompileObservable.notifyObservers(this);
  623. this.onCompileObservable.clear();
  624. // Unbind mesh reference in fallbacks
  625. if (this._fallbacks) {
  626. this._fallbacks.unBindMesh();
  627. }
  628. if (previousProgram) {
  629. this.getEngine()._deleteProgram(previousProgram);
  630. }
  631. }
  632. catch (e) {
  633. this._compilationError = e.message;
  634. // Let's go through fallbacks then
  635. BABYLON.Tools.Error("Unable to compile effect:");
  636. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  637. return " " + uniform;
  638. }));
  639. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  640. return " " + attribute;
  641. }));
  642. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  643. BABYLON.Tools.Error("Error: " + this._compilationError);
  644. if (previousProgram) {
  645. this._program = previousProgram;
  646. this._isReady = true;
  647. if (this.onError) {
  648. this.onError(this, this._compilationError);
  649. }
  650. this.onErrorObservable.notifyObservers(this);
  651. }
  652. if (fallbacks && fallbacks.isMoreFallbacks) {
  653. BABYLON.Tools.Error("Trying next fallback.");
  654. this.defines = fallbacks.reduce(this.defines);
  655. this._prepareEffect();
  656. }
  657. else {
  658. if (this.onError) {
  659. this.onError(this, this._compilationError);
  660. }
  661. this.onErrorObservable.notifyObservers(this);
  662. this.onErrorObservable.clear();
  663. // Unbind mesh reference in fallbacks
  664. if (this._fallbacks) {
  665. this._fallbacks.unBindMesh();
  666. }
  667. }
  668. }
  669. };
  670. Object.defineProperty(Effect.prototype, "isSupported", {
  671. /**
  672. * Checks if the effect is supported. (Must be called after compilation)
  673. */
  674. get: function () {
  675. return this._compilationError === "";
  676. },
  677. enumerable: true,
  678. configurable: true
  679. });
  680. /**
  681. * Binds a texture to the engine to be used as output of the shader.
  682. * @param channel Name of the output variable.
  683. * @param texture Texture to bind.
  684. */
  685. Effect.prototype._bindTexture = function (channel, texture) {
  686. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  687. };
  688. /**
  689. * Sets a texture on the engine to be used in the shader.
  690. * @param channel Name of the sampler variable.
  691. * @param texture Texture to set.
  692. */
  693. Effect.prototype.setTexture = function (channel, texture) {
  694. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  695. };
  696. /**
  697. * Sets an array of textures on the engine to be used in the shader.
  698. * @param channel Name of the variable.
  699. * @param textures Textures to set.
  700. */
  701. Effect.prototype.setTextureArray = function (channel, textures) {
  702. if (this._samplers.indexOf(channel + "Ex") === -1) {
  703. var initialPos = this._samplers.indexOf(channel);
  704. for (var index = 1; index < textures.length; index++) {
  705. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  706. }
  707. }
  708. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  709. };
  710. /**
  711. * Sets a texture to be the input of the specified post process. (To use the output, pass in the next post process in the pipeline)
  712. * @param channel Name of the sampler variable.
  713. * @param postProcess Post process to get the input texture from.
  714. */
  715. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  716. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  717. };
  718. /** @ignore */
  719. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  720. var cache = this._valueCache[uniformName];
  721. var flag = matrix.updateFlag;
  722. if (cache !== undefined && cache === flag) {
  723. return false;
  724. }
  725. this._valueCache[uniformName] = flag;
  726. return true;
  727. };
  728. /** @ignore */
  729. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  730. var cache = this._valueCache[uniformName];
  731. if (!cache) {
  732. cache = [x, y];
  733. this._valueCache[uniformName] = cache;
  734. return true;
  735. }
  736. var changed = false;
  737. if (cache[0] !== x) {
  738. cache[0] = x;
  739. changed = true;
  740. }
  741. if (cache[1] !== y) {
  742. cache[1] = y;
  743. changed = true;
  744. }
  745. return changed;
  746. };
  747. /** @ignore */
  748. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  749. var cache = this._valueCache[uniformName];
  750. if (!cache) {
  751. cache = [x, y, z];
  752. this._valueCache[uniformName] = cache;
  753. return true;
  754. }
  755. var changed = false;
  756. if (cache[0] !== x) {
  757. cache[0] = x;
  758. changed = true;
  759. }
  760. if (cache[1] !== y) {
  761. cache[1] = y;
  762. changed = true;
  763. }
  764. if (cache[2] !== z) {
  765. cache[2] = z;
  766. changed = true;
  767. }
  768. return changed;
  769. };
  770. /** @ignore */
  771. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  772. var cache = this._valueCache[uniformName];
  773. if (!cache) {
  774. cache = [x, y, z, w];
  775. this._valueCache[uniformName] = cache;
  776. return true;
  777. }
  778. var changed = false;
  779. if (cache[0] !== x) {
  780. cache[0] = x;
  781. changed = true;
  782. }
  783. if (cache[1] !== y) {
  784. cache[1] = y;
  785. changed = true;
  786. }
  787. if (cache[2] !== z) {
  788. cache[2] = z;
  789. changed = true;
  790. }
  791. if (cache[3] !== w) {
  792. cache[3] = w;
  793. changed = true;
  794. }
  795. return changed;
  796. };
  797. /**
  798. * Binds a buffer to a uniform.
  799. * @param buffer Buffer to bind.
  800. * @param name Name of the uniform variable to bind to.
  801. */
  802. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  803. var bufferName = this._uniformBuffersNames[name];
  804. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  805. return;
  806. }
  807. Effect._baseCache[bufferName] = buffer;
  808. this._engine.bindUniformBufferBase(buffer, bufferName);
  809. };
  810. /**
  811. * Binds block to a uniform.
  812. * @param blockName Name of the block to bind.
  813. * @param index Index to bind.
  814. */
  815. Effect.prototype.bindUniformBlock = function (blockName, index) {
  816. this._engine.bindUniformBlock(this._program, blockName, index);
  817. };
  818. /**
  819. * Sets an interger value on a uniform variable.
  820. * @param uniformName Name of the variable.
  821. * @param value Value to be set.
  822. * @returns this effect.
  823. */
  824. Effect.prototype.setInt = function (uniformName, value) {
  825. var cache = this._valueCache[uniformName];
  826. if (cache !== undefined && cache === value)
  827. return this;
  828. this._valueCache[uniformName] = value;
  829. this._engine.setInt(this.getUniform(uniformName), value);
  830. return this;
  831. };
  832. /**
  833. * Sets an int array on a uniform variable.
  834. * @param uniformName Name of the variable.
  835. * @param array array to be set.
  836. * @returns this effect.
  837. */
  838. Effect.prototype.setIntArray = function (uniformName, array) {
  839. this._valueCache[uniformName] = null;
  840. this._engine.setIntArray(this.getUniform(uniformName), array);
  841. return this;
  842. };
  843. /**
  844. * Sets an int array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  845. * @param uniformName Name of the variable.
  846. * @param array array to be set.
  847. * @returns this effect.
  848. */
  849. Effect.prototype.setIntArray2 = function (uniformName, array) {
  850. this._valueCache[uniformName] = null;
  851. this._engine.setIntArray2(this.getUniform(uniformName), array);
  852. return this;
  853. };
  854. /**
  855. * Sets an int array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  856. * @param uniformName Name of the variable.
  857. * @param array array to be set.
  858. * @returns this effect.
  859. */
  860. Effect.prototype.setIntArray3 = function (uniformName, array) {
  861. this._valueCache[uniformName] = null;
  862. this._engine.setIntArray3(this.getUniform(uniformName), array);
  863. return this;
  864. };
  865. /**
  866. * Sets an int array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  867. * @param uniformName Name of the variable.
  868. * @param array array to be set.
  869. * @returns this effect.
  870. */
  871. Effect.prototype.setIntArray4 = function (uniformName, array) {
  872. this._valueCache[uniformName] = null;
  873. this._engine.setIntArray4(this.getUniform(uniformName), array);
  874. return this;
  875. };
  876. /**
  877. * Sets an float array on a uniform variable.
  878. * @param uniformName Name of the variable.
  879. * @param array array to be set.
  880. * @returns this effect.
  881. */
  882. Effect.prototype.setFloatArray = function (uniformName, array) {
  883. this._valueCache[uniformName] = null;
  884. this._engine.setFloatArray(this.getUniform(uniformName), array);
  885. return this;
  886. };
  887. /**
  888. * Sets an float array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  889. * @param uniformName Name of the variable.
  890. * @param array array to be set.
  891. * @returns this effect.
  892. */
  893. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  894. this._valueCache[uniformName] = null;
  895. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  896. return this;
  897. };
  898. /**
  899. * Sets an float array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  900. * @param uniformName Name of the variable.
  901. * @param array array to be set.
  902. * @returns this effect.
  903. */
  904. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  905. this._valueCache[uniformName] = null;
  906. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  907. return this;
  908. };
  909. /**
  910. * Sets an float array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  911. * @param uniformName Name of the variable.
  912. * @param array array to be set.
  913. * @returns this effect.
  914. */
  915. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  916. this._valueCache[uniformName] = null;
  917. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  918. return this;
  919. };
  920. /**
  921. * Sets an array on a uniform variable.
  922. * @param uniformName Name of the variable.
  923. * @param array array to be set.
  924. * @returns this effect.
  925. */
  926. Effect.prototype.setArray = function (uniformName, array) {
  927. this._valueCache[uniformName] = null;
  928. this._engine.setArray(this.getUniform(uniformName), array);
  929. return this;
  930. };
  931. /**
  932. * Sets an array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  933. * @param uniformName Name of the variable.
  934. * @param array array to be set.
  935. * @returns this effect.
  936. */
  937. Effect.prototype.setArray2 = function (uniformName, array) {
  938. this._valueCache[uniformName] = null;
  939. this._engine.setArray2(this.getUniform(uniformName), array);
  940. return this;
  941. };
  942. /**
  943. * Sets an array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  944. * @param uniformName Name of the variable.
  945. * @param array array to be set.
  946. * @returns this effect.
  947. */
  948. Effect.prototype.setArray3 = function (uniformName, array) {
  949. this._valueCache[uniformName] = null;
  950. this._engine.setArray3(this.getUniform(uniformName), array);
  951. return this;
  952. };
  953. /**
  954. * Sets an array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  955. * @param uniformName Name of the variable.
  956. * @param array array to be set.
  957. * @returns this effect.
  958. */
  959. Effect.prototype.setArray4 = function (uniformName, array) {
  960. this._valueCache[uniformName] = null;
  961. this._engine.setArray4(this.getUniform(uniformName), array);
  962. return this;
  963. };
  964. /**
  965. * Sets matrices on a uniform variable.
  966. * @param uniformName Name of the variable.
  967. * @param matrices matrices to be set.
  968. * @returns this effect.
  969. */
  970. Effect.prototype.setMatrices = function (uniformName, matrices) {
  971. if (!matrices) {
  972. return this;
  973. }
  974. this._valueCache[uniformName] = null;
  975. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  976. return this;
  977. };
  978. /**
  979. * Sets matrix on a uniform variable.
  980. * @param uniformName Name of the variable.
  981. * @param matrix matrix to be set.
  982. * @returns this effect.
  983. */
  984. Effect.prototype.setMatrix = function (uniformName, matrix) {
  985. if (this._cacheMatrix(uniformName, matrix)) {
  986. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  987. }
  988. return this;
  989. };
  990. /**
  991. * Sets a 3x3 matrix on a uniform variable. (Speicified as [1,2,3,4,5,6,7,8,9] will result in [1,2,3][4,5,6][7,8,9] matrix)
  992. * @param uniformName Name of the variable.
  993. * @param matrix matrix to be set.
  994. * @returns this effect.
  995. */
  996. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  997. this._valueCache[uniformName] = null;
  998. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  999. return this;
  1000. };
  1001. /**
  1002. * Sets a 2x2 matrix on a uniform variable. (Speicified as [1,2,3,4] will result in [1,2][3,4] matrix)
  1003. * @param uniformName Name of the variable.
  1004. * @param matrix matrix to be set.
  1005. * @returns this effect.
  1006. */
  1007. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  1008. this._valueCache[uniformName] = null;
  1009. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  1010. return this;
  1011. };
  1012. /**
  1013. * Sets a float on a uniform variable.
  1014. * @param uniformName Name of the variable.
  1015. * @param value value to be set.
  1016. * @returns this effect.
  1017. */
  1018. Effect.prototype.setFloat = function (uniformName, value) {
  1019. var cache = this._valueCache[uniformName];
  1020. if (cache !== undefined && cache === value)
  1021. return this;
  1022. this._valueCache[uniformName] = value;
  1023. this._engine.setFloat(this.getUniform(uniformName), value);
  1024. return this;
  1025. };
  1026. /**
  1027. * Sets a boolean on a uniform variable.
  1028. * @param uniformName Name of the variable.
  1029. * @param bool value to be set.
  1030. * @returns this effect.
  1031. */
  1032. Effect.prototype.setBool = function (uniformName, bool) {
  1033. var cache = this._valueCache[uniformName];
  1034. if (cache !== undefined && cache === bool)
  1035. return this;
  1036. this._valueCache[uniformName] = bool;
  1037. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  1038. return this;
  1039. };
  1040. /**
  1041. * Sets a Vector2 on a uniform variable.
  1042. * @param uniformName Name of the variable.
  1043. * @param vector2 vector2 to be set.
  1044. * @returns this effect.
  1045. */
  1046. Effect.prototype.setVector2 = function (uniformName, vector2) {
  1047. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  1048. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  1049. }
  1050. return this;
  1051. };
  1052. /**
  1053. * Sets a float2 on a uniform variable.
  1054. * @param uniformName Name of the variable.
  1055. * @param x First float in float2.
  1056. * @param y Second float in float2.
  1057. * @returns this effect.
  1058. */
  1059. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  1060. if (this._cacheFloat2(uniformName, x, y)) {
  1061. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  1062. }
  1063. return this;
  1064. };
  1065. /**
  1066. * Sets a Vector3 on a uniform variable.
  1067. * @param uniformName Name of the variable.
  1068. * @param vector3 Value to be set.
  1069. * @returns this effect.
  1070. */
  1071. Effect.prototype.setVector3 = function (uniformName, vector3) {
  1072. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  1073. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  1074. }
  1075. return this;
  1076. };
  1077. /**
  1078. * Sets a float3 on a uniform variable.
  1079. * @param uniformName Name of the variable.
  1080. * @param x First float in float3.
  1081. * @param y Second float in float3.
  1082. * @param z Third float in float3.
  1083. * @returns this effect.
  1084. */
  1085. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  1086. if (this._cacheFloat3(uniformName, x, y, z)) {
  1087. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  1088. }
  1089. return this;
  1090. };
  1091. /**
  1092. * Sets a Vector4 on a uniform variable.
  1093. * @param uniformName Name of the variable.
  1094. * @param vector4 Value to be set.
  1095. * @returns this effect.
  1096. */
  1097. Effect.prototype.setVector4 = function (uniformName, vector4) {
  1098. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  1099. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  1100. }
  1101. return this;
  1102. };
  1103. /**
  1104. * Sets a float4 on a uniform variable.
  1105. * @param uniformName Name of the variable.
  1106. * @param x First float in float4.
  1107. * @param y Second float in float4.
  1108. * @param z Third float in float4.
  1109. * @param w Fourth float in float4.
  1110. * @returns this effect.
  1111. */
  1112. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  1113. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  1114. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  1115. }
  1116. return this;
  1117. };
  1118. /**
  1119. * Sets a Color3 on a uniform variable.
  1120. * @param uniformName Name of the variable.
  1121. * @param color3 Value to be set.
  1122. * @returns this effect.
  1123. */
  1124. Effect.prototype.setColor3 = function (uniformName, color3) {
  1125. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  1126. this._engine.setColor3(this.getUniform(uniformName), color3);
  1127. }
  1128. return this;
  1129. };
  1130. /**
  1131. * Sets a Color4 on a uniform variable.
  1132. * @param uniformName Name of the variable.
  1133. * @param color3 Value to be set.
  1134. * @param alpha Alpha value to be set.
  1135. * @returns this effect.
  1136. */
  1137. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  1138. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  1139. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  1140. }
  1141. return this;
  1142. };
  1143. /**
  1144. * Resets the cache of effects.
  1145. */
  1146. Effect.ResetCache = function () {
  1147. Effect._baseCache = {};
  1148. };
  1149. Effect._uniqueIdSeed = 0;
  1150. Effect._baseCache = {};
  1151. // Statics
  1152. /**
  1153. * Store of each shader (The can be looked up using effect.key)
  1154. */
  1155. Effect.ShadersStore = {};
  1156. /**
  1157. * Store of each included file for a shader (The can be looked up using effect.key)
  1158. */
  1159. Effect.IncludesShadersStore = {};
  1160. return Effect;
  1161. }());
  1162. BABYLON.Effect = Effect;
  1163. })(BABYLON || (BABYLON = {}));
  1164. //# sourceMappingURL=babylon.effect.js.map
  1165. //# sourceMappingURL=babylon.types.js.map
  1166. var BABYLON;
  1167. (function (BABYLON) {
  1168. var KeyboardEventTypes = /** @class */ (function () {
  1169. function KeyboardEventTypes() {
  1170. }
  1171. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  1172. get: function () {
  1173. return KeyboardEventTypes._KEYDOWN;
  1174. },
  1175. enumerable: true,
  1176. configurable: true
  1177. });
  1178. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  1179. get: function () {
  1180. return KeyboardEventTypes._KEYUP;
  1181. },
  1182. enumerable: true,
  1183. configurable: true
  1184. });
  1185. KeyboardEventTypes._KEYDOWN = 0x01;
  1186. KeyboardEventTypes._KEYUP = 0x02;
  1187. return KeyboardEventTypes;
  1188. }());
  1189. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  1190. var KeyboardInfo = /** @class */ (function () {
  1191. function KeyboardInfo(type, event) {
  1192. this.type = type;
  1193. this.event = event;
  1194. }
  1195. return KeyboardInfo;
  1196. }());
  1197. BABYLON.KeyboardInfo = KeyboardInfo;
  1198. /**
  1199. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  1200. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  1201. */
  1202. var KeyboardInfoPre = /** @class */ (function (_super) {
  1203. __extends(KeyboardInfoPre, _super);
  1204. function KeyboardInfoPre(type, event) {
  1205. var _this = _super.call(this, type, event) || this;
  1206. _this.skipOnPointerObservable = false;
  1207. return _this;
  1208. }
  1209. return KeyboardInfoPre;
  1210. }(KeyboardInfo));
  1211. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  1212. })(BABYLON || (BABYLON = {}));
  1213. //# sourceMappingURL=babylon.keyboardEvents.js.map
  1214. var BABYLON;
  1215. (function (BABYLON) {
  1216. var PointerEventTypes = /** @class */ (function () {
  1217. function PointerEventTypes() {
  1218. }
  1219. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  1220. get: function () {
  1221. return PointerEventTypes._POINTERDOWN;
  1222. },
  1223. enumerable: true,
  1224. configurable: true
  1225. });
  1226. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  1227. get: function () {
  1228. return PointerEventTypes._POINTERUP;
  1229. },
  1230. enumerable: true,
  1231. configurable: true
  1232. });
  1233. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  1234. get: function () {
  1235. return PointerEventTypes._POINTERMOVE;
  1236. },
  1237. enumerable: true,
  1238. configurable: true
  1239. });
  1240. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  1241. get: function () {
  1242. return PointerEventTypes._POINTERWHEEL;
  1243. },
  1244. enumerable: true,
  1245. configurable: true
  1246. });
  1247. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  1248. get: function () {
  1249. return PointerEventTypes._POINTERPICK;
  1250. },
  1251. enumerable: true,
  1252. configurable: true
  1253. });
  1254. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  1255. get: function () {
  1256. return PointerEventTypes._POINTERTAP;
  1257. },
  1258. enumerable: true,
  1259. configurable: true
  1260. });
  1261. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  1262. get: function () {
  1263. return PointerEventTypes._POINTERDOUBLETAP;
  1264. },
  1265. enumerable: true,
  1266. configurable: true
  1267. });
  1268. PointerEventTypes._POINTERDOWN = 0x01;
  1269. PointerEventTypes._POINTERUP = 0x02;
  1270. PointerEventTypes._POINTERMOVE = 0x04;
  1271. PointerEventTypes._POINTERWHEEL = 0x08;
  1272. PointerEventTypes._POINTERPICK = 0x10;
  1273. PointerEventTypes._POINTERTAP = 0x20;
  1274. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  1275. return PointerEventTypes;
  1276. }());
  1277. BABYLON.PointerEventTypes = PointerEventTypes;
  1278. var PointerInfoBase = /** @class */ (function () {
  1279. function PointerInfoBase(type, event) {
  1280. this.type = type;
  1281. this.event = event;
  1282. }
  1283. return PointerInfoBase;
  1284. }());
  1285. BABYLON.PointerInfoBase = PointerInfoBase;
  1286. /**
  1287. * This class is used to store pointer related info for the onPrePointerObservable event.
  1288. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  1289. */
  1290. var PointerInfoPre = /** @class */ (function (_super) {
  1291. __extends(PointerInfoPre, _super);
  1292. function PointerInfoPre(type, event, localX, localY) {
  1293. var _this = _super.call(this, type, event) || this;
  1294. _this.skipOnPointerObservable = false;
  1295. _this.localPosition = new BABYLON.Vector2(localX, localY);
  1296. return _this;
  1297. }
  1298. return PointerInfoPre;
  1299. }(PointerInfoBase));
  1300. BABYLON.PointerInfoPre = PointerInfoPre;
  1301. /**
  1302. * This type contains all the data related to a pointer event in Babylon.js.
  1303. * The event member is an instance of PointerEvent for all types except PointerWheel and is of type MouseWheelEvent when type equals PointerWheel. The different event types can be found in the PointerEventTypes class.
  1304. */
  1305. var PointerInfo = /** @class */ (function (_super) {
  1306. __extends(PointerInfo, _super);
  1307. function PointerInfo(type, event, pickInfo) {
  1308. var _this = _super.call(this, type, event) || this;
  1309. _this.pickInfo = pickInfo;
  1310. return _this;
  1311. }
  1312. return PointerInfo;
  1313. }(PointerInfoBase));
  1314. BABYLON.PointerInfo = PointerInfo;
  1315. })(BABYLON || (BABYLON = {}));
  1316. //# sourceMappingURL=babylon.pointerEvents.js.map
  1317. var BABYLON;
  1318. (function (BABYLON) {
  1319. BABYLON.ToGammaSpace = 1 / 2.2;
  1320. BABYLON.ToLinearSpace = 2.2;
  1321. BABYLON.Epsilon = 0.001;
  1322. /**
  1323. * Class used to hold a RBG color
  1324. */
  1325. var Color3 = /** @class */ (function () {
  1326. /**
  1327. * Creates a new Color3 object from red, green, blue values, all between 0 and 1
  1328. * @param r defines the red component (between 0 and 1, default is 0)
  1329. * @param g defines the green component (between 0 and 1, default is 0)
  1330. * @param b defines the blue component (between 0 and 1, default is 0)
  1331. */
  1332. function Color3(
  1333. /**
  1334. * Defines the red component (between 0 and 1, default is 0)
  1335. */
  1336. r,
  1337. /**
  1338. * Defines the green component (between 0 and 1, default is 0)
  1339. */
  1340. g,
  1341. /**
  1342. * Defines the blue component (between 0 and 1, default is 0)
  1343. */
  1344. b) {
  1345. if (r === void 0) { r = 0; }
  1346. if (g === void 0) { g = 0; }
  1347. if (b === void 0) { b = 0; }
  1348. this.r = r;
  1349. this.g = g;
  1350. this.b = b;
  1351. }
  1352. /**
  1353. * Creates a string with the Color3 current values
  1354. * @returns the string representation of the Color3 object
  1355. */
  1356. Color3.prototype.toString = function () {
  1357. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1358. };
  1359. /**
  1360. * Returns the string "Color3"
  1361. * @returns "Color3"
  1362. */
  1363. Color3.prototype.getClassName = function () {
  1364. return "Color3";
  1365. };
  1366. /**
  1367. * Compute the Color3 hash code
  1368. * @returns an unique number that can be used to hash Color3 objects
  1369. */
  1370. Color3.prototype.getHashCode = function () {
  1371. var hash = this.r || 0;
  1372. hash = (hash * 397) ^ (this.g || 0);
  1373. hash = (hash * 397) ^ (this.b || 0);
  1374. return hash;
  1375. };
  1376. // Operators
  1377. /**
  1378. * Stores in the passed array from the passed starting index the red, green, blue values as successive elements
  1379. * @param array defines the array where to store the r,g,b components
  1380. * @param index defines an optional index in the target array to define where to start storing values
  1381. * @returns the current Color3 object
  1382. */
  1383. Color3.prototype.toArray = function (array, index) {
  1384. if (index === undefined) {
  1385. index = 0;
  1386. }
  1387. array[index] = this.r;
  1388. array[index + 1] = this.g;
  1389. array[index + 2] = this.b;
  1390. return this;
  1391. };
  1392. /**
  1393. * Returns a new {BABYLON.Color4} object from the current Color3 and the passed alpha
  1394. * @param alpha defines the alpha component on the new {BABYLON.Color4} object (default is 1)
  1395. * @returns a new {BABYLON.Color4} object
  1396. */
  1397. Color3.prototype.toColor4 = function (alpha) {
  1398. if (alpha === void 0) { alpha = 1; }
  1399. return new Color4(this.r, this.g, this.b, alpha);
  1400. };
  1401. /**
  1402. * Returns a new array populated with 3 numeric elements : red, green and blue values
  1403. * @returns the new array
  1404. */
  1405. Color3.prototype.asArray = function () {
  1406. var result = new Array();
  1407. this.toArray(result, 0);
  1408. return result;
  1409. };
  1410. /**
  1411. * Returns the luminance value
  1412. * @returns a float value
  1413. */
  1414. Color3.prototype.toLuminance = function () {
  1415. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1416. };
  1417. /**
  1418. * Multiply each Color3 rgb values by the passed Color3 rgb values in a new Color3 object
  1419. * @param otherColor defines the second operand
  1420. * @returns the new Color3 object
  1421. */
  1422. Color3.prototype.multiply = function (otherColor) {
  1423. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1424. };
  1425. /**
  1426. * Multiply the rgb values of the Color3 and the passed Color3 and stores the result in the object "result"
  1427. * @param otherColor defines the second operand
  1428. * @param result defines the Color3 object where to store the result
  1429. * @returns the current Color3
  1430. */
  1431. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1432. result.r = this.r * otherColor.r;
  1433. result.g = this.g * otherColor.g;
  1434. result.b = this.b * otherColor.b;
  1435. return this;
  1436. };
  1437. /**
  1438. * Determines equality between Color3 objects
  1439. * @param otherColor defines the second operand
  1440. * @returns true if the rgb values are equal to the passed ones
  1441. */
  1442. Color3.prototype.equals = function (otherColor) {
  1443. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1444. };
  1445. /**
  1446. * Determines equality between the current Color3 object and a set of r,b,g values
  1447. * @param r defines the red component to check
  1448. * @param g defines the green component to check
  1449. * @param b defines the blue component to check
  1450. * @returns true if the rgb values are equal to the passed ones
  1451. */
  1452. Color3.prototype.equalsFloats = function (r, g, b) {
  1453. return this.r === r && this.g === g && this.b === b;
  1454. };
  1455. /**
  1456. * Multiplies in place each rgb value by scale
  1457. * @param scale defines the scaling factor
  1458. * @returns the updated Color3.
  1459. */
  1460. Color3.prototype.scale = function (scale) {
  1461. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1462. };
  1463. /**
  1464. * Multiplies the rgb values by scale and stores the result into "result"
  1465. * @param scale defines the scaling factor
  1466. * @param result defines the Color3 object where to store the result
  1467. * @returns the unmodified current Color3.
  1468. */
  1469. Color3.prototype.scaleToRef = function (scale, result) {
  1470. result.r = this.r * scale;
  1471. result.g = this.g * scale;
  1472. result.b = this.b * scale;
  1473. return this;
  1474. };
  1475. /**
  1476. * Clamps the rgb values by the min and max values and stores the result into "result"
  1477. * @param min defines minimum clamping value (default is 0)
  1478. * @param max defines maximum clamping value (default is 1)
  1479. * @param result defines color to store the result into
  1480. * @returns the original Color3
  1481. */
  1482. Color3.prototype.clampToRef = function (min, max, result) {
  1483. if (min === void 0) { min = 0; }
  1484. if (max === void 0) { max = 1; }
  1485. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1486. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1487. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1488. return this;
  1489. };
  1490. /**
  1491. * Creates a new Color3 set with the added values of the current Color3 and of the passed one
  1492. * @param otherColor defines the second operand
  1493. * @returns the new Color3
  1494. */
  1495. Color3.prototype.add = function (otherColor) {
  1496. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1497. };
  1498. /**
  1499. * Stores the result of the addition of the current Color3 and passed one rgb values into "result"
  1500. * @param otherColor defines the second operand
  1501. * @param result defines Color3 object to store the result into
  1502. * @returns the unmodified current Color3
  1503. */
  1504. Color3.prototype.addToRef = function (otherColor, result) {
  1505. result.r = this.r + otherColor.r;
  1506. result.g = this.g + otherColor.g;
  1507. result.b = this.b + otherColor.b;
  1508. return this;
  1509. };
  1510. /**
  1511. * Returns a new Color3 set with the subtracted values of the passed one from the current Color3
  1512. * @param otherColor defines the second operand
  1513. * @returns the new Color3
  1514. */
  1515. Color3.prototype.subtract = function (otherColor) {
  1516. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1517. };
  1518. /**
  1519. * Stores the result of the subtraction of passed one from the current Color3 rgb values into "result"
  1520. * @param otherColor defines the second operand
  1521. * @param result defines Color3 object to store the result into
  1522. * @returns the unmodified current Color3
  1523. */
  1524. Color3.prototype.subtractToRef = function (otherColor, result) {
  1525. result.r = this.r - otherColor.r;
  1526. result.g = this.g - otherColor.g;
  1527. result.b = this.b - otherColor.b;
  1528. return this;
  1529. };
  1530. /**
  1531. * Copy the current object
  1532. * @returns a new Color3 copied the current one
  1533. */
  1534. Color3.prototype.clone = function () {
  1535. return new Color3(this.r, this.g, this.b);
  1536. };
  1537. /**
  1538. * Copies the rgb values from the source in the current Color3
  1539. * @param source defines the source Color3 object
  1540. * @returns the updated Color3 object
  1541. */
  1542. Color3.prototype.copyFrom = function (source) {
  1543. this.r = source.r;
  1544. this.g = source.g;
  1545. this.b = source.b;
  1546. return this;
  1547. };
  1548. /**
  1549. * Updates the Color3 rgb values from the passed floats
  1550. * @param r defines the red component to read from
  1551. * @param g defines the green component to read from
  1552. * @param b defines the blue component to read from
  1553. * @returns the current Color3 object
  1554. */
  1555. Color3.prototype.copyFromFloats = function (r, g, b) {
  1556. this.r = r;
  1557. this.g = g;
  1558. this.b = b;
  1559. return this;
  1560. };
  1561. /**
  1562. * Updates the Color3 rgb values from the passed floats
  1563. * @param r defines the red component to read from
  1564. * @param g defines the green component to read from
  1565. * @param b defines the blue component to read from
  1566. * @returns the current Color3 object
  1567. */
  1568. Color3.prototype.set = function (r, g, b) {
  1569. return this.copyFromFloats(r, g, b);
  1570. };
  1571. /**
  1572. * Compute the Color3 hexadecimal code as a string
  1573. * @returns a string containing the hexadecimal representation of the Color3 object
  1574. */
  1575. Color3.prototype.toHexString = function () {
  1576. var intR = (this.r * 255) | 0;
  1577. var intG = (this.g * 255) | 0;
  1578. var intB = (this.b * 255) | 0;
  1579. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1580. };
  1581. /**
  1582. * Computes a new Color3 converted from the current one to linear space
  1583. * @returns a new Color3 object
  1584. */
  1585. Color3.prototype.toLinearSpace = function () {
  1586. var convertedColor = new Color3();
  1587. this.toLinearSpaceToRef(convertedColor);
  1588. return convertedColor;
  1589. };
  1590. /**
  1591. * Converts the Color3 values to linear space and stores the result in "convertedColor"
  1592. * @param convertedColor defines the Color3 object where to store the linear space version
  1593. * @returns the unmodified Color3
  1594. */
  1595. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1596. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1597. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1598. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1599. return this;
  1600. };
  1601. /**
  1602. * Computes a new Color3 converted from the current one to gamma space
  1603. * @returns a new Color3 object
  1604. */
  1605. Color3.prototype.toGammaSpace = function () {
  1606. var convertedColor = new Color3();
  1607. this.toGammaSpaceToRef(convertedColor);
  1608. return convertedColor;
  1609. };
  1610. /**
  1611. * Converts the Color3 values to gamma space and stores the result in "convertedColor"
  1612. * @param convertedColor defines the Color3 object where to store the gamma space version
  1613. * @returns the unmodified Color3
  1614. */
  1615. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1616. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1617. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1618. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1619. return this;
  1620. };
  1621. // Statics
  1622. /**
  1623. * Creates a new Color3 from the string containing valid hexadecimal values
  1624. * @param hex defines a string containing valid hexadecimal values
  1625. * @returns a new Color3 object
  1626. */
  1627. Color3.FromHexString = function (hex) {
  1628. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1629. //Tools.Warn("Color3.FromHexString must be called with a string like #FFFFFF");
  1630. return new Color3(0, 0, 0);
  1631. }
  1632. var r = parseInt(hex.substring(1, 3), 16);
  1633. var g = parseInt(hex.substring(3, 5), 16);
  1634. var b = parseInt(hex.substring(5, 7), 16);
  1635. return Color3.FromInts(r, g, b);
  1636. };
  1637. /**
  1638. * Creates a new Vector3 from the starting index of the passed array
  1639. * @param array defines the source array
  1640. * @param offset defines an offset in the source array
  1641. * @returns a new Color3 object
  1642. */
  1643. Color3.FromArray = function (array, offset) {
  1644. if (offset === void 0) { offset = 0; }
  1645. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1646. };
  1647. /**
  1648. * Creates a new Color3 from integer values (< 256)
  1649. * @param r defines the red component to read from (value between 0 and 255)
  1650. * @param g defines the green component to read from (value between 0 and 255)
  1651. * @param b defines the blue component to read from (value between 0 and 255)
  1652. * @returns a new Color3 object
  1653. */
  1654. Color3.FromInts = function (r, g, b) {
  1655. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1656. };
  1657. /**
  1658. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1659. * @param start defines the start Color3 value
  1660. * @param end defines the end Color3 value
  1661. * @param amount defines the gradient value between start and end
  1662. * @returns a new Color3 object
  1663. */
  1664. Color3.Lerp = function (start, end, amount) {
  1665. var r = start.r + ((end.r - start.r) * amount);
  1666. var g = start.g + ((end.g - start.g) * amount);
  1667. var b = start.b + ((end.b - start.b) * amount);
  1668. return new Color3(r, g, b);
  1669. };
  1670. /**
  1671. * Returns a Color3 value containing a red color
  1672. * @returns a new Color3 object
  1673. */
  1674. Color3.Red = function () { return new Color3(1, 0, 0); };
  1675. /**
  1676. * Returns a Color3 value containing a green color
  1677. * @returns a new Color3 object
  1678. */
  1679. Color3.Green = function () { return new Color3(0, 1, 0); };
  1680. /**
  1681. * Returns a Color3 value containing a blue color
  1682. * @returns a new Color3 object
  1683. */
  1684. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1685. /**
  1686. * Returns a Color3 value containing a black color
  1687. * @returns a new Color3 object
  1688. */
  1689. Color3.Black = function () { return new Color3(0, 0, 0); };
  1690. /**
  1691. * Returns a Color3 value containing a white color
  1692. * @returns a new Color3 object
  1693. */
  1694. Color3.White = function () { return new Color3(1, 1, 1); };
  1695. /**
  1696. * Returns a Color3 value containing a purple color
  1697. * @returns a new Color3 object
  1698. */
  1699. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1700. /**
  1701. * Returns a Color3 value containing a magenta color
  1702. * @returns a new Color3 object
  1703. */
  1704. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1705. /**
  1706. * Returns a Color3 value containing a yellow color
  1707. * @returns a new Color3 object
  1708. */
  1709. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1710. /**
  1711. * Returns a Color3 value containing a gray color
  1712. * @returns a new Color3 object
  1713. */
  1714. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1715. /**
  1716. * Returns a Color3 value containing a teal color
  1717. * @returns a new Color3 object
  1718. */
  1719. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1720. /**
  1721. * Returns a Color3 value containing a random color
  1722. * @returns a new Color3 object
  1723. */
  1724. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1725. return Color3;
  1726. }());
  1727. BABYLON.Color3 = Color3;
  1728. /**
  1729. * Class used to hold a RBGA color
  1730. */
  1731. var Color4 = /** @class */ (function () {
  1732. /**
  1733. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  1734. * @param r defines the red component (between 0 and 1, default is 0)
  1735. * @param g defines the green component (between 0 and 1, default is 0)
  1736. * @param b defines the blue component (between 0 and 1, default is 0)
  1737. * @param a defines the alpha component (between 0 and 1, default is 1)
  1738. */
  1739. function Color4(
  1740. /**
  1741. * Defines the red component (between 0 and 1, default is 0)
  1742. */
  1743. r,
  1744. /**
  1745. * Defines the green component (between 0 and 1, default is 0)
  1746. */
  1747. g,
  1748. /**
  1749. * Defines the blue component (between 0 and 1, default is 0)
  1750. */
  1751. b,
  1752. /**
  1753. * Defines the alpha component (between 0 and 1, default is 1)
  1754. */
  1755. a) {
  1756. if (r === void 0) { r = 0; }
  1757. if (g === void 0) { g = 0; }
  1758. if (b === void 0) { b = 0; }
  1759. if (a === void 0) { a = 1; }
  1760. this.r = r;
  1761. this.g = g;
  1762. this.b = b;
  1763. this.a = a;
  1764. }
  1765. // Operators
  1766. /**
  1767. * Adds in place the passed Color4 values to the current Color4 object
  1768. * @param right defines the second operand
  1769. * @returns the current updated Color4 object
  1770. */
  1771. Color4.prototype.addInPlace = function (right) {
  1772. this.r += right.r;
  1773. this.g += right.g;
  1774. this.b += right.b;
  1775. this.a += right.a;
  1776. return this;
  1777. };
  1778. /**
  1779. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  1780. * @returns the new array
  1781. */
  1782. Color4.prototype.asArray = function () {
  1783. var result = new Array();
  1784. this.toArray(result, 0);
  1785. return result;
  1786. };
  1787. /**
  1788. * Stores from the starting index in the passed array the Color4 successive values
  1789. * @param array defines the array where to store the r,g,b components
  1790. * @param index defines an optional index in the target array to define where to start storing values
  1791. * @returns the current Color4 object
  1792. */
  1793. Color4.prototype.toArray = function (array, index) {
  1794. if (index === undefined) {
  1795. index = 0;
  1796. }
  1797. array[index] = this.r;
  1798. array[index + 1] = this.g;
  1799. array[index + 2] = this.b;
  1800. array[index + 3] = this.a;
  1801. return this;
  1802. };
  1803. /**
  1804. * Creates a new Color4 set with the added values of the current Color4 and of the passed one
  1805. * @param right defines the second operand
  1806. * @returns a new Color4 object
  1807. */
  1808. Color4.prototype.add = function (right) {
  1809. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1810. };
  1811. /**
  1812. * Creates a new Color4 set with the subtracted values of the passed one from the current Color4
  1813. * @param right defines the second operand
  1814. * @returns a new Color4 object
  1815. */
  1816. Color4.prototype.subtract = function (right) {
  1817. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1818. };
  1819. /**
  1820. * Subtracts the passed ones from the current Color4 values and stores the results in "result"
  1821. * @param right defines the second operand
  1822. * @param result defines the Color4 object where to store the result
  1823. * @returns the current Color4 object
  1824. */
  1825. Color4.prototype.subtractToRef = function (right, result) {
  1826. result.r = this.r - right.r;
  1827. result.g = this.g - right.g;
  1828. result.b = this.b - right.b;
  1829. result.a = this.a - right.a;
  1830. return this;
  1831. };
  1832. /**
  1833. * Creates a new Color4 with the current Color4 values multiplied by scale
  1834. * @param scale defines the scaling factor to apply
  1835. * @returns a new Color4 object
  1836. */
  1837. Color4.prototype.scale = function (scale) {
  1838. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  1839. };
  1840. /**
  1841. * Multiplies the current Color4 values by scale and stores the result in "result"
  1842. * @param scale defines the scaling factor to apply
  1843. * @param result defines the Color4 object where to store the result
  1844. * @returns the current Color4.
  1845. */
  1846. Color4.prototype.scaleToRef = function (scale, result) {
  1847. result.r = this.r * scale;
  1848. result.g = this.g * scale;
  1849. result.b = this.b * scale;
  1850. result.a = this.a * scale;
  1851. return this;
  1852. };
  1853. /**
  1854. * Clamps the rgb values by the min and max values and stores the result into "result"
  1855. * @param min defines minimum clamping value (default is 0)
  1856. * @param max defines maximum clamping value (default is 1)
  1857. * @param result defines color to store the result into.
  1858. * @returns the cuurent Color4
  1859. */
  1860. Color4.prototype.clampToRef = function (min, max, result) {
  1861. if (min === void 0) { min = 0; }
  1862. if (max === void 0) { max = 1; }
  1863. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1864. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1865. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1866. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  1867. return this;
  1868. };
  1869. /**
  1870. * Multipy an Color4 value by another and return a new Color4 object
  1871. * @param color defines the Color4 value to multiply by
  1872. * @returns a new Color4 object
  1873. */
  1874. Color4.prototype.multiply = function (color) {
  1875. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  1876. };
  1877. /**
  1878. * Multipy a Color4 value by another and push the result in a reference value
  1879. * @param color defines the Color4 value to multiply by
  1880. * @param result defines the Color4 to fill the result in
  1881. * @returns the result Color4
  1882. */
  1883. Color4.prototype.multiplyToRef = function (color, result) {
  1884. result.r = this.r * color.r;
  1885. result.g = this.g * color.g;
  1886. result.b = this.b * color.b;
  1887. result.a = this.a * color.a;
  1888. return result;
  1889. };
  1890. /**
  1891. * Creates a string with the Color4 current values
  1892. * @returns the string representation of the Color4 object
  1893. */
  1894. Color4.prototype.toString = function () {
  1895. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  1896. };
  1897. /**
  1898. * Returns the string "Color4"
  1899. * @returns "Color4"
  1900. */
  1901. Color4.prototype.getClassName = function () {
  1902. return "Color4";
  1903. };
  1904. /**
  1905. * Compute the Color4 hash code
  1906. * @returns an unique number that can be used to hash Color4 objects
  1907. */
  1908. Color4.prototype.getHashCode = function () {
  1909. var hash = this.r || 0;
  1910. hash = (hash * 397) ^ (this.g || 0);
  1911. hash = (hash * 397) ^ (this.b || 0);
  1912. hash = (hash * 397) ^ (this.a || 0);
  1913. return hash;
  1914. };
  1915. /**
  1916. * Creates a new Color4 copied from the current one
  1917. * @returns a new Color4 object
  1918. */
  1919. Color4.prototype.clone = function () {
  1920. return new Color4(this.r, this.g, this.b, this.a);
  1921. };
  1922. /**
  1923. * Copies the passed Color4 values into the current one
  1924. * @param source defines the source Color4 object
  1925. * @returns the current updated Color4 object
  1926. */
  1927. Color4.prototype.copyFrom = function (source) {
  1928. this.r = source.r;
  1929. this.g = source.g;
  1930. this.b = source.b;
  1931. this.a = source.a;
  1932. return this;
  1933. };
  1934. /**
  1935. * Copies the passed float values into the current one
  1936. * @param r defines the red component to read from
  1937. * @param g defines the green component to read from
  1938. * @param b defines the blue component to read from
  1939. * @param a defines the alpha component to read from
  1940. * @returns the current updated Color4 object
  1941. */
  1942. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  1943. this.r = r;
  1944. this.g = g;
  1945. this.b = b;
  1946. this.a = a;
  1947. return this;
  1948. };
  1949. /**
  1950. * Copies the passed float values into the current one
  1951. * @param r defines the red component to read from
  1952. * @param g defines the green component to read from
  1953. * @param b defines the blue component to read from
  1954. * @param a defines the alpha component to read from
  1955. * @returns the current updated Color4 object
  1956. */
  1957. Color4.prototype.set = function (r, g, b, a) {
  1958. return this.copyFromFloats(r, g, b, a);
  1959. };
  1960. /**
  1961. * Compute the Color4 hexadecimal code as a string
  1962. * @returns a string containing the hexadecimal representation of the Color4 object
  1963. */
  1964. Color4.prototype.toHexString = function () {
  1965. var intR = (this.r * 255) | 0;
  1966. var intG = (this.g * 255) | 0;
  1967. var intB = (this.b * 255) | 0;
  1968. var intA = (this.a * 255) | 0;
  1969. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  1970. };
  1971. /**
  1972. * Computes a new Color4 converted from the current one to linear space
  1973. * @returns a new Color4 object
  1974. */
  1975. Color4.prototype.toLinearSpace = function () {
  1976. var convertedColor = new Color4();
  1977. this.toLinearSpaceToRef(convertedColor);
  1978. return convertedColor;
  1979. };
  1980. /**
  1981. * Converts the Color4 values to linear space and stores the result in "convertedColor"
  1982. * @param convertedColor defines the Color4 object where to store the linear space version
  1983. * @returns the unmodified Color4
  1984. */
  1985. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  1986. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1987. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1988. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1989. convertedColor.a = this.a;
  1990. return this;
  1991. };
  1992. /**
  1993. * Computes a new Color4 converted from the current one to gamma space
  1994. * @returns a new Color4 object
  1995. */
  1996. Color4.prototype.toGammaSpace = function () {
  1997. var convertedColor = new Color4();
  1998. this.toGammaSpaceToRef(convertedColor);
  1999. return convertedColor;
  2000. };
  2001. /**
  2002. * Converts the Color4 values to gamma space and stores the result in "convertedColor"
  2003. * @param convertedColor defines the Color4 object where to store the gamma space version
  2004. * @returns the unmodified Color4
  2005. */
  2006. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  2007. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  2008. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  2009. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  2010. convertedColor.a = this.a;
  2011. return this;
  2012. };
  2013. // Statics
  2014. /**
  2015. * Creates a new Color4 from the string containing valid hexadecimal values
  2016. * @param hex defines a string containing valid hexadecimal values
  2017. * @returns a new Color4 object
  2018. */
  2019. Color4.FromHexString = function (hex) {
  2020. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  2021. //Tools.Warn("Color4.FromHexString must be called with a string like #FFFFFFFF");
  2022. return new Color4(0.0, 0.0, 0.0, 0.0);
  2023. }
  2024. var r = parseInt(hex.substring(1, 3), 16);
  2025. var g = parseInt(hex.substring(3, 5), 16);
  2026. var b = parseInt(hex.substring(5, 7), 16);
  2027. var a = parseInt(hex.substring(7, 9), 16);
  2028. return Color4.FromInts(r, g, b, a);
  2029. };
  2030. /**
  2031. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2032. * @param left defines the start value
  2033. * @param right defines the end value
  2034. * @param amount defines the gradient factor
  2035. * @returns a new Color4 object
  2036. */
  2037. Color4.Lerp = function (left, right, amount) {
  2038. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  2039. Color4.LerpToRef(left, right, amount, result);
  2040. return result;
  2041. };
  2042. /**
  2043. * Set the passed "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2044. * @param left defines the start value
  2045. * @param right defines the end value
  2046. * @param amount defines the gradient factor
  2047. * @param result defines the Color4 object where to store data
  2048. */
  2049. Color4.LerpToRef = function (left, right, amount, result) {
  2050. result.r = left.r + (right.r - left.r) * amount;
  2051. result.g = left.g + (right.g - left.g) * amount;
  2052. result.b = left.b + (right.b - left.b) * amount;
  2053. result.a = left.a + (right.a - left.a) * amount;
  2054. };
  2055. /**
  2056. * Creates a new Color4 from the starting index element of the passed array
  2057. * @param array defines the source array to read from
  2058. * @param offset defines the offset in the source array
  2059. * @returns a new Color4 object
  2060. */
  2061. Color4.FromArray = function (array, offset) {
  2062. if (offset === void 0) { offset = 0; }
  2063. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2064. };
  2065. /**
  2066. * Creates a new Color3 from integer values (< 256)
  2067. * @param r defines the red component to read from (value between 0 and 255)
  2068. * @param g defines the green component to read from (value between 0 and 255)
  2069. * @param b defines the blue component to read from (value between 0 and 255)
  2070. * @param a defines the alpha component to read from (value between 0 and 255)
  2071. * @returns a new Color3 object
  2072. */
  2073. Color4.FromInts = function (r, g, b, a) {
  2074. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  2075. };
  2076. /**
  2077. * Check the content of a given array and convert it to an array containing RGBA data
  2078. * If the original array was already containing count * 4 values then it is returned directly
  2079. * @param colors defines the array to check
  2080. * @param count defines the number of RGBA data to expect
  2081. * @returns an array containing count * 4 values (RGBA)
  2082. */
  2083. Color4.CheckColors4 = function (colors, count) {
  2084. // Check if color3 was used
  2085. if (colors.length === count * 3) {
  2086. var colors4 = [];
  2087. for (var index = 0; index < colors.length; index += 3) {
  2088. var newIndex = (index / 3) * 4;
  2089. colors4[newIndex] = colors[index];
  2090. colors4[newIndex + 1] = colors[index + 1];
  2091. colors4[newIndex + 2] = colors[index + 2];
  2092. colors4[newIndex + 3] = 1.0;
  2093. }
  2094. return colors4;
  2095. }
  2096. return colors;
  2097. };
  2098. return Color4;
  2099. }());
  2100. BABYLON.Color4 = Color4;
  2101. var Vector2 = /** @class */ (function () {
  2102. /**
  2103. * Creates a new Vector2 from the passed x and y coordinates.
  2104. */
  2105. function Vector2(x, y) {
  2106. this.x = x;
  2107. this.y = y;
  2108. }
  2109. /**
  2110. * Returns a string with the Vector2 coordinates.
  2111. */
  2112. Vector2.prototype.toString = function () {
  2113. return "{X: " + this.x + " Y:" + this.y + "}";
  2114. };
  2115. /**
  2116. * Returns the string "Vector2"
  2117. */
  2118. Vector2.prototype.getClassName = function () {
  2119. return "Vector2";
  2120. };
  2121. /**
  2122. * Returns the Vector2 hash code as a number.
  2123. */
  2124. Vector2.prototype.getHashCode = function () {
  2125. var hash = this.x || 0;
  2126. hash = (hash * 397) ^ (this.y || 0);
  2127. return hash;
  2128. };
  2129. // Operators
  2130. /**
  2131. * Sets the Vector2 coordinates in the passed array or Float32Array from the passed index.
  2132. * Returns the Vector2.
  2133. */
  2134. Vector2.prototype.toArray = function (array, index) {
  2135. if (index === void 0) { index = 0; }
  2136. array[index] = this.x;
  2137. array[index + 1] = this.y;
  2138. return this;
  2139. };
  2140. /**
  2141. * Returns a new array with 2 elements : the Vector2 coordinates.
  2142. */
  2143. Vector2.prototype.asArray = function () {
  2144. var result = new Array();
  2145. this.toArray(result, 0);
  2146. return result;
  2147. };
  2148. /**
  2149. * Sets the Vector2 coordinates with the passed Vector2 coordinates.
  2150. * Returns the updated Vector2.
  2151. */
  2152. Vector2.prototype.copyFrom = function (source) {
  2153. this.x = source.x;
  2154. this.y = source.y;
  2155. return this;
  2156. };
  2157. /**
  2158. * Sets the Vector2 coordinates with the passed floats.
  2159. * Returns the updated Vector2.
  2160. */
  2161. Vector2.prototype.copyFromFloats = function (x, y) {
  2162. this.x = x;
  2163. this.y = y;
  2164. return this;
  2165. };
  2166. /**
  2167. * Sets the Vector2 coordinates with the passed floats.
  2168. * Returns the updated Vector2.
  2169. */
  2170. Vector2.prototype.set = function (x, y) {
  2171. return this.copyFromFloats(x, y);
  2172. };
  2173. /**
  2174. * Returns a new Vector2 set with the addition of the current Vector2 and the passed one coordinates.
  2175. */
  2176. Vector2.prototype.add = function (otherVector) {
  2177. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2178. };
  2179. /**
  2180. * Sets the "result" coordinates with the addition of the current Vector2 and the passed one coordinates.
  2181. * Returns the Vector2.
  2182. */
  2183. Vector2.prototype.addToRef = function (otherVector, result) {
  2184. result.x = this.x + otherVector.x;
  2185. result.y = this.y + otherVector.y;
  2186. return this;
  2187. };
  2188. /**
  2189. * Set the Vector2 coordinates by adding the passed Vector2 coordinates.
  2190. * Returns the updated Vector2.
  2191. */
  2192. Vector2.prototype.addInPlace = function (otherVector) {
  2193. this.x += otherVector.x;
  2194. this.y += otherVector.y;
  2195. return this;
  2196. };
  2197. /**
  2198. * Returns a new Vector2 by adding the current Vector2 coordinates to the passed Vector3 x, y coordinates.
  2199. */
  2200. Vector2.prototype.addVector3 = function (otherVector) {
  2201. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2202. };
  2203. /**
  2204. * Returns a new Vector2 set with the subtracted coordinates of the passed one from the current Vector2.
  2205. */
  2206. Vector2.prototype.subtract = function (otherVector) {
  2207. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  2208. };
  2209. /**
  2210. * Sets the "result" coordinates with the subtraction of the passed one from the current Vector2 coordinates.
  2211. * Returns the Vector2.
  2212. */
  2213. Vector2.prototype.subtractToRef = function (otherVector, result) {
  2214. result.x = this.x - otherVector.x;
  2215. result.y = this.y - otherVector.y;
  2216. return this;
  2217. };
  2218. /**
  2219. * Sets the current Vector2 coordinates by subtracting from it the passed one coordinates.
  2220. * Returns the updated Vector2.
  2221. */
  2222. Vector2.prototype.subtractInPlace = function (otherVector) {
  2223. this.x -= otherVector.x;
  2224. this.y -= otherVector.y;
  2225. return this;
  2226. };
  2227. /**
  2228. * Multiplies in place the current Vector2 coordinates by the passed ones.
  2229. * Returns the updated Vector2.
  2230. */
  2231. Vector2.prototype.multiplyInPlace = function (otherVector) {
  2232. this.x *= otherVector.x;
  2233. this.y *= otherVector.y;
  2234. return this;
  2235. };
  2236. /**
  2237. * Returns a new Vector2 set with the multiplication of the current Vector2 and the passed one coordinates.
  2238. */
  2239. Vector2.prototype.multiply = function (otherVector) {
  2240. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  2241. };
  2242. /**
  2243. * Sets "result" coordinates with the multiplication of the current Vector2 and the passed one coordinates.
  2244. * Returns the Vector2.
  2245. */
  2246. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  2247. result.x = this.x * otherVector.x;
  2248. result.y = this.y * otherVector.y;
  2249. return this;
  2250. };
  2251. /**
  2252. * Returns a new Vector2 set with the Vector2 coordinates multiplied by the passed floats.
  2253. */
  2254. Vector2.prototype.multiplyByFloats = function (x, y) {
  2255. return new Vector2(this.x * x, this.y * y);
  2256. };
  2257. /**
  2258. * Returns a new Vector2 set with the Vector2 coordinates divided by the passed one coordinates.
  2259. */
  2260. Vector2.prototype.divide = function (otherVector) {
  2261. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  2262. };
  2263. /**
  2264. * Sets the "result" coordinates with the Vector2 divided by the passed one coordinates.
  2265. * Returns the Vector2.
  2266. */
  2267. Vector2.prototype.divideToRef = function (otherVector, result) {
  2268. result.x = this.x / otherVector.x;
  2269. result.y = this.y / otherVector.y;
  2270. return this;
  2271. };
  2272. /**
  2273. * Divides the current Vector3 coordinates by the passed ones.
  2274. * Returns the updated Vector3.
  2275. */
  2276. Vector2.prototype.divideInPlace = function (otherVector) {
  2277. return this.divideToRef(otherVector, this);
  2278. };
  2279. /**
  2280. * Returns a new Vector2 with current Vector2 negated coordinates.
  2281. */
  2282. Vector2.prototype.negate = function () {
  2283. return new Vector2(-this.x, -this.y);
  2284. };
  2285. /**
  2286. * Multiply the Vector2 coordinates by scale.
  2287. * Returns the updated Vector2.
  2288. */
  2289. Vector2.prototype.scaleInPlace = function (scale) {
  2290. this.x *= scale;
  2291. this.y *= scale;
  2292. return this;
  2293. };
  2294. /**
  2295. * Returns a new Vector2 scaled by "scale" from the current Vector2.
  2296. */
  2297. Vector2.prototype.scale = function (scale) {
  2298. return new Vector2(this.x * scale, this.y * scale);
  2299. };
  2300. /**
  2301. * Boolean : True if the passed vector coordinates strictly equal the current Vector2 ones.
  2302. */
  2303. Vector2.prototype.equals = function (otherVector) {
  2304. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  2305. };
  2306. /**
  2307. * Boolean : True if the passed vector coordinates are close to the current ones by a distance of epsilon.
  2308. */
  2309. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2310. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2311. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  2312. };
  2313. // Properties
  2314. /**
  2315. * Returns the vector length (float).
  2316. */
  2317. Vector2.prototype.length = function () {
  2318. return Math.sqrt(this.x * this.x + this.y * this.y);
  2319. };
  2320. /**
  2321. * Returns the vector squared length (float);
  2322. */
  2323. Vector2.prototype.lengthSquared = function () {
  2324. return (this.x * this.x + this.y * this.y);
  2325. };
  2326. // Methods
  2327. /**
  2328. * Normalize the vector.
  2329. * Returns the updated Vector2.
  2330. */
  2331. Vector2.prototype.normalize = function () {
  2332. var len = this.length();
  2333. if (len === 0)
  2334. return this;
  2335. var num = 1.0 / len;
  2336. this.x *= num;
  2337. this.y *= num;
  2338. return this;
  2339. };
  2340. /**
  2341. * Returns a new Vector2 copied from the Vector2.
  2342. */
  2343. Vector2.prototype.clone = function () {
  2344. return new Vector2(this.x, this.y);
  2345. };
  2346. // Statics
  2347. /**
  2348. * Returns a new Vector2(0, 0)
  2349. */
  2350. Vector2.Zero = function () {
  2351. return new Vector2(0, 0);
  2352. };
  2353. /**
  2354. * Returns a new Vector2(1, 1)
  2355. */
  2356. Vector2.One = function () {
  2357. return new Vector2(1, 1);
  2358. };
  2359. /**
  2360. * Returns a new Vector2 set from the passed index element of the passed array.
  2361. */
  2362. Vector2.FromArray = function (array, offset) {
  2363. if (offset === void 0) { offset = 0; }
  2364. return new Vector2(array[offset], array[offset + 1]);
  2365. };
  2366. /**
  2367. * Sets "result" from the passed index element of the passed array.
  2368. */
  2369. Vector2.FromArrayToRef = function (array, offset, result) {
  2370. result.x = array[offset];
  2371. result.y = array[offset + 1];
  2372. };
  2373. /**
  2374. * Retuns a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the passed four Vector2.
  2375. */
  2376. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  2377. var squared = amount * amount;
  2378. var cubed = amount * squared;
  2379. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2380. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2381. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2382. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2383. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2384. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2385. return new Vector2(x, y);
  2386. };
  2387. /**
  2388. * Returns a new Vector2 set with same the coordinates than "value" ones if the vector "value" is in the square defined by "min" and "max".
  2389. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  2390. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate.
  2391. */
  2392. Vector2.Clamp = function (value, min, max) {
  2393. var x = value.x;
  2394. x = (x > max.x) ? max.x : x;
  2395. x = (x < min.x) ? min.x : x;
  2396. var y = value.y;
  2397. y = (y > max.y) ? max.y : y;
  2398. y = (y < min.y) ? min.y : y;
  2399. return new Vector2(x, y);
  2400. };
  2401. /**
  2402. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2".
  2403. */
  2404. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2405. var squared = amount * amount;
  2406. var cubed = amount * squared;
  2407. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2408. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2409. var part3 = (cubed - (2.0 * squared)) + amount;
  2410. var part4 = cubed - squared;
  2411. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2412. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2413. return new Vector2(x, y);
  2414. };
  2415. /**
  2416. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  2417. */
  2418. Vector2.Lerp = function (start, end, amount) {
  2419. var x = start.x + ((end.x - start.x) * amount);
  2420. var y = start.y + ((end.y - start.y) * amount);
  2421. return new Vector2(x, y);
  2422. };
  2423. /**
  2424. * Returns the dot product (float) of the vector "left" and the vector "right".
  2425. */
  2426. Vector2.Dot = function (left, right) {
  2427. return left.x * right.x + left.y * right.y;
  2428. };
  2429. /**
  2430. * Returns a new Vector2 equal to the normalized passed vector.
  2431. */
  2432. Vector2.Normalize = function (vector) {
  2433. var newVector = vector.clone();
  2434. newVector.normalize();
  2435. return newVector;
  2436. };
  2437. /**
  2438. * Returns a new Vecto2 set with the minimal coordinate values from the "left" and "right" vectors.
  2439. */
  2440. Vector2.Minimize = function (left, right) {
  2441. var x = (left.x < right.x) ? left.x : right.x;
  2442. var y = (left.y < right.y) ? left.y : right.y;
  2443. return new Vector2(x, y);
  2444. };
  2445. /**
  2446. * Returns a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors.
  2447. */
  2448. Vector2.Maximize = function (left, right) {
  2449. var x = (left.x > right.x) ? left.x : right.x;
  2450. var y = (left.y > right.y) ? left.y : right.y;
  2451. return new Vector2(x, y);
  2452. };
  2453. /**
  2454. * Returns a new Vecto2 set with the transformed coordinates of the passed vector by the passed transformation matrix.
  2455. */
  2456. Vector2.Transform = function (vector, transformation) {
  2457. var r = Vector2.Zero();
  2458. Vector2.TransformToRef(vector, transformation, r);
  2459. return r;
  2460. };
  2461. /**
  2462. * Transforms the passed vector coordinates by the passed transformation matrix and stores the result in the vector "result" coordinates.
  2463. */
  2464. Vector2.TransformToRef = function (vector, transformation, result) {
  2465. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  2466. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  2467. result.x = x;
  2468. result.y = y;
  2469. };
  2470. /**
  2471. * Boolean : True if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  2472. */
  2473. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  2474. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  2475. var sign = a < 0 ? -1 : 1;
  2476. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  2477. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  2478. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  2479. };
  2480. /**
  2481. * Returns the distance (float) between the vectors "value1" and "value2".
  2482. */
  2483. Vector2.Distance = function (value1, value2) {
  2484. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  2485. };
  2486. /**
  2487. * Returns the squared distance (float) between the vectors "value1" and "value2".
  2488. */
  2489. Vector2.DistanceSquared = function (value1, value2) {
  2490. var x = value1.x - value2.x;
  2491. var y = value1.y - value2.y;
  2492. return (x * x) + (y * y);
  2493. };
  2494. /**
  2495. * Returns a new Vecto2 located at the center of the vectors "value1" and "value2".
  2496. */
  2497. Vector2.Center = function (value1, value2) {
  2498. var center = value1.add(value2);
  2499. center.scaleInPlace(0.5);
  2500. return center;
  2501. };
  2502. /**
  2503. * Returns the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  2504. */
  2505. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  2506. var l2 = Vector2.DistanceSquared(segA, segB);
  2507. if (l2 === 0.0) {
  2508. return Vector2.Distance(p, segA);
  2509. }
  2510. var v = segB.subtract(segA);
  2511. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  2512. var proj = segA.add(v.multiplyByFloats(t, t));
  2513. return Vector2.Distance(p, proj);
  2514. };
  2515. return Vector2;
  2516. }());
  2517. BABYLON.Vector2 = Vector2;
  2518. /**
  2519. * Classed used to store (x,y,z) vector representation
  2520. * A Vector3 is the main object used in 3D geometry
  2521. * It can represent etiher the coordinates of a point the space, either a direction
  2522. * Reminder: Babylon.js uses a left handed forward facing system
  2523. */
  2524. var Vector3 = /** @class */ (function () {
  2525. /**
  2526. * Creates a new Vector3 object from the passed x, y, z (floats) coordinates.
  2527. * @param x defines the first coordinates (on X axis)
  2528. * @param y defines the second coordinates (on Y axis)
  2529. * @param z defines the third coordinates (on Z axis)
  2530. */
  2531. function Vector3(
  2532. /**
  2533. * Defines the first coordinates (on X axis)
  2534. */
  2535. x,
  2536. /**
  2537. * Defines the second coordinates (on Y axis)
  2538. */
  2539. y,
  2540. /**
  2541. * Defines the third coordinates (on Z axis)
  2542. */
  2543. z) {
  2544. this.x = x;
  2545. this.y = y;
  2546. this.z = z;
  2547. }
  2548. /**
  2549. * Creates a string representation of the Vector3
  2550. * @returns a string with the Vector3 coordinates.
  2551. */
  2552. Vector3.prototype.toString = function () {
  2553. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  2554. };
  2555. /**
  2556. * Gets the class name
  2557. * @returns the string "Vector3"
  2558. */
  2559. Vector3.prototype.getClassName = function () {
  2560. return "Vector3";
  2561. };
  2562. /**
  2563. * Creates the Vector3 hash code
  2564. * @returns a number which tends to be unique between Vector3 instances
  2565. */
  2566. Vector3.prototype.getHashCode = function () {
  2567. var hash = this.x || 0;
  2568. hash = (hash * 397) ^ (this.y || 0);
  2569. hash = (hash * 397) ^ (this.z || 0);
  2570. return hash;
  2571. };
  2572. // Operators
  2573. /**
  2574. * Creates an array containing three elements : the coordinates of the Vector3
  2575. * @returns a new array of numbers
  2576. */
  2577. Vector3.prototype.asArray = function () {
  2578. var result = [];
  2579. this.toArray(result, 0);
  2580. return result;
  2581. };
  2582. /**
  2583. * Populates the passed array or Float32Array from the passed index with the successive coordinates of the Vector3
  2584. * @param array defines the destination array
  2585. * @param index defines the offset in the destination array
  2586. * @returns the current Vector3
  2587. */
  2588. Vector3.prototype.toArray = function (array, index) {
  2589. if (index === void 0) { index = 0; }
  2590. array[index] = this.x;
  2591. array[index + 1] = this.y;
  2592. array[index + 2] = this.z;
  2593. return this;
  2594. };
  2595. /**
  2596. * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)
  2597. * @returns a new Quaternion object, computed from the Vector3 coordinates
  2598. */
  2599. Vector3.prototype.toQuaternion = function () {
  2600. var result = new Quaternion(0.0, 0.0, 0.0, 1.0);
  2601. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  2602. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  2603. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  2604. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  2605. var cosy = Math.cos(this.y * 0.5);
  2606. var siny = Math.sin(this.y * 0.5);
  2607. result.x = coszMinusx * siny;
  2608. result.y = -sinzMinusx * siny;
  2609. result.z = sinxPlusz * cosy;
  2610. result.w = cosxPlusz * cosy;
  2611. return result;
  2612. };
  2613. /**
  2614. * Adds the passed vector to the current Vector3
  2615. * @param otherVector defines the second operand
  2616. * @returns the current updated Vector3
  2617. */
  2618. Vector3.prototype.addInPlace = function (otherVector) {
  2619. this.x += otherVector.x;
  2620. this.y += otherVector.y;
  2621. this.z += otherVector.z;
  2622. return this;
  2623. };
  2624. /**
  2625. * Gets a new Vector3, result of the addition the current Vector3 and the passed vector
  2626. * @param otherVector defines the second operand
  2627. * @returns the resulting Vector3
  2628. */
  2629. Vector3.prototype.add = function (otherVector) {
  2630. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2631. };
  2632. /**
  2633. * Adds the current Vector3 to the passed one and stores the result in the vector "result"
  2634. * @param otherVector defines the second operand
  2635. * @param result defines the Vector3 object where to store the result
  2636. * @returns the current Vector3
  2637. */
  2638. Vector3.prototype.addToRef = function (otherVector, result) {
  2639. result.x = this.x + otherVector.x;
  2640. result.y = this.y + otherVector.y;
  2641. result.z = this.z + otherVector.z;
  2642. return this;
  2643. };
  2644. /**
  2645. * Subtract the passed vector from the current Vector3
  2646. * @param otherVector defines the second operand
  2647. * @returns the current updated Vector3
  2648. */
  2649. Vector3.prototype.subtractInPlace = function (otherVector) {
  2650. this.x -= otherVector.x;
  2651. this.y -= otherVector.y;
  2652. this.z -= otherVector.z;
  2653. return this;
  2654. };
  2655. /**
  2656. * Returns a new Vector3, result of the subtraction of the passed vector from the current Vector3
  2657. * @param otherVector defines the second operand
  2658. * @returns the resulting Vector3
  2659. */
  2660. Vector3.prototype.subtract = function (otherVector) {
  2661. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2662. };
  2663. /**
  2664. * Subtracts the passed vector from the current Vector3 and stores the result in the vector "result".
  2665. * @param otherVector defines the second operand
  2666. * @param result defines the Vector3 object where to store the result
  2667. * @returns the current Vector3
  2668. */
  2669. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2670. result.x = this.x - otherVector.x;
  2671. result.y = this.y - otherVector.y;
  2672. result.z = this.z - otherVector.z;
  2673. return this;
  2674. };
  2675. /**
  2676. * Returns a new Vector3 set with the subtraction of the passed floats from the current Vector3 coordinates
  2677. * @param x defines the x coordinate of the operand
  2678. * @param y defines the y coordinate of the operand
  2679. * @param z defines the z coordinate of the operand
  2680. * @returns the resulting Vector3
  2681. */
  2682. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  2683. return new Vector3(this.x - x, this.y - y, this.z - z);
  2684. };
  2685. /**
  2686. * Subtracts the passed floats from the current Vector3 coordinates and set the passed vector "result" with this result
  2687. * @param x defines the x coordinate of the operand
  2688. * @param y defines the y coordinate of the operand
  2689. * @param z defines the z coordinate of the operand
  2690. * @param result defines the Vector3 object where to store the result
  2691. * @returns the current Vector3
  2692. */
  2693. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  2694. result.x = this.x - x;
  2695. result.y = this.y - y;
  2696. result.z = this.z - z;
  2697. return this;
  2698. };
  2699. /**
  2700. * Gets a new Vector3 set with the current Vector3 negated coordinates
  2701. * @returns a new Vector3
  2702. */
  2703. Vector3.prototype.negate = function () {
  2704. return new Vector3(-this.x, -this.y, -this.z);
  2705. };
  2706. /**
  2707. * Multiplies the Vector3 coordinates by the float "scale"
  2708. * @param scale defines the multiplier factor
  2709. * @returns the current updated Vector3
  2710. */
  2711. Vector3.prototype.scaleInPlace = function (scale) {
  2712. this.x *= scale;
  2713. this.y *= scale;
  2714. this.z *= scale;
  2715. return this;
  2716. };
  2717. /**
  2718. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale"
  2719. * @param scale defines the multiplier factor
  2720. * @returns a new Vector3
  2721. */
  2722. Vector3.prototype.scale = function (scale) {
  2723. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  2724. };
  2725. /**
  2726. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the passed vector "result" coordinates
  2727. * @param scale defines the multiplier factor
  2728. * @param result defines the Vector3 object where to store the result
  2729. * @returns the current Vector3
  2730. */
  2731. Vector3.prototype.scaleToRef = function (scale, result) {
  2732. result.x = this.x * scale;
  2733. result.y = this.y * scale;
  2734. result.z = this.z * scale;
  2735. return this;
  2736. };
  2737. /**
  2738. * Returns true if the current Vector3 and the passed vector coordinates are strictly equal
  2739. * @param otherVector defines the second operand
  2740. * @returns true if both vectors are equals
  2741. */
  2742. Vector3.prototype.equals = function (otherVector) {
  2743. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  2744. };
  2745. /**
  2746. * Returns true if the current Vector3 and the passed vector coordinates are distant less than epsilon
  2747. * @param otherVector defines the second operand
  2748. * @param epsilon defines the minimal distance to define values as equals
  2749. * @returns true if both vectors are distant less than epsilon
  2750. */
  2751. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2752. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2753. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon) && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon);
  2754. };
  2755. /**
  2756. * Returns true if the current Vector3 coordinates equals the passed floats
  2757. * @param x defines the x coordinate of the operand
  2758. * @param y defines the y coordinate of the operand
  2759. * @param z defines the z coordinate of the operand
  2760. * @returns true if both vectors are equals
  2761. */
  2762. Vector3.prototype.equalsToFloats = function (x, y, z) {
  2763. return this.x === x && this.y === y && this.z === z;
  2764. };
  2765. /**
  2766. * Multiplies the current Vector3 coordinates by the passed ones
  2767. * @param otherVector defines the second operand
  2768. * @returns the current updated Vector3
  2769. */
  2770. Vector3.prototype.multiplyInPlace = function (otherVector) {
  2771. this.x *= otherVector.x;
  2772. this.y *= otherVector.y;
  2773. this.z *= otherVector.z;
  2774. return this;
  2775. };
  2776. /**
  2777. * Returns a new Vector3, result of the multiplication of the current Vector3 by the passed vector
  2778. * @param otherVector defines the second operand
  2779. * @returns the new Vector3
  2780. */
  2781. Vector3.prototype.multiply = function (otherVector) {
  2782. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  2783. };
  2784. /**
  2785. * Multiplies the current Vector3 by the passed one and stores the result in the passed vector "result"
  2786. * @param otherVector defines the second operand
  2787. * @param result defines the Vector3 object where to store the result
  2788. * @returns the current Vector3
  2789. */
  2790. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  2791. result.x = this.x * otherVector.x;
  2792. result.y = this.y * otherVector.y;
  2793. result.z = this.z * otherVector.z;
  2794. return this;
  2795. };
  2796. /**
  2797. * Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by the passed floats
  2798. * @param x defines the x coordinate of the operand
  2799. * @param y defines the y coordinate of the operand
  2800. * @param z defines the z coordinate of the operand
  2801. * @returns the new Vector3
  2802. */
  2803. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  2804. return new Vector3(this.x * x, this.y * y, this.z * z);
  2805. };
  2806. /**
  2807. * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the passed ones
  2808. * @param otherVector defines the second operand
  2809. * @returns the new Vector3
  2810. */
  2811. Vector3.prototype.divide = function (otherVector) {
  2812. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  2813. };
  2814. /**
  2815. * Divides the current Vector3 coordinates by the passed ones and stores the result in the passed vector "result"
  2816. * @param otherVector defines the second operand
  2817. * @param result defines the Vector3 object where to store the result
  2818. * @returns the current Vector3
  2819. */
  2820. Vector3.prototype.divideToRef = function (otherVector, result) {
  2821. result.x = this.x / otherVector.x;
  2822. result.y = this.y / otherVector.y;
  2823. result.z = this.z / otherVector.z;
  2824. return this;
  2825. };
  2826. /**
  2827. * Divides the current Vector3 coordinates by the passed ones.
  2828. * @param otherVector defines the second operand
  2829. * @returns the current updated Vector3
  2830. */
  2831. Vector3.prototype.divideInPlace = function (otherVector) {
  2832. return this.divideToRef(otherVector, this);
  2833. };
  2834. /**
  2835. * Updates the current Vector3 with the minimal coordinate values between its and the passed vector ones
  2836. * @param other defines the second operand
  2837. * @returns the current updated Vector3
  2838. */
  2839. Vector3.prototype.minimizeInPlace = function (other) {
  2840. if (other.x < this.x)
  2841. this.x = other.x;
  2842. if (other.y < this.y)
  2843. this.y = other.y;
  2844. if (other.z < this.z)
  2845. this.z = other.z;
  2846. return this;
  2847. };
  2848. /**
  2849. * Updates the current Vector3 with the maximal coordinate values between its and the passed vector ones.
  2850. * @param other defines the second operand
  2851. * @returns the current updated Vector3
  2852. */
  2853. Vector3.prototype.maximizeInPlace = function (other) {
  2854. if (other.x > this.x)
  2855. this.x = other.x;
  2856. if (other.y > this.y)
  2857. this.y = other.y;
  2858. if (other.z > this.z)
  2859. this.z = other.z;
  2860. return this;
  2861. };
  2862. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  2863. /**
  2864. * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
  2865. */
  2866. get: function () {
  2867. var absX = Math.abs(this.x);
  2868. var absY = Math.abs(this.y);
  2869. if (absX !== absY) {
  2870. return true;
  2871. }
  2872. var absZ = Math.abs(this.z);
  2873. if (absX !== absZ) {
  2874. return true;
  2875. }
  2876. if (absY !== absZ) {
  2877. return true;
  2878. }
  2879. return false;
  2880. },
  2881. enumerable: true,
  2882. configurable: true
  2883. });
  2884. // Properties
  2885. /**
  2886. * Gets the length of the Vector3
  2887. * @returns the length of the Vecto3
  2888. */
  2889. Vector3.prototype.length = function () {
  2890. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  2891. };
  2892. /**
  2893. * Gets the squared length of the Vector3
  2894. * @returns squared length of the Vector3
  2895. */
  2896. Vector3.prototype.lengthSquared = function () {
  2897. return (this.x * this.x + this.y * this.y + this.z * this.z);
  2898. };
  2899. /**
  2900. * Normalize the current Vector3.
  2901. * Please note that this is an in place operation.
  2902. * @returns the current updated Vector3
  2903. */
  2904. Vector3.prototype.normalize = function () {
  2905. var len = this.length();
  2906. if (len === 0 || len === 1.0)
  2907. return this;
  2908. var num = 1.0 / len;
  2909. this.x *= num;
  2910. this.y *= num;
  2911. this.z *= num;
  2912. return this;
  2913. };
  2914. /**
  2915. * Normalize the current Vector3 to a new vector
  2916. * @returns the new Vector3
  2917. */
  2918. Vector3.prototype.normalizeToNew = function () {
  2919. var normalized = new Vector3(0, 0, 0);
  2920. this.normalizeToRef(normalized);
  2921. return normalized;
  2922. };
  2923. /**
  2924. * Normalize the current Vector3 to the reference
  2925. * @param reference define the Vector3 to update
  2926. * @returns the updated Vector3
  2927. */
  2928. Vector3.prototype.normalizeToRef = function (reference) {
  2929. var len = this.length();
  2930. if (len === 0 || len === 1.0) {
  2931. reference.set(this.x, this.y, this.z);
  2932. return reference;
  2933. }
  2934. var scale = 1.0 / len;
  2935. this.scaleToRef(scale, reference);
  2936. return reference;
  2937. };
  2938. /**
  2939. * Creates a new Vector3 copied from the current Vector3
  2940. * @returns the new Vector3
  2941. */
  2942. Vector3.prototype.clone = function () {
  2943. return new Vector3(this.x, this.y, this.z);
  2944. };
  2945. /**
  2946. * Copies the passed vector coordinates to the current Vector3 ones
  2947. * @param source defines the source Vector3
  2948. * @returns the current updated Vector3
  2949. */
  2950. Vector3.prototype.copyFrom = function (source) {
  2951. this.x = source.x;
  2952. this.y = source.y;
  2953. this.z = source.z;
  2954. return this;
  2955. };
  2956. /**
  2957. * Copies the passed floats to the current Vector3 coordinates
  2958. * @param x defines the x coordinate of the operand
  2959. * @param y defines the y coordinate of the operand
  2960. * @param z defines the z coordinate of the operand
  2961. * @returns the current updated Vector3
  2962. */
  2963. Vector3.prototype.copyFromFloats = function (x, y, z) {
  2964. this.x = x;
  2965. this.y = y;
  2966. this.z = z;
  2967. return this;
  2968. };
  2969. /**
  2970. * Copies the passed floats to the current Vector3 coordinates
  2971. * @param x defines the x coordinate of the operand
  2972. * @param y defines the y coordinate of the operand
  2973. * @param z defines the z coordinate of the operand
  2974. * @returns the current updated Vector3
  2975. */
  2976. Vector3.prototype.set = function (x, y, z) {
  2977. return this.copyFromFloats(x, y, z);
  2978. };
  2979. // Statics
  2980. /**
  2981. * Get the clip factor between two vectors
  2982. * @param vector0 defines the first operand
  2983. * @param vector1 defines the second operand
  2984. * @param axis defines the axis to use
  2985. * @param size defines the size along the axis
  2986. * @returns the clip factor
  2987. */
  2988. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  2989. var d0 = Vector3.Dot(vector0, axis) - size;
  2990. var d1 = Vector3.Dot(vector1, axis) - size;
  2991. var s = d0 / (d0 - d1);
  2992. return s;
  2993. };
  2994. /**
  2995. * Get angle between two vectors
  2996. * @param vector0 angle between vector0 and vector1
  2997. * @param vector1 angle between vector0 and vector1
  2998. * @param normal direction of the normal
  2999. * @return the angle between vector0 and vector1
  3000. */
  3001. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  3002. var v0 = vector0.clone().normalize();
  3003. var v1 = vector1.clone().normalize();
  3004. var dot = Vector3.Dot(v0, v1);
  3005. var n = Vector3.Cross(v0, v1);
  3006. if (Vector3.Dot(n, normal) > 0) {
  3007. return Math.acos(dot);
  3008. }
  3009. return -Math.acos(dot);
  3010. };
  3011. /**
  3012. * Returns a new Vector3 set from the index "offset" of the passed array
  3013. * @param array defines the source array
  3014. * @param offset defines the offset in the source array
  3015. * @returns the new Vector3
  3016. */
  3017. Vector3.FromArray = function (array, offset) {
  3018. if (!offset) {
  3019. offset = 0;
  3020. }
  3021. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  3022. };
  3023. /**
  3024. * Returns a new Vector3 set from the index "offset" of the passed Float32Array
  3025. * This function is deprecated. Use FromArray instead
  3026. * @param array defines the source array
  3027. * @param offset defines the offset in the source array
  3028. * @returns the new Vector3
  3029. */
  3030. Vector3.FromFloatArray = function (array, offset) {
  3031. return Vector3.FromArray(array, offset);
  3032. };
  3033. /**
  3034. * Sets the passed vector "result" with the element values from the index "offset" of the passed array
  3035. * @param array defines the source array
  3036. * @param offset defines the offset in the source array
  3037. * @param result defines the Vector3 where to store the result
  3038. */
  3039. Vector3.FromArrayToRef = function (array, offset, result) {
  3040. result.x = array[offset];
  3041. result.y = array[offset + 1];
  3042. result.z = array[offset + 2];
  3043. };
  3044. /**
  3045. * Sets the passed vector "result" with the element values from the index "offset" of the passed Float32Array
  3046. * This function is deprecated. Use FromArrayToRef instead.
  3047. * @param array defines the source array
  3048. * @param offset defines the offset in the source array
  3049. * @param result defines the Vector3 where to store the result
  3050. */
  3051. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  3052. return Vector3.FromArrayToRef(array, offset, result);
  3053. };
  3054. /**
  3055. * Sets the passed vector "result" with the passed floats.
  3056. * @param x defines the x coordinate of the source
  3057. * @param y defines the y coordinate of the source
  3058. * @param z defines the z coordinate of the source
  3059. * @param result defines the Vector3 where to store the result
  3060. */
  3061. Vector3.FromFloatsToRef = function (x, y, z, result) {
  3062. result.x = x;
  3063. result.y = y;
  3064. result.z = z;
  3065. };
  3066. /**
  3067. * Returns a new Vector3 set to (0.0, 0.0, 0.0)
  3068. * @returns a new empty Vector3
  3069. */
  3070. Vector3.Zero = function () {
  3071. return new Vector3(0.0, 0.0, 0.0);
  3072. };
  3073. /**
  3074. * Returns a new Vector3 set to (1.0, 1.0, 1.0)
  3075. * @returns a new unit Vector3
  3076. */
  3077. Vector3.One = function () {
  3078. return new Vector3(1.0, 1.0, 1.0);
  3079. };
  3080. /**
  3081. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  3082. * @returns a new up Vector3
  3083. */
  3084. Vector3.Up = function () {
  3085. return new Vector3(0.0, 1.0, 0.0);
  3086. };
  3087. /**
  3088. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  3089. * @returns a new forward Vector3
  3090. */
  3091. Vector3.Forward = function () {
  3092. return new Vector3(0.0, 0.0, 1.0);
  3093. };
  3094. /**
  3095. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  3096. * @returns a new right Vector3
  3097. */
  3098. Vector3.Right = function () {
  3099. return new Vector3(1.0, 0.0, 0.0);
  3100. };
  3101. /**
  3102. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  3103. * @returns a new left Vector3
  3104. */
  3105. Vector3.Left = function () {
  3106. return new Vector3(-1.0, 0.0, 0.0);
  3107. };
  3108. /**
  3109. * Returns a new Vector3 set with the result of the transformation by the passed matrix of the passed vector.
  3110. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3111. * @param vector defines the Vector3 to transform
  3112. * @param transformation defines the transformation matrix
  3113. * @returns the transformed Vector3
  3114. */
  3115. Vector3.TransformCoordinates = function (vector, transformation) {
  3116. var result = Vector3.Zero();
  3117. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  3118. return result;
  3119. };
  3120. /**
  3121. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed vector
  3122. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3123. * @param vector defines the Vector3 to transform
  3124. * @param transformation defines the transformation matrix
  3125. * @param result defines the Vector3 where to store the result
  3126. */
  3127. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  3128. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  3129. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  3130. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  3131. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  3132. result.x = x / w;
  3133. result.y = y / w;
  3134. result.z = z / w;
  3135. };
  3136. /**
  3137. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed floats (x, y, z)
  3138. * This method computes tranformed coordinates only, not transformed direction vectors
  3139. * @param x define the x coordinate of the source vector
  3140. * @param y define the y coordinate of the source vector
  3141. * @param z define the z coordinate of the source vector
  3142. * @param transformation defines the transformation matrix
  3143. * @param result defines the Vector3 where to store the result
  3144. */
  3145. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  3146. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  3147. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  3148. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  3149. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  3150. result.x = rx / rw;
  3151. result.y = ry / rw;
  3152. result.z = rz / rw;
  3153. };
  3154. /**
  3155. * Returns a new Vector3 set with the result of the normal transformation by the passed matrix of the passed vector
  3156. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3157. * @param vector defines the Vector3 to transform
  3158. * @param transformation defines the transformation matrix
  3159. * @returns the new Vector3
  3160. */
  3161. Vector3.TransformNormal = function (vector, transformation) {
  3162. var result = Vector3.Zero();
  3163. Vector3.TransformNormalToRef(vector, transformation, result);
  3164. return result;
  3165. };
  3166. /**
  3167. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector
  3168. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3169. * @param vector defines the Vector3 to transform
  3170. * @param transformation defines the transformation matrix
  3171. * @param result defines the Vector3 where to store the result
  3172. */
  3173. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  3174. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3175. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3176. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3177. result.x = x;
  3178. result.y = y;
  3179. result.z = z;
  3180. };
  3181. /**
  3182. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z)
  3183. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3184. * @param x define the x coordinate of the source vector
  3185. * @param y define the y coordinate of the source vector
  3186. * @param z define the z coordinate of the source vector
  3187. * @param transformation defines the transformation matrix
  3188. * @param result defines the Vector3 where to store the result
  3189. */
  3190. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  3191. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3192. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3193. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3194. };
  3195. /**
  3196. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
  3197. * @param value1 defines the first control point
  3198. * @param value2 defines the second control point
  3199. * @param value3 defines the third control point
  3200. * @param value4 defines the fourth control point
  3201. * @param amount defines the amount on the spline to use
  3202. * @returns the new Vector3
  3203. */
  3204. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  3205. var squared = amount * amount;
  3206. var cubed = amount * squared;
  3207. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  3208. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  3209. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  3210. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  3211. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  3212. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  3213. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  3214. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  3215. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  3216. return new Vector3(x, y, z);
  3217. };
  3218. /**
  3219. * Returns a new Vector3 set with the coordinates of "value", if the vector "value" is in the cube defined by the vectors "min" and "max"
  3220. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  3221. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  3222. * @param value defines the current value
  3223. * @param min defines the lower range value
  3224. * @param max defines the upper range value
  3225. * @returns the new Vector3
  3226. */
  3227. Vector3.Clamp = function (value, min, max) {
  3228. var x = value.x;
  3229. x = (x > max.x) ? max.x : x;
  3230. x = (x < min.x) ? min.x : x;
  3231. var y = value.y;
  3232. y = (y > max.y) ? max.y : y;
  3233. y = (y < min.y) ? min.y : y;
  3234. var z = value.z;
  3235. z = (z > max.z) ? max.z : z;
  3236. z = (z < min.z) ? min.z : z;
  3237. return new Vector3(x, y, z);
  3238. };
  3239. /**
  3240. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
  3241. * @param value1 defines the first control point
  3242. * @param tangent1 defines the first tangent vector
  3243. * @param value2 defines the second control point
  3244. * @param tangent2 defines the second tangent vector
  3245. * @param amount defines the amount on the interpolation spline (between 0 and 1)
  3246. * @returns the new Vector3
  3247. */
  3248. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3249. var squared = amount * amount;
  3250. var cubed = amount * squared;
  3251. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3252. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3253. var part3 = (cubed - (2.0 * squared)) + amount;
  3254. var part4 = cubed - squared;
  3255. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3256. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3257. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3258. return new Vector3(x, y, z);
  3259. };
  3260. /**
  3261. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
  3262. * @param start defines the start value
  3263. * @param end defines the end value
  3264. * @param amount max defines amount between both (between 0 and 1)
  3265. * @returns the new Vector3
  3266. */
  3267. Vector3.Lerp = function (start, end, amount) {
  3268. var result = new Vector3(0, 0, 0);
  3269. Vector3.LerpToRef(start, end, amount, result);
  3270. return result;
  3271. };
  3272. /**
  3273. * Sets the passed vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
  3274. * @param start defines the start value
  3275. * @param end defines the end value
  3276. * @param amount max defines amount between both (between 0 and 1)
  3277. * @param result defines the Vector3 where to store the result
  3278. */
  3279. Vector3.LerpToRef = function (start, end, amount, result) {
  3280. result.x = start.x + ((end.x - start.x) * amount);
  3281. result.y = start.y + ((end.y - start.y) * amount);
  3282. result.z = start.z + ((end.z - start.z) * amount);
  3283. };
  3284. /**
  3285. * Returns the dot product (float) between the vectors "left" and "right"
  3286. * @param left defines the left operand
  3287. * @param right defines the right operand
  3288. * @returns the dot product
  3289. */
  3290. Vector3.Dot = function (left, right) {
  3291. return (left.x * right.x + left.y * right.y + left.z * right.z);
  3292. };
  3293. /**
  3294. * Returns a new Vector3 as the cross product of the vectors "left" and "right"
  3295. * The cross product is then orthogonal to both "left" and "right"
  3296. * @param left defines the left operand
  3297. * @param right defines the right operand
  3298. * @returns the cross product
  3299. */
  3300. Vector3.Cross = function (left, right) {
  3301. var result = Vector3.Zero();
  3302. Vector3.CrossToRef(left, right, result);
  3303. return result;
  3304. };
  3305. /**
  3306. * Sets the passed vector "result" with the cross product of "left" and "right"
  3307. * The cross product is then orthogonal to both "left" and "right"
  3308. * @param left defines the left operand
  3309. * @param right defines the right operand
  3310. * @param result defines the Vector3 where to store the result
  3311. */
  3312. Vector3.CrossToRef = function (left, right, result) {
  3313. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  3314. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  3315. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  3316. result.copyFrom(MathTmp.Vector3[0]);
  3317. };
  3318. /**
  3319. * Returns a new Vector3 as the normalization of the passed vector
  3320. * @param vector defines the Vector3 to normalize
  3321. * @returns the new Vector3
  3322. */
  3323. Vector3.Normalize = function (vector) {
  3324. var result = Vector3.Zero();
  3325. Vector3.NormalizeToRef(vector, result);
  3326. return result;
  3327. };
  3328. /**
  3329. * Sets the passed vector "result" with the normalization of the passed first vector
  3330. * @param vector defines the Vector3 to normalize
  3331. * @param result defines the Vector3 where to store the result
  3332. */
  3333. Vector3.NormalizeToRef = function (vector, result) {
  3334. result.copyFrom(vector);
  3335. result.normalize();
  3336. };
  3337. /**
  3338. * Project a Vector3 onto screen space
  3339. * @param vector defines the Vector3 to project
  3340. * @param world defines the world matrix to use
  3341. * @param transform defines the transform (view x projection) matrix to use
  3342. * @param viewport defines the screen viewport to use
  3343. * @returns the new Vector3
  3344. */
  3345. Vector3.Project = function (vector, world, transform, viewport) {
  3346. var cw = viewport.width;
  3347. var ch = viewport.height;
  3348. var cx = viewport.x;
  3349. var cy = viewport.y;
  3350. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  3351. Matrix.FromValuesToRef(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, 0.5, 0, cx + cw / 2.0, ch / 2.0 + cy, 0.5, 1, viewportMatrix);
  3352. var matrix = MathTmp.Matrix[0];
  3353. world.multiplyToRef(transform, matrix);
  3354. matrix.multiplyToRef(viewportMatrix, matrix);
  3355. return Vector3.TransformCoordinates(vector, matrix);
  3356. };
  3357. /**
  3358. * Unproject from screen space to object space
  3359. * @param source defines the screen space Vector3 to use
  3360. * @param viewportWidth defines the current width of the viewport
  3361. * @param viewportHeight defines the current height of the viewport
  3362. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3363. * @param transform defines the transform (view x projection) matrix to use
  3364. * @returns the new Vector3
  3365. */
  3366. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  3367. var matrix = MathTmp.Matrix[0];
  3368. world.multiplyToRef(transform, matrix);
  3369. matrix.invert();
  3370. source.x = source.x / viewportWidth * 2 - 1;
  3371. source.y = -(source.y / viewportHeight * 2 - 1);
  3372. var vector = Vector3.TransformCoordinates(source, matrix);
  3373. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  3374. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3375. vector = vector.scale(1.0 / num);
  3376. }
  3377. return vector;
  3378. };
  3379. /**
  3380. * Unproject from screen space to object space
  3381. * @param source defines the screen space Vector3 to use
  3382. * @param viewportWidth defines the current width of the viewport
  3383. * @param viewportHeight defines the current height of the viewport
  3384. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3385. * @param view defines the view matrix to use
  3386. * @param projection defines the projection matrix to use
  3387. * @returns the new Vector3
  3388. */
  3389. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  3390. var result = Vector3.Zero();
  3391. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  3392. return result;
  3393. };
  3394. /**
  3395. * Unproject from screen space to object space
  3396. * @param source defines the screen space Vector3 to use
  3397. * @param viewportWidth defines the current width of the viewport
  3398. * @param viewportHeight defines the current height of the viewport
  3399. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3400. * @param view defines the view matrix to use
  3401. * @param projection defines the projection matrix to use
  3402. * @param result defines the Vector3 where to store the result
  3403. */
  3404. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  3405. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  3406. };
  3407. /**
  3408. * Unproject from screen space to object space
  3409. * @param sourceX defines the screen space x coordinate to use
  3410. * @param sourceY defines the screen space y coordinate to use
  3411. * @param sourceZ defines the screen space z coordinate to use
  3412. * @param viewportWidth defines the current width of the viewport
  3413. * @param viewportHeight defines the current height of the viewport
  3414. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3415. * @param view defines the view matrix to use
  3416. * @param projection defines the projection matrix to use
  3417. * @param result defines the Vector3 where to store the result
  3418. */
  3419. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  3420. var matrix = MathTmp.Matrix[0];
  3421. world.multiplyToRef(view, matrix);
  3422. matrix.multiplyToRef(projection, matrix);
  3423. matrix.invert();
  3424. var screenSource = MathTmp.Vector3[0];
  3425. screenSource.x = sourceX / viewportWidth * 2 - 1;
  3426. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  3427. screenSource.z = 2 * sourceZ - 1.0;
  3428. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  3429. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  3430. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3431. result.scaleInPlace(1.0 / num);
  3432. }
  3433. };
  3434. /**
  3435. * Gets the minimal coordinate values between two Vector3
  3436. * @param left defines the first operand
  3437. * @param right defines the second operand
  3438. * @returns the new Vector3
  3439. */
  3440. Vector3.Minimize = function (left, right) {
  3441. var min = left.clone();
  3442. min.minimizeInPlace(right);
  3443. return min;
  3444. };
  3445. /**
  3446. * Gets the maximal coordinate values between two Vector3
  3447. * @param left defines the first operand
  3448. * @param right defines the second operand
  3449. * @returns the new Vector3
  3450. */
  3451. Vector3.Maximize = function (left, right) {
  3452. var max = left.clone();
  3453. max.maximizeInPlace(right);
  3454. return max;
  3455. };
  3456. /**
  3457. * Returns the distance between the vectors "value1" and "value2"
  3458. * @param value1 defines the first operand
  3459. * @param value2 defines the second operand
  3460. * @returns the distance
  3461. */
  3462. Vector3.Distance = function (value1, value2) {
  3463. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  3464. };
  3465. /**
  3466. * Returns the squared distance between the vectors "value1" and "value2"
  3467. * @param value1 defines the first operand
  3468. * @param value2 defines the second operand
  3469. * @returns the squared distance
  3470. */
  3471. Vector3.DistanceSquared = function (value1, value2) {
  3472. var x = value1.x - value2.x;
  3473. var y = value1.y - value2.y;
  3474. var z = value1.z - value2.z;
  3475. return (x * x) + (y * y) + (z * z);
  3476. };
  3477. /**
  3478. * Returns a new Vector3 located at the center between "value1" and "value2"
  3479. * @param value1 defines the first operand
  3480. * @param value2 defines the second operand
  3481. * @returns the new Vector3
  3482. */
  3483. Vector3.Center = function (value1, value2) {
  3484. var center = value1.add(value2);
  3485. center.scaleInPlace(0.5);
  3486. return center;
  3487. };
  3488. /**
  3489. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  3490. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  3491. * to something in order to rotate it from its local system to the given target system
  3492. * Note: axis1, axis2 and axis3 are normalized during this operation
  3493. * @param axis1 defines the first axis
  3494. * @param axis2 defines the second axis
  3495. * @param axis3 defines the third axis
  3496. * @returns a new Vector3
  3497. */
  3498. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  3499. var rotation = Vector3.Zero();
  3500. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  3501. return rotation;
  3502. };
  3503. /**
  3504. * The same than RotationFromAxis but updates the passed ref Vector3 parameter instead of returning a new Vector3
  3505. * @param axis1 defines the first axis
  3506. * @param axis2 defines the second axis
  3507. * @param axis3 defines the third axis
  3508. * @param ref defines the Vector3 where to store the result
  3509. */
  3510. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3511. var quat = MathTmp.Quaternion[0];
  3512. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3513. quat.toEulerAnglesToRef(ref);
  3514. };
  3515. return Vector3;
  3516. }());
  3517. BABYLON.Vector3 = Vector3;
  3518. //Vector4 class created for EulerAngle class conversion to Quaternion
  3519. var Vector4 = /** @class */ (function () {
  3520. /**
  3521. * Creates a Vector4 object from the passed floats.
  3522. */
  3523. function Vector4(x, y, z, w) {
  3524. this.x = x;
  3525. this.y = y;
  3526. this.z = z;
  3527. this.w = w;
  3528. }
  3529. /**
  3530. * Returns the string with the Vector4 coordinates.
  3531. */
  3532. Vector4.prototype.toString = function () {
  3533. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3534. };
  3535. /**
  3536. * Returns the string "Vector4".
  3537. */
  3538. Vector4.prototype.getClassName = function () {
  3539. return "Vector4";
  3540. };
  3541. /**
  3542. * Returns the Vector4 hash code.
  3543. */
  3544. Vector4.prototype.getHashCode = function () {
  3545. var hash = this.x || 0;
  3546. hash = (hash * 397) ^ (this.y || 0);
  3547. hash = (hash * 397) ^ (this.z || 0);
  3548. hash = (hash * 397) ^ (this.w || 0);
  3549. return hash;
  3550. };
  3551. // Operators
  3552. /**
  3553. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  3554. */
  3555. Vector4.prototype.asArray = function () {
  3556. var result = new Array();
  3557. this.toArray(result, 0);
  3558. return result;
  3559. };
  3560. /**
  3561. * Populates the passed array from the passed index with the Vector4 coordinates.
  3562. * Returns the Vector4.
  3563. */
  3564. Vector4.prototype.toArray = function (array, index) {
  3565. if (index === undefined) {
  3566. index = 0;
  3567. }
  3568. array[index] = this.x;
  3569. array[index + 1] = this.y;
  3570. array[index + 2] = this.z;
  3571. array[index + 3] = this.w;
  3572. return this;
  3573. };
  3574. /**
  3575. * Adds the passed vector to the current Vector4.
  3576. * Returns the updated Vector4.
  3577. */
  3578. Vector4.prototype.addInPlace = function (otherVector) {
  3579. this.x += otherVector.x;
  3580. this.y += otherVector.y;
  3581. this.z += otherVector.z;
  3582. this.w += otherVector.w;
  3583. return this;
  3584. };
  3585. /**
  3586. * Returns a new Vector4 as the result of the addition of the current Vector4 and the passed one.
  3587. */
  3588. Vector4.prototype.add = function (otherVector) {
  3589. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  3590. };
  3591. /**
  3592. * Updates the passed vector "result" with the result of the addition of the current Vector4 and the passed one.
  3593. * Returns the current Vector4.
  3594. */
  3595. Vector4.prototype.addToRef = function (otherVector, result) {
  3596. result.x = this.x + otherVector.x;
  3597. result.y = this.y + otherVector.y;
  3598. result.z = this.z + otherVector.z;
  3599. result.w = this.w + otherVector.w;
  3600. return this;
  3601. };
  3602. /**
  3603. * Subtract in place the passed vector from the current Vector4.
  3604. * Returns the updated Vector4.
  3605. */
  3606. Vector4.prototype.subtractInPlace = function (otherVector) {
  3607. this.x -= otherVector.x;
  3608. this.y -= otherVector.y;
  3609. this.z -= otherVector.z;
  3610. this.w -= otherVector.w;
  3611. return this;
  3612. };
  3613. /**
  3614. * Returns a new Vector4 with the result of the subtraction of the passed vector from the current Vector4.
  3615. */
  3616. Vector4.prototype.subtract = function (otherVector) {
  3617. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  3618. };
  3619. /**
  3620. * Sets the passed vector "result" with the result of the subtraction of the passed vector from the current Vector4.
  3621. * Returns the current Vector4.
  3622. */
  3623. Vector4.prototype.subtractToRef = function (otherVector, result) {
  3624. result.x = this.x - otherVector.x;
  3625. result.y = this.y - otherVector.y;
  3626. result.z = this.z - otherVector.z;
  3627. result.w = this.w - otherVector.w;
  3628. return this;
  3629. };
  3630. /**
  3631. * Returns a new Vector4 set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  3632. */
  3633. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  3634. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  3635. };
  3636. /**
  3637. * Sets the passed vector "result" set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  3638. * Returns the current Vector4.
  3639. */
  3640. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  3641. result.x = this.x - x;
  3642. result.y = this.y - y;
  3643. result.z = this.z - z;
  3644. result.w = this.w - w;
  3645. return this;
  3646. };
  3647. /**
  3648. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  3649. */
  3650. Vector4.prototype.negate = function () {
  3651. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  3652. };
  3653. /**
  3654. * Multiplies the current Vector4 coordinates by scale (float).
  3655. * Returns the updated Vector4.
  3656. */
  3657. Vector4.prototype.scaleInPlace = function (scale) {
  3658. this.x *= scale;
  3659. this.y *= scale;
  3660. this.z *= scale;
  3661. this.w *= scale;
  3662. return this;
  3663. };
  3664. /**
  3665. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  3666. */
  3667. Vector4.prototype.scale = function (scale) {
  3668. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  3669. };
  3670. /**
  3671. * Sets the passed vector "result" with the current Vector4 coordinates multiplied by scale (float).
  3672. * Returns the current Vector4.
  3673. */
  3674. Vector4.prototype.scaleToRef = function (scale, result) {
  3675. result.x = this.x * scale;
  3676. result.y = this.y * scale;
  3677. result.z = this.z * scale;
  3678. result.w = this.w * scale;
  3679. return this;
  3680. };
  3681. /**
  3682. * Boolean : True if the current Vector4 coordinates are stricly equal to the passed ones.
  3683. */
  3684. Vector4.prototype.equals = function (otherVector) {
  3685. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  3686. };
  3687. /**
  3688. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the passed vector ones.
  3689. */
  3690. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3691. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3692. return otherVector
  3693. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  3694. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  3695. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  3696. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  3697. };
  3698. /**
  3699. * Boolean : True if the passed floats are strictly equal to the current Vector4 coordinates.
  3700. */
  3701. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  3702. return this.x === x && this.y === y && this.z === z && this.w === w;
  3703. };
  3704. /**
  3705. * Multiplies in place the current Vector4 by the passed one.
  3706. * Returns the updated Vector4.
  3707. */
  3708. Vector4.prototype.multiplyInPlace = function (otherVector) {
  3709. this.x *= otherVector.x;
  3710. this.y *= otherVector.y;
  3711. this.z *= otherVector.z;
  3712. this.w *= otherVector.w;
  3713. return this;
  3714. };
  3715. /**
  3716. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the passed one.
  3717. */
  3718. Vector4.prototype.multiply = function (otherVector) {
  3719. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  3720. };
  3721. /**
  3722. * Updates the passed vector "result" with the multiplication result of the current Vector4 and the passed one.
  3723. * Returns the current Vector4.
  3724. */
  3725. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  3726. result.x = this.x * otherVector.x;
  3727. result.y = this.y * otherVector.y;
  3728. result.z = this.z * otherVector.z;
  3729. result.w = this.w * otherVector.w;
  3730. return this;
  3731. };
  3732. /**
  3733. * Returns a new Vector4 set with the multiplication result of the passed floats and the current Vector4 coordinates.
  3734. */
  3735. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  3736. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  3737. };
  3738. /**
  3739. * Returns a new Vector4 set with the division result of the current Vector4 by the passed one.
  3740. */
  3741. Vector4.prototype.divide = function (otherVector) {
  3742. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  3743. };
  3744. /**
  3745. * Updates the passed vector "result" with the division result of the current Vector4 by the passed one.
  3746. * Returns the current Vector4.
  3747. */
  3748. Vector4.prototype.divideToRef = function (otherVector, result) {
  3749. result.x = this.x / otherVector.x;
  3750. result.y = this.y / otherVector.y;
  3751. result.z = this.z / otherVector.z;
  3752. result.w = this.w / otherVector.w;
  3753. return this;
  3754. };
  3755. /**
  3756. * Divides the current Vector3 coordinates by the passed ones.
  3757. * @returns the updated Vector3.
  3758. */
  3759. Vector4.prototype.divideInPlace = function (otherVector) {
  3760. return this.divideToRef(otherVector, this);
  3761. };
  3762. /**
  3763. * Updates the Vector4 coordinates with the minimum values between its own and the passed vector ones
  3764. * @param other defines the second operand
  3765. * @returns the current updated Vector4
  3766. */
  3767. Vector4.prototype.minimizeInPlace = function (other) {
  3768. if (other.x < this.x)
  3769. this.x = other.x;
  3770. if (other.y < this.y)
  3771. this.y = other.y;
  3772. if (other.z < this.z)
  3773. this.z = other.z;
  3774. if (other.w < this.w)
  3775. this.w = other.w;
  3776. return this;
  3777. };
  3778. /**
  3779. * Updates the Vector4 coordinates with the maximum values between its own and the passed vector ones
  3780. * @param other defines the second operand
  3781. * @returns the current updated Vector4
  3782. */
  3783. Vector4.prototype.maximizeInPlace = function (other) {
  3784. if (other.x > this.x)
  3785. this.x = other.x;
  3786. if (other.y > this.y)
  3787. this.y = other.y;
  3788. if (other.z > this.z)
  3789. this.z = other.z;
  3790. if (other.w > this.w)
  3791. this.w = other.w;
  3792. return this;
  3793. };
  3794. // Properties
  3795. /**
  3796. * Returns the Vector4 length (float).
  3797. */
  3798. Vector4.prototype.length = function () {
  3799. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  3800. };
  3801. /**
  3802. * Returns the Vector4 squared length (float).
  3803. */
  3804. Vector4.prototype.lengthSquared = function () {
  3805. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  3806. };
  3807. // Methods
  3808. /**
  3809. * Normalizes in place the Vector4.
  3810. * Returns the updated Vector4.
  3811. */
  3812. Vector4.prototype.normalize = function () {
  3813. var len = this.length();
  3814. if (len === 0)
  3815. return this;
  3816. var num = 1.0 / len;
  3817. this.x *= num;
  3818. this.y *= num;
  3819. this.z *= num;
  3820. this.w *= num;
  3821. return this;
  3822. };
  3823. /**
  3824. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  3825. */
  3826. Vector4.prototype.toVector3 = function () {
  3827. return new Vector3(this.x, this.y, this.z);
  3828. };
  3829. /**
  3830. * Returns a new Vector4 copied from the current one.
  3831. */
  3832. Vector4.prototype.clone = function () {
  3833. return new Vector4(this.x, this.y, this.z, this.w);
  3834. };
  3835. /**
  3836. * Updates the current Vector4 with the passed one coordinates.
  3837. * Returns the updated Vector4.
  3838. */
  3839. Vector4.prototype.copyFrom = function (source) {
  3840. this.x = source.x;
  3841. this.y = source.y;
  3842. this.z = source.z;
  3843. this.w = source.w;
  3844. return this;
  3845. };
  3846. /**
  3847. * Updates the current Vector4 coordinates with the passed floats.
  3848. * Returns the updated Vector4.
  3849. */
  3850. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  3851. this.x = x;
  3852. this.y = y;
  3853. this.z = z;
  3854. this.w = w;
  3855. return this;
  3856. };
  3857. /**
  3858. * Updates the current Vector4 coordinates with the passed floats.
  3859. * Returns the updated Vector4.
  3860. */
  3861. Vector4.prototype.set = function (x, y, z, w) {
  3862. return this.copyFromFloats(x, y, z, w);
  3863. };
  3864. // Statics
  3865. /**
  3866. * Returns a new Vector4 set from the starting index of the passed array.
  3867. */
  3868. Vector4.FromArray = function (array, offset) {
  3869. if (!offset) {
  3870. offset = 0;
  3871. }
  3872. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  3873. };
  3874. /**
  3875. * Updates the passed vector "result" from the starting index of the passed array.
  3876. */
  3877. Vector4.FromArrayToRef = function (array, offset, result) {
  3878. result.x = array[offset];
  3879. result.y = array[offset + 1];
  3880. result.z = array[offset + 2];
  3881. result.w = array[offset + 3];
  3882. };
  3883. /**
  3884. * Updates the passed vector "result" from the starting index of the passed Float32Array.
  3885. */
  3886. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  3887. Vector4.FromArrayToRef(array, offset, result);
  3888. };
  3889. /**
  3890. * Updates the passed vector "result" coordinates from the passed floats.
  3891. */
  3892. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  3893. result.x = x;
  3894. result.y = y;
  3895. result.z = z;
  3896. result.w = w;
  3897. };
  3898. /**
  3899. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  3900. */
  3901. Vector4.Zero = function () {
  3902. return new Vector4(0.0, 0.0, 0.0, 0.0);
  3903. };
  3904. /**
  3905. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  3906. */
  3907. Vector4.One = function () {
  3908. return new Vector4(1.0, 1.0, 1.0, 1.0);
  3909. };
  3910. /**
  3911. * Returns a new normalized Vector4 from the passed one.
  3912. */
  3913. Vector4.Normalize = function (vector) {
  3914. var result = Vector4.Zero();
  3915. Vector4.NormalizeToRef(vector, result);
  3916. return result;
  3917. };
  3918. /**
  3919. * Updates the passed vector "result" from the normalization of the passed one.
  3920. */
  3921. Vector4.NormalizeToRef = function (vector, result) {
  3922. result.copyFrom(vector);
  3923. result.normalize();
  3924. };
  3925. Vector4.Minimize = function (left, right) {
  3926. var min = left.clone();
  3927. min.minimizeInPlace(right);
  3928. return min;
  3929. };
  3930. Vector4.Maximize = function (left, right) {
  3931. var max = left.clone();
  3932. max.maximizeInPlace(right);
  3933. return max;
  3934. };
  3935. /**
  3936. * Returns the distance (float) between the vectors "value1" and "value2".
  3937. */
  3938. Vector4.Distance = function (value1, value2) {
  3939. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  3940. };
  3941. /**
  3942. * Returns the squared distance (float) between the vectors "value1" and "value2".
  3943. */
  3944. Vector4.DistanceSquared = function (value1, value2) {
  3945. var x = value1.x - value2.x;
  3946. var y = value1.y - value2.y;
  3947. var z = value1.z - value2.z;
  3948. var w = value1.w - value2.w;
  3949. return (x * x) + (y * y) + (z * z) + (w * w);
  3950. };
  3951. /**
  3952. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  3953. */
  3954. Vector4.Center = function (value1, value2) {
  3955. var center = value1.add(value2);
  3956. center.scaleInPlace(0.5);
  3957. return center;
  3958. };
  3959. /**
  3960. * Returns a new Vector4 set with the result of the normal transformation by the passed matrix of the passed vector.
  3961. * This methods computes transformed normalized direction vectors only.
  3962. */
  3963. Vector4.TransformNormal = function (vector, transformation) {
  3964. var result = Vector4.Zero();
  3965. Vector4.TransformNormalToRef(vector, transformation, result);
  3966. return result;
  3967. };
  3968. /**
  3969. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  3970. * This methods computes transformed normalized direction vectors only.
  3971. */
  3972. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  3973. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3974. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3975. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3976. result.x = x;
  3977. result.y = y;
  3978. result.z = z;
  3979. result.w = vector.w;
  3980. };
  3981. /**
  3982. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z, w).
  3983. * This methods computes transformed normalized direction vectors only.
  3984. */
  3985. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  3986. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3987. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3988. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3989. result.w = w;
  3990. };
  3991. return Vector4;
  3992. }());
  3993. BABYLON.Vector4 = Vector4;
  3994. var Size = /** @class */ (function () {
  3995. /**
  3996. * Creates a Size object from the passed width and height (floats).
  3997. */
  3998. function Size(width, height) {
  3999. this.width = width;
  4000. this.height = height;
  4001. }
  4002. // Returns a string with the Size width and height.
  4003. Size.prototype.toString = function () {
  4004. return "{W: " + this.width + ", H: " + this.height + "}";
  4005. };
  4006. /**
  4007. * Returns the string "Size"
  4008. */
  4009. Size.prototype.getClassName = function () {
  4010. return "Size";
  4011. };
  4012. /**
  4013. * Returns the Size hash code.
  4014. */
  4015. Size.prototype.getHashCode = function () {
  4016. var hash = this.width || 0;
  4017. hash = (hash * 397) ^ (this.height || 0);
  4018. return hash;
  4019. };
  4020. /**
  4021. * Updates the current size from the passed one.
  4022. * Returns the updated Size.
  4023. */
  4024. Size.prototype.copyFrom = function (src) {
  4025. this.width = src.width;
  4026. this.height = src.height;
  4027. };
  4028. /**
  4029. * Updates in place the current Size from the passed floats.
  4030. * Returns the updated Size.
  4031. */
  4032. Size.prototype.copyFromFloats = function (width, height) {
  4033. this.width = width;
  4034. this.height = height;
  4035. return this;
  4036. };
  4037. /**
  4038. * Updates in place the current Size from the passed floats.
  4039. * Returns the updated Size.
  4040. */
  4041. Size.prototype.set = function (width, height) {
  4042. return this.copyFromFloats(width, height);
  4043. };
  4044. /**
  4045. * Returns a new Size set with the multiplication result of the current Size and the passed floats.
  4046. */
  4047. Size.prototype.multiplyByFloats = function (w, h) {
  4048. return new Size(this.width * w, this.height * h);
  4049. };
  4050. /**
  4051. * Returns a new Size copied from the passed one.
  4052. */
  4053. Size.prototype.clone = function () {
  4054. return new Size(this.width, this.height);
  4055. };
  4056. /**
  4057. * Boolean : True if the current Size and the passed one width and height are strictly equal.
  4058. */
  4059. Size.prototype.equals = function (other) {
  4060. if (!other) {
  4061. return false;
  4062. }
  4063. return (this.width === other.width) && (this.height === other.height);
  4064. };
  4065. Object.defineProperty(Size.prototype, "surface", {
  4066. /**
  4067. * Returns the surface of the Size : width * height (float).
  4068. */
  4069. get: function () {
  4070. return this.width * this.height;
  4071. },
  4072. enumerable: true,
  4073. configurable: true
  4074. });
  4075. /**
  4076. * Returns a new Size set to (0.0, 0.0)
  4077. */
  4078. Size.Zero = function () {
  4079. return new Size(0.0, 0.0);
  4080. };
  4081. /**
  4082. * Returns a new Size set as the addition result of the current Size and the passed one.
  4083. */
  4084. Size.prototype.add = function (otherSize) {
  4085. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  4086. return r;
  4087. };
  4088. /**
  4089. * Returns a new Size set as the subtraction result of the passed one from the current Size.
  4090. */
  4091. Size.prototype.subtract = function (otherSize) {
  4092. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  4093. return r;
  4094. };
  4095. /**
  4096. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  4097. */
  4098. Size.Lerp = function (start, end, amount) {
  4099. var w = start.width + ((end.width - start.width) * amount);
  4100. var h = start.height + ((end.height - start.height) * amount);
  4101. return new Size(w, h);
  4102. };
  4103. return Size;
  4104. }());
  4105. BABYLON.Size = Size;
  4106. var Quaternion = /** @class */ (function () {
  4107. /**
  4108. * Creates a new Quaternion from the passed floats.
  4109. */
  4110. function Quaternion(x, y, z, w) {
  4111. if (x === void 0) { x = 0.0; }
  4112. if (y === void 0) { y = 0.0; }
  4113. if (z === void 0) { z = 0.0; }
  4114. if (w === void 0) { w = 1.0; }
  4115. this.x = x;
  4116. this.y = y;
  4117. this.z = z;
  4118. this.w = w;
  4119. }
  4120. /**
  4121. * Returns a string with the Quaternion coordinates.
  4122. */
  4123. Quaternion.prototype.toString = function () {
  4124. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  4125. };
  4126. /**
  4127. * Returns the string "Quaternion".
  4128. */
  4129. Quaternion.prototype.getClassName = function () {
  4130. return "Quaternion";
  4131. };
  4132. /**
  4133. * Returns the Quaternion hash code.
  4134. */
  4135. Quaternion.prototype.getHashCode = function () {
  4136. var hash = this.x || 0;
  4137. hash = (hash * 397) ^ (this.y || 0);
  4138. hash = (hash * 397) ^ (this.z || 0);
  4139. hash = (hash * 397) ^ (this.w || 0);
  4140. return hash;
  4141. };
  4142. /**
  4143. * Returns a new array populated with 4 elements : the Quaternion coordinates.
  4144. */
  4145. Quaternion.prototype.asArray = function () {
  4146. return [this.x, this.y, this.z, this.w];
  4147. };
  4148. /**
  4149. * Boolean : True if the current Quaterion and the passed one coordinates are strictly equal.
  4150. */
  4151. Quaternion.prototype.equals = function (otherQuaternion) {
  4152. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  4153. };
  4154. /**
  4155. * Returns a new Quaternion copied from the current one.
  4156. */
  4157. Quaternion.prototype.clone = function () {
  4158. return new Quaternion(this.x, this.y, this.z, this.w);
  4159. };
  4160. /**
  4161. * Updates the current Quaternion from the passed one coordinates.
  4162. * Returns the updated Quaterion.
  4163. */
  4164. Quaternion.prototype.copyFrom = function (other) {
  4165. this.x = other.x;
  4166. this.y = other.y;
  4167. this.z = other.z;
  4168. this.w = other.w;
  4169. return this;
  4170. };
  4171. /**
  4172. * Updates the current Quaternion from the passed float coordinates.
  4173. * Returns the updated Quaterion.
  4174. */
  4175. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  4176. this.x = x;
  4177. this.y = y;
  4178. this.z = z;
  4179. this.w = w;
  4180. return this;
  4181. };
  4182. /**
  4183. * Updates the current Quaternion from the passed float coordinates.
  4184. * Returns the updated Quaterion.
  4185. */
  4186. Quaternion.prototype.set = function (x, y, z, w) {
  4187. return this.copyFromFloats(x, y, z, w);
  4188. };
  4189. /**
  4190. * Returns a new Quaternion as the addition result of the passed one and the current Quaternion.
  4191. */
  4192. Quaternion.prototype.add = function (other) {
  4193. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  4194. };
  4195. /**
  4196. * Returns a new Quaternion as the subtraction result of the passed one from the current Quaternion.
  4197. */
  4198. Quaternion.prototype.subtract = function (other) {
  4199. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  4200. };
  4201. /**
  4202. * Returns a new Quaternion set by multiplying the current Quaterion coordinates by the float "scale".
  4203. */
  4204. Quaternion.prototype.scale = function (value) {
  4205. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  4206. };
  4207. /**
  4208. * Returns a new Quaternion set as the quaternion mulplication result of the current one with the passed one "q1".
  4209. */
  4210. Quaternion.prototype.multiply = function (q1) {
  4211. var result = new Quaternion(0, 0, 0, 1.0);
  4212. this.multiplyToRef(q1, result);
  4213. return result;
  4214. };
  4215. /**
  4216. * Sets the passed "result" as the quaternion mulplication result of the current one with the passed one "q1".
  4217. * Returns the current Quaternion.
  4218. */
  4219. Quaternion.prototype.multiplyToRef = function (q1, result) {
  4220. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  4221. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  4222. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  4223. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  4224. result.copyFromFloats(x, y, z, w);
  4225. return this;
  4226. };
  4227. /**
  4228. * Updates the current Quaternion with the quaternion mulplication result of itself with the passed one "q1".
  4229. * Returns the updated Quaternion.
  4230. */
  4231. Quaternion.prototype.multiplyInPlace = function (q1) {
  4232. this.multiplyToRef(q1, this);
  4233. return this;
  4234. };
  4235. /**
  4236. * Sets the passed "ref" with the conjugation of the current Quaternion.
  4237. * Returns the current Quaternion.
  4238. */
  4239. Quaternion.prototype.conjugateToRef = function (ref) {
  4240. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  4241. return this;
  4242. };
  4243. /**
  4244. * Conjugates in place the current Quaternion.
  4245. * Returns the updated Quaternion.
  4246. */
  4247. Quaternion.prototype.conjugateInPlace = function () {
  4248. this.x *= -1;
  4249. this.y *= -1;
  4250. this.z *= -1;
  4251. return this;
  4252. };
  4253. /**
  4254. * Returns a new Quaternion as the conjugate of the current Quaternion.
  4255. */
  4256. Quaternion.prototype.conjugate = function () {
  4257. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  4258. return result;
  4259. };
  4260. /**
  4261. * Returns the Quaternion length (float).
  4262. */
  4263. Quaternion.prototype.length = function () {
  4264. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  4265. };
  4266. /**
  4267. * Normalize in place the current Quaternion.
  4268. * Returns the updated Quaternion.
  4269. */
  4270. Quaternion.prototype.normalize = function () {
  4271. var length = 1.0 / this.length();
  4272. this.x *= length;
  4273. this.y *= length;
  4274. this.z *= length;
  4275. this.w *= length;
  4276. return this;
  4277. };
  4278. /**
  4279. * Returns a new Vector3 set with the Euler angles translated from the current Quaternion.
  4280. */
  4281. Quaternion.prototype.toEulerAngles = function (order) {
  4282. if (order === void 0) { order = "YZX"; }
  4283. var result = Vector3.Zero();
  4284. this.toEulerAnglesToRef(result, order);
  4285. return result;
  4286. };
  4287. /**
  4288. * Sets the passed vector3 "result" with the Euler angles translated from the current Quaternion.
  4289. * Returns the current Quaternion.
  4290. */
  4291. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  4292. if (order === void 0) { order = "YZX"; }
  4293. var qz = this.z;
  4294. var qx = this.x;
  4295. var qy = this.y;
  4296. var qw = this.w;
  4297. var sqw = qw * qw;
  4298. var sqz = qz * qz;
  4299. var sqx = qx * qx;
  4300. var sqy = qy * qy;
  4301. var zAxisY = qy * qz - qx * qw;
  4302. var limit = .4999999;
  4303. if (zAxisY < -limit) {
  4304. result.y = 2 * Math.atan2(qy, qw);
  4305. result.x = Math.PI / 2;
  4306. result.z = 0;
  4307. }
  4308. else if (zAxisY > limit) {
  4309. result.y = 2 * Math.atan2(qy, qw);
  4310. result.x = -Math.PI / 2;
  4311. result.z = 0;
  4312. }
  4313. else {
  4314. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  4315. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  4316. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  4317. }
  4318. return this;
  4319. };
  4320. /**
  4321. * Updates the passed rotation matrix with the current Quaternion values.
  4322. * Returns the current Quaternion.
  4323. */
  4324. Quaternion.prototype.toRotationMatrix = function (result) {
  4325. var xx = this.x * this.x;
  4326. var yy = this.y * this.y;
  4327. var zz = this.z * this.z;
  4328. var xy = this.x * this.y;
  4329. var zw = this.z * this.w;
  4330. var zx = this.z * this.x;
  4331. var yw = this.y * this.w;
  4332. var yz = this.y * this.z;
  4333. var xw = this.x * this.w;
  4334. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4335. result.m[1] = 2.0 * (xy + zw);
  4336. result.m[2] = 2.0 * (zx - yw);
  4337. result.m[3] = 0;
  4338. result.m[4] = 2.0 * (xy - zw);
  4339. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4340. result.m[6] = 2.0 * (yz + xw);
  4341. result.m[7] = 0;
  4342. result.m[8] = 2.0 * (zx + yw);
  4343. result.m[9] = 2.0 * (yz - xw);
  4344. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4345. result.m[11] = 0;
  4346. result.m[12] = 0;
  4347. result.m[13] = 0;
  4348. result.m[14] = 0;
  4349. result.m[15] = 1.0;
  4350. result._markAsUpdated();
  4351. return this;
  4352. };
  4353. /**
  4354. * Updates the current Quaternion from the passed rotation matrix values.
  4355. * Returns the updated Quaternion.
  4356. */
  4357. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  4358. Quaternion.FromRotationMatrixToRef(matrix, this);
  4359. return this;
  4360. };
  4361. // Statics
  4362. /**
  4363. * Returns a new Quaternion set from the passed rotation matrix values.
  4364. */
  4365. Quaternion.FromRotationMatrix = function (matrix) {
  4366. var result = new Quaternion();
  4367. Quaternion.FromRotationMatrixToRef(matrix, result);
  4368. return result;
  4369. };
  4370. /**
  4371. * Updates the passed quaternion "result" with the passed rotation matrix values.
  4372. */
  4373. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  4374. var data = matrix.m;
  4375. var m11 = data[0], m12 = data[4], m13 = data[8];
  4376. var m21 = data[1], m22 = data[5], m23 = data[9];
  4377. var m31 = data[2], m32 = data[6], m33 = data[10];
  4378. var trace = m11 + m22 + m33;
  4379. var s;
  4380. if (trace > 0) {
  4381. s = 0.5 / Math.sqrt(trace + 1.0);
  4382. result.w = 0.25 / s;
  4383. result.x = (m32 - m23) * s;
  4384. result.y = (m13 - m31) * s;
  4385. result.z = (m21 - m12) * s;
  4386. }
  4387. else if (m11 > m22 && m11 > m33) {
  4388. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  4389. result.w = (m32 - m23) / s;
  4390. result.x = 0.25 * s;
  4391. result.y = (m12 + m21) / s;
  4392. result.z = (m13 + m31) / s;
  4393. }
  4394. else if (m22 > m33) {
  4395. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  4396. result.w = (m13 - m31) / s;
  4397. result.x = (m12 + m21) / s;
  4398. result.y = 0.25 * s;
  4399. result.z = (m23 + m32) / s;
  4400. }
  4401. else {
  4402. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  4403. result.w = (m21 - m12) / s;
  4404. result.x = (m13 + m31) / s;
  4405. result.y = (m23 + m32) / s;
  4406. result.z = 0.25 * s;
  4407. }
  4408. };
  4409. /**
  4410. * Returns a new Quaternion set to (0.0, 0.0, 0.0).
  4411. */
  4412. Quaternion.Zero = function () {
  4413. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  4414. };
  4415. /**
  4416. * Returns a new Quaternion as the inverted current Quaternion.
  4417. */
  4418. Quaternion.Inverse = function (q) {
  4419. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  4420. };
  4421. /**
  4422. * Returns the identity Quaternion.
  4423. */
  4424. Quaternion.Identity = function () {
  4425. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  4426. };
  4427. Quaternion.IsIdentity = function (quaternion) {
  4428. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  4429. };
  4430. /**
  4431. * Returns a new Quaternion set from the passed axis (Vector3) and angle in radians (float).
  4432. */
  4433. Quaternion.RotationAxis = function (axis, angle) {
  4434. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  4435. };
  4436. /**
  4437. * Sets the passed quaternion "result" from the passed axis (Vector3) and angle in radians (float).
  4438. */
  4439. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  4440. var sin = Math.sin(angle / 2);
  4441. axis.normalize();
  4442. result.w = Math.cos(angle / 2);
  4443. result.x = axis.x * sin;
  4444. result.y = axis.y * sin;
  4445. result.z = axis.z * sin;
  4446. return result;
  4447. };
  4448. /**
  4449. * Retuns a new Quaternion set from the starting index of the passed array.
  4450. */
  4451. Quaternion.FromArray = function (array, offset) {
  4452. if (!offset) {
  4453. offset = 0;
  4454. }
  4455. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4456. };
  4457. /**
  4458. * Returns a new Quaternion set from the passed Euler float angles (y, x, z).
  4459. */
  4460. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4461. var q = new Quaternion();
  4462. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  4463. return q;
  4464. };
  4465. /**
  4466. * Sets the passed quaternion "result" from the passed float Euler angles (y, x, z).
  4467. */
  4468. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  4469. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  4470. var halfRoll = roll * 0.5;
  4471. var halfPitch = pitch * 0.5;
  4472. var halfYaw = yaw * 0.5;
  4473. var sinRoll = Math.sin(halfRoll);
  4474. var cosRoll = Math.cos(halfRoll);
  4475. var sinPitch = Math.sin(halfPitch);
  4476. var cosPitch = Math.cos(halfPitch);
  4477. var sinYaw = Math.sin(halfYaw);
  4478. var cosYaw = Math.cos(halfYaw);
  4479. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  4480. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  4481. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  4482. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  4483. };
  4484. /**
  4485. * Returns a new Quaternion from the passed float Euler angles expressed in z-x-z orientation
  4486. */
  4487. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  4488. var result = new Quaternion();
  4489. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  4490. return result;
  4491. };
  4492. /**
  4493. * Sets the passed quaternion "result" from the passed float Euler angles expressed in z-x-z orientation
  4494. */
  4495. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  4496. // Produces a quaternion from Euler angles in the z-x-z orientation
  4497. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  4498. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  4499. var halfBeta = beta * 0.5;
  4500. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4501. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4502. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4503. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4504. };
  4505. /**
  4506. * Returns a new Quaternion as the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  4507. * cf to Vector3.RotationFromAxis() documentation.
  4508. * Note : axis1, axis2 and axis3 are normalized during this operation.
  4509. */
  4510. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3, ref) {
  4511. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  4512. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  4513. return quat;
  4514. };
  4515. /**
  4516. * Sets the passed quaternion "ref" with the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  4517. * cf to Vector3.RotationFromAxis() documentation.
  4518. * Note : axis1, axis2 and axis3 are normalized during this operation.
  4519. */
  4520. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  4521. var rotMat = MathTmp.Matrix[0];
  4522. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  4523. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  4524. };
  4525. Quaternion.Slerp = function (left, right, amount) {
  4526. var result = Quaternion.Identity();
  4527. Quaternion.SlerpToRef(left, right, amount, result);
  4528. return result;
  4529. };
  4530. Quaternion.SlerpToRef = function (left, right, amount, result) {
  4531. var num2;
  4532. var num3;
  4533. var num = amount;
  4534. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  4535. var flag = false;
  4536. if (num4 < 0) {
  4537. flag = true;
  4538. num4 = -num4;
  4539. }
  4540. if (num4 > 0.999999) {
  4541. num3 = 1 - num;
  4542. num2 = flag ? -num : num;
  4543. }
  4544. else {
  4545. var num5 = Math.acos(num4);
  4546. var num6 = (1.0 / Math.sin(num5));
  4547. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  4548. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  4549. }
  4550. result.x = (num3 * left.x) + (num2 * right.x);
  4551. result.y = (num3 * left.y) + (num2 * right.y);
  4552. result.z = (num3 * left.z) + (num2 * right.z);
  4553. result.w = (num3 * left.w) + (num2 * right.w);
  4554. };
  4555. /**
  4556. * Returns a new Quaternion located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  4557. */
  4558. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  4559. var squared = amount * amount;
  4560. var cubed = amount * squared;
  4561. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  4562. var part2 = (-2.0 * cubed) + (3.0 * squared);
  4563. var part3 = (cubed - (2.0 * squared)) + amount;
  4564. var part4 = cubed - squared;
  4565. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  4566. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  4567. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  4568. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  4569. return new Quaternion(x, y, z, w);
  4570. };
  4571. return Quaternion;
  4572. }());
  4573. BABYLON.Quaternion = Quaternion;
  4574. var Matrix = /** @class */ (function () {
  4575. function Matrix() {
  4576. this._isIdentity = false;
  4577. this._isIdentityDirty = true;
  4578. this.m = new Float32Array(16);
  4579. this._markAsUpdated();
  4580. }
  4581. Matrix.prototype._markAsUpdated = function () {
  4582. this.updateFlag = Matrix._updateFlagSeed++;
  4583. this._isIdentityDirty = true;
  4584. };
  4585. // Properties
  4586. /**
  4587. * Boolean : True is the matrix is the identity matrix
  4588. */
  4589. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  4590. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  4591. if (this._isIdentityDirty) {
  4592. this._isIdentityDirty = false;
  4593. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  4594. this._isIdentity = false;
  4595. }
  4596. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  4597. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  4598. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  4599. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  4600. this._isIdentity = false;
  4601. }
  4602. else {
  4603. this._isIdentity = true;
  4604. }
  4605. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  4606. this._isIdentity = false;
  4607. }
  4608. }
  4609. return this._isIdentity;
  4610. };
  4611. /**
  4612. * Returns the matrix determinant (float).
  4613. */
  4614. Matrix.prototype.determinant = function () {
  4615. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  4616. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  4617. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  4618. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  4619. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  4620. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  4621. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  4622. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  4623. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  4624. };
  4625. // Methods
  4626. /**
  4627. * Returns the matrix underlying array.
  4628. */
  4629. Matrix.prototype.toArray = function () {
  4630. return this.m;
  4631. };
  4632. /**
  4633. * Returns the matrix underlying array.
  4634. */
  4635. Matrix.prototype.asArray = function () {
  4636. return this.toArray();
  4637. };
  4638. /**
  4639. * Inverts in place the Matrix.
  4640. * Returns the Matrix inverted.
  4641. */
  4642. Matrix.prototype.invert = function () {
  4643. this.invertToRef(this);
  4644. return this;
  4645. };
  4646. /**
  4647. * Sets all the matrix elements to zero.
  4648. * Returns the Matrix.
  4649. */
  4650. Matrix.prototype.reset = function () {
  4651. for (var index = 0; index < 16; index++) {
  4652. this.m[index] = 0.0;
  4653. }
  4654. this._markAsUpdated();
  4655. return this;
  4656. };
  4657. /**
  4658. * Returns a new Matrix as the addition result of the current Matrix and the passed one.
  4659. */
  4660. Matrix.prototype.add = function (other) {
  4661. var result = new Matrix();
  4662. this.addToRef(other, result);
  4663. return result;
  4664. };
  4665. /**
  4666. * Sets the passed matrix "result" with the ddition result of the current Matrix and the passed one.
  4667. * Returns the Matrix.
  4668. */
  4669. Matrix.prototype.addToRef = function (other, result) {
  4670. for (var index = 0; index < 16; index++) {
  4671. result.m[index] = this.m[index] + other.m[index];
  4672. }
  4673. result._markAsUpdated();
  4674. return this;
  4675. };
  4676. /**
  4677. * Adds in place the passed matrix to the current Matrix.
  4678. * Returns the updated Matrix.
  4679. */
  4680. Matrix.prototype.addToSelf = function (other) {
  4681. for (var index = 0; index < 16; index++) {
  4682. this.m[index] += other.m[index];
  4683. }
  4684. this._markAsUpdated();
  4685. return this;
  4686. };
  4687. /**
  4688. * Sets the passed matrix with the current inverted Matrix.
  4689. * Returns the unmodified current Matrix.
  4690. */
  4691. Matrix.prototype.invertToRef = function (other) {
  4692. var l1 = this.m[0];
  4693. var l2 = this.m[1];
  4694. var l3 = this.m[2];
  4695. var l4 = this.m[3];
  4696. var l5 = this.m[4];
  4697. var l6 = this.m[5];
  4698. var l7 = this.m[6];
  4699. var l8 = this.m[7];
  4700. var l9 = this.m[8];
  4701. var l10 = this.m[9];
  4702. var l11 = this.m[10];
  4703. var l12 = this.m[11];
  4704. var l13 = this.m[12];
  4705. var l14 = this.m[13];
  4706. var l15 = this.m[14];
  4707. var l16 = this.m[15];
  4708. var l17 = (l11 * l16) - (l12 * l15);
  4709. var l18 = (l10 * l16) - (l12 * l14);
  4710. var l19 = (l10 * l15) - (l11 * l14);
  4711. var l20 = (l9 * l16) - (l12 * l13);
  4712. var l21 = (l9 * l15) - (l11 * l13);
  4713. var l22 = (l9 * l14) - (l10 * l13);
  4714. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  4715. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  4716. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  4717. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  4718. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  4719. var l28 = (l7 * l16) - (l8 * l15);
  4720. var l29 = (l6 * l16) - (l8 * l14);
  4721. var l30 = (l6 * l15) - (l7 * l14);
  4722. var l31 = (l5 * l16) - (l8 * l13);
  4723. var l32 = (l5 * l15) - (l7 * l13);
  4724. var l33 = (l5 * l14) - (l6 * l13);
  4725. var l34 = (l7 * l12) - (l8 * l11);
  4726. var l35 = (l6 * l12) - (l8 * l10);
  4727. var l36 = (l6 * l11) - (l7 * l10);
  4728. var l37 = (l5 * l12) - (l8 * l9);
  4729. var l38 = (l5 * l11) - (l7 * l9);
  4730. var l39 = (l5 * l10) - (l6 * l9);
  4731. other.m[0] = l23 * l27;
  4732. other.m[4] = l24 * l27;
  4733. other.m[8] = l25 * l27;
  4734. other.m[12] = l26 * l27;
  4735. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  4736. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  4737. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  4738. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  4739. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  4740. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  4741. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  4742. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  4743. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  4744. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  4745. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  4746. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  4747. other._markAsUpdated();
  4748. return this;
  4749. };
  4750. /**
  4751. * Inserts the translation vector (using 3 x floats) in the current Matrix.
  4752. * Returns the updated Matrix.
  4753. */
  4754. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  4755. this.m[12] = x;
  4756. this.m[13] = y;
  4757. this.m[14] = z;
  4758. this._markAsUpdated();
  4759. return this;
  4760. };
  4761. /**
  4762. * Inserts the translation vector in the current Matrix.
  4763. * Returns the updated Matrix.
  4764. */
  4765. Matrix.prototype.setTranslation = function (vector3) {
  4766. this.m[12] = vector3.x;
  4767. this.m[13] = vector3.y;
  4768. this.m[14] = vector3.z;
  4769. this._markAsUpdated();
  4770. return this;
  4771. };
  4772. /**
  4773. * Returns a new Vector3 as the extracted translation from the Matrix.
  4774. */
  4775. Matrix.prototype.getTranslation = function () {
  4776. return new Vector3(this.m[12], this.m[13], this.m[14]);
  4777. };
  4778. /**
  4779. * Fill a Vector3 with the extracted translation from the Matrix.
  4780. */
  4781. Matrix.prototype.getTranslationToRef = function (result) {
  4782. result.x = this.m[12];
  4783. result.y = this.m[13];
  4784. result.z = this.m[14];
  4785. return this;
  4786. };
  4787. /**
  4788. * Remove rotation and scaling part from the Matrix.
  4789. * Returns the updated Matrix.
  4790. */
  4791. Matrix.prototype.removeRotationAndScaling = function () {
  4792. this.setRowFromFloats(0, 1, 0, 0, 0);
  4793. this.setRowFromFloats(1, 0, 1, 0, 0);
  4794. this.setRowFromFloats(2, 0, 0, 1, 0);
  4795. return this;
  4796. };
  4797. /**
  4798. * Returns a new Matrix set with the multiplication result of the current Matrix and the passed one.
  4799. */
  4800. Matrix.prototype.multiply = function (other) {
  4801. var result = new Matrix();
  4802. this.multiplyToRef(other, result);
  4803. return result;
  4804. };
  4805. /**
  4806. * Updates the current Matrix from the passed one values.
  4807. * Returns the updated Matrix.
  4808. */
  4809. Matrix.prototype.copyFrom = function (other) {
  4810. for (var index = 0; index < 16; index++) {
  4811. this.m[index] = other.m[index];
  4812. }
  4813. this._markAsUpdated();
  4814. return this;
  4815. };
  4816. /**
  4817. * Populates the passed array from the starting index with the Matrix values.
  4818. * Returns the Matrix.
  4819. */
  4820. Matrix.prototype.copyToArray = function (array, offset) {
  4821. if (offset === void 0) { offset = 0; }
  4822. for (var index = 0; index < 16; index++) {
  4823. array[offset + index] = this.m[index];
  4824. }
  4825. return this;
  4826. };
  4827. /**
  4828. * Sets the passed matrix "result" with the multiplication result of the current Matrix and the passed one.
  4829. */
  4830. Matrix.prototype.multiplyToRef = function (other, result) {
  4831. this.multiplyToArray(other, result.m, 0);
  4832. result._markAsUpdated();
  4833. return this;
  4834. };
  4835. /**
  4836. * Sets the Float32Array "result" from the passed index "offset" with the multiplication result of the current Matrix and the passed one.
  4837. */
  4838. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  4839. var tm0 = this.m[0];
  4840. var tm1 = this.m[1];
  4841. var tm2 = this.m[2];
  4842. var tm3 = this.m[3];
  4843. var tm4 = this.m[4];
  4844. var tm5 = this.m[5];
  4845. var tm6 = this.m[6];
  4846. var tm7 = this.m[7];
  4847. var tm8 = this.m[8];
  4848. var tm9 = this.m[9];
  4849. var tm10 = this.m[10];
  4850. var tm11 = this.m[11];
  4851. var tm12 = this.m[12];
  4852. var tm13 = this.m[13];
  4853. var tm14 = this.m[14];
  4854. var tm15 = this.m[15];
  4855. var om0 = other.m[0];
  4856. var om1 = other.m[1];
  4857. var om2 = other.m[2];
  4858. var om3 = other.m[3];
  4859. var om4 = other.m[4];
  4860. var om5 = other.m[5];
  4861. var om6 = other.m[6];
  4862. var om7 = other.m[7];
  4863. var om8 = other.m[8];
  4864. var om9 = other.m[9];
  4865. var om10 = other.m[10];
  4866. var om11 = other.m[11];
  4867. var om12 = other.m[12];
  4868. var om13 = other.m[13];
  4869. var om14 = other.m[14];
  4870. var om15 = other.m[15];
  4871. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  4872. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  4873. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  4874. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  4875. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  4876. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  4877. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  4878. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  4879. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  4880. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  4881. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  4882. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  4883. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  4884. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  4885. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  4886. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  4887. return this;
  4888. };
  4889. /**
  4890. * Boolean : True is the current Matrix and the passed one values are strictly equal.
  4891. */
  4892. Matrix.prototype.equals = function (value) {
  4893. return value &&
  4894. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  4895. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  4896. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  4897. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  4898. };
  4899. /**
  4900. * Returns a new Matrix from the current Matrix.
  4901. */
  4902. Matrix.prototype.clone = function () {
  4903. return Matrix.FromValues(this.m[0], this.m[1], this.m[2], this.m[3], this.m[4], this.m[5], this.m[6], this.m[7], this.m[8], this.m[9], this.m[10], this.m[11], this.m[12], this.m[13], this.m[14], this.m[15]);
  4904. };
  4905. /**
  4906. * Returns the string "Matrix"
  4907. */
  4908. Matrix.prototype.getClassName = function () {
  4909. return "Matrix";
  4910. };
  4911. /**
  4912. * Returns the Matrix hash code.
  4913. */
  4914. Matrix.prototype.getHashCode = function () {
  4915. var hash = this.m[0] || 0;
  4916. for (var i = 1; i < 16; i++) {
  4917. hash = (hash * 397) ^ (this.m[i] || 0);
  4918. }
  4919. return hash;
  4920. };
  4921. /**
  4922. * Decomposes the current Matrix into :
  4923. * - a scale vector3 passed as a reference to update,
  4924. * - a rotation quaternion passed as a reference to update,
  4925. * - a translation vector3 passed as a reference to update.
  4926. * Returns the true if operation was successful.
  4927. */
  4928. Matrix.prototype.decompose = function (scale, rotation, translation) {
  4929. translation.x = this.m[12];
  4930. translation.y = this.m[13];
  4931. translation.z = this.m[14];
  4932. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  4933. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  4934. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  4935. if (this.determinant() <= 0) {
  4936. scale.y *= -1;
  4937. }
  4938. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  4939. rotation.x = 0;
  4940. rotation.y = 0;
  4941. rotation.z = 0;
  4942. rotation.w = 1;
  4943. return false;
  4944. }
  4945. Matrix.FromValuesToRef(this.m[0] / scale.x, this.m[1] / scale.x, this.m[2] / scale.x, 0, this.m[4] / scale.y, this.m[5] / scale.y, this.m[6] / scale.y, 0, this.m[8] / scale.z, this.m[9] / scale.z, this.m[10] / scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[0]);
  4946. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  4947. return true;
  4948. };
  4949. /**
  4950. * Returns a new Matrix as the extracted rotation matrix from the current one.
  4951. */
  4952. Matrix.prototype.getRotationMatrix = function () {
  4953. var result = Matrix.Identity();
  4954. this.getRotationMatrixToRef(result);
  4955. return result;
  4956. };
  4957. /**
  4958. * Extracts the rotation matrix from the current one and sets it as the passed "result".
  4959. * Returns the current Matrix.
  4960. */
  4961. Matrix.prototype.getRotationMatrixToRef = function (result) {
  4962. var m = this.m;
  4963. var xs = m[0] * m[1] * m[2] * m[3] < 0 ? -1 : 1;
  4964. var ys = m[4] * m[5] * m[6] * m[7] < 0 ? -1 : 1;
  4965. var zs = m[8] * m[9] * m[10] * m[11] < 0 ? -1 : 1;
  4966. var sx = xs * Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  4967. var sy = ys * Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  4968. var sz = zs * Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  4969. Matrix.FromValuesToRef(m[0] / sx, m[1] / sx, m[2] / sx, 0, m[4] / sy, m[5] / sy, m[6] / sy, 0, m[8] / sz, m[9] / sz, m[10] / sz, 0, 0, 0, 0, 1, result);
  4970. return this;
  4971. };
  4972. // Statics
  4973. /**
  4974. * Returns a new Matrix set from the starting index of the passed array.
  4975. */
  4976. Matrix.FromArray = function (array, offset) {
  4977. var result = new Matrix();
  4978. if (!offset) {
  4979. offset = 0;
  4980. }
  4981. Matrix.FromArrayToRef(array, offset, result);
  4982. return result;
  4983. };
  4984. /**
  4985. * Sets the passed "result" matrix from the starting index of the passed array.
  4986. */
  4987. Matrix.FromArrayToRef = function (array, offset, result) {
  4988. for (var index = 0; index < 16; index++) {
  4989. result.m[index] = array[index + offset];
  4990. }
  4991. result._markAsUpdated();
  4992. };
  4993. /**
  4994. * Sets the passed "result" matrix from the starting index of the passed Float32Array by multiplying each element by the float "scale".
  4995. */
  4996. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  4997. for (var index = 0; index < 16; index++) {
  4998. result.m[index] = array[index + offset] * scale;
  4999. }
  5000. result._markAsUpdated();
  5001. };
  5002. /**
  5003. * Sets the passed matrix "result" with the 16 passed floats.
  5004. */
  5005. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  5006. result.m[0] = initialM11;
  5007. result.m[1] = initialM12;
  5008. result.m[2] = initialM13;
  5009. result.m[3] = initialM14;
  5010. result.m[4] = initialM21;
  5011. result.m[5] = initialM22;
  5012. result.m[6] = initialM23;
  5013. result.m[7] = initialM24;
  5014. result.m[8] = initialM31;
  5015. result.m[9] = initialM32;
  5016. result.m[10] = initialM33;
  5017. result.m[11] = initialM34;
  5018. result.m[12] = initialM41;
  5019. result.m[13] = initialM42;
  5020. result.m[14] = initialM43;
  5021. result.m[15] = initialM44;
  5022. result._markAsUpdated();
  5023. };
  5024. /**
  5025. * Returns the index-th row of the current matrix as a new Vector4.
  5026. */
  5027. Matrix.prototype.getRow = function (index) {
  5028. if (index < 0 || index > 3) {
  5029. return null;
  5030. }
  5031. var i = index * 4;
  5032. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  5033. };
  5034. /**
  5035. * Sets the index-th row of the current matrix with the passed Vector4 values.
  5036. * Returns the updated Matrix.
  5037. */
  5038. Matrix.prototype.setRow = function (index, row) {
  5039. if (index < 0 || index > 3) {
  5040. return this;
  5041. }
  5042. var i = index * 4;
  5043. this.m[i + 0] = row.x;
  5044. this.m[i + 1] = row.y;
  5045. this.m[i + 2] = row.z;
  5046. this.m[i + 3] = row.w;
  5047. this._markAsUpdated();
  5048. return this;
  5049. };
  5050. /**
  5051. * Compute the transpose of the matrix.
  5052. * Returns a new Matrix.
  5053. */
  5054. Matrix.prototype.transpose = function () {
  5055. return Matrix.Transpose(this);
  5056. };
  5057. /**
  5058. * Compute the transpose of the matrix.
  5059. * Returns the current matrix.
  5060. */
  5061. Matrix.prototype.transposeToRef = function (result) {
  5062. Matrix.TransposeToRef(this, result);
  5063. return this;
  5064. };
  5065. /**
  5066. * Sets the index-th row of the current matrix with the passed 4 x float values.
  5067. * Returns the updated Matrix.
  5068. */
  5069. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  5070. if (index < 0 || index > 3) {
  5071. return this;
  5072. }
  5073. var i = index * 4;
  5074. this.m[i + 0] = x;
  5075. this.m[i + 1] = y;
  5076. this.m[i + 2] = z;
  5077. this.m[i + 3] = w;
  5078. this._markAsUpdated();
  5079. return this;
  5080. };
  5081. Object.defineProperty(Matrix, "IdentityReadOnly", {
  5082. /**
  5083. * Static identity matrix to be used as readonly matrix
  5084. * Must not be updated.
  5085. */
  5086. get: function () {
  5087. return Matrix._identityReadOnly;
  5088. },
  5089. enumerable: true,
  5090. configurable: true
  5091. });
  5092. /**
  5093. * Returns a new Matrix set from the 16 passed floats.
  5094. */
  5095. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  5096. var result = new Matrix();
  5097. result.m[0] = initialM11;
  5098. result.m[1] = initialM12;
  5099. result.m[2] = initialM13;
  5100. result.m[3] = initialM14;
  5101. result.m[4] = initialM21;
  5102. result.m[5] = initialM22;
  5103. result.m[6] = initialM23;
  5104. result.m[7] = initialM24;
  5105. result.m[8] = initialM31;
  5106. result.m[9] = initialM32;
  5107. result.m[10] = initialM33;
  5108. result.m[11] = initialM34;
  5109. result.m[12] = initialM41;
  5110. result.m[13] = initialM42;
  5111. result.m[14] = initialM43;
  5112. result.m[15] = initialM44;
  5113. return result;
  5114. };
  5115. /**
  5116. * Returns a new Matrix composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  5117. */
  5118. Matrix.Compose = function (scale, rotation, translation) {
  5119. var result = Matrix.Identity();
  5120. Matrix.ComposeToRef(scale, rotation, translation, result);
  5121. return result;
  5122. };
  5123. /**
  5124. * Update a Matrix with values composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  5125. */
  5126. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  5127. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  5128. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  5129. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  5130. result.setTranslation(translation);
  5131. };
  5132. /**
  5133. * Returns a new indentity Matrix.
  5134. */
  5135. Matrix.Identity = function () {
  5136. return Matrix.FromValues(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0);
  5137. };
  5138. /**
  5139. * Sets the passed "result" as an identity matrix.
  5140. */
  5141. Matrix.IdentityToRef = function (result) {
  5142. Matrix.FromValuesToRef(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, result);
  5143. };
  5144. /**
  5145. * Returns a new zero Matrix.
  5146. */
  5147. Matrix.Zero = function () {
  5148. return Matrix.FromValues(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0);
  5149. };
  5150. /**
  5151. * Returns a new rotation matrix for "angle" radians around the X axis.
  5152. */
  5153. Matrix.RotationX = function (angle) {
  5154. var result = new Matrix();
  5155. Matrix.RotationXToRef(angle, result);
  5156. return result;
  5157. };
  5158. /**
  5159. * Returns a new Matrix as the passed inverted one.
  5160. */
  5161. Matrix.Invert = function (source) {
  5162. var result = new Matrix();
  5163. source.invertToRef(result);
  5164. return result;
  5165. };
  5166. /**
  5167. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the X axis.
  5168. */
  5169. Matrix.RotationXToRef = function (angle, result) {
  5170. var s = Math.sin(angle);
  5171. var c = Math.cos(angle);
  5172. result.m[0] = 1.0;
  5173. result.m[15] = 1.0;
  5174. result.m[5] = c;
  5175. result.m[10] = c;
  5176. result.m[9] = -s;
  5177. result.m[6] = s;
  5178. result.m[1] = 0.0;
  5179. result.m[2] = 0.0;
  5180. result.m[3] = 0.0;
  5181. result.m[4] = 0.0;
  5182. result.m[7] = 0.0;
  5183. result.m[8] = 0.0;
  5184. result.m[11] = 0.0;
  5185. result.m[12] = 0.0;
  5186. result.m[13] = 0.0;
  5187. result.m[14] = 0.0;
  5188. result._markAsUpdated();
  5189. };
  5190. /**
  5191. * Returns a new rotation matrix for "angle" radians around the Y axis.
  5192. */
  5193. Matrix.RotationY = function (angle) {
  5194. var result = new Matrix();
  5195. Matrix.RotationYToRef(angle, result);
  5196. return result;
  5197. };
  5198. /**
  5199. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Y axis.
  5200. */
  5201. Matrix.RotationYToRef = function (angle, result) {
  5202. var s = Math.sin(angle);
  5203. var c = Math.cos(angle);
  5204. result.m[5] = 1.0;
  5205. result.m[15] = 1.0;
  5206. result.m[0] = c;
  5207. result.m[2] = -s;
  5208. result.m[8] = s;
  5209. result.m[10] = c;
  5210. result.m[1] = 0.0;
  5211. result.m[3] = 0.0;
  5212. result.m[4] = 0.0;
  5213. result.m[6] = 0.0;
  5214. result.m[7] = 0.0;
  5215. result.m[9] = 0.0;
  5216. result.m[11] = 0.0;
  5217. result.m[12] = 0.0;
  5218. result.m[13] = 0.0;
  5219. result.m[14] = 0.0;
  5220. result._markAsUpdated();
  5221. };
  5222. /**
  5223. * Returns a new rotation matrix for "angle" radians around the Z axis.
  5224. */
  5225. Matrix.RotationZ = function (angle) {
  5226. var result = new Matrix();
  5227. Matrix.RotationZToRef(angle, result);
  5228. return result;
  5229. };
  5230. /**
  5231. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Z axis.
  5232. */
  5233. Matrix.RotationZToRef = function (angle, result) {
  5234. var s = Math.sin(angle);
  5235. var c = Math.cos(angle);
  5236. result.m[10] = 1.0;
  5237. result.m[15] = 1.0;
  5238. result.m[0] = c;
  5239. result.m[1] = s;
  5240. result.m[4] = -s;
  5241. result.m[5] = c;
  5242. result.m[2] = 0.0;
  5243. result.m[3] = 0.0;
  5244. result.m[6] = 0.0;
  5245. result.m[7] = 0.0;
  5246. result.m[8] = 0.0;
  5247. result.m[9] = 0.0;
  5248. result.m[11] = 0.0;
  5249. result.m[12] = 0.0;
  5250. result.m[13] = 0.0;
  5251. result.m[14] = 0.0;
  5252. result._markAsUpdated();
  5253. };
  5254. /**
  5255. * Returns a new rotation matrix for "angle" radians around the passed axis.
  5256. */
  5257. Matrix.RotationAxis = function (axis, angle) {
  5258. var result = Matrix.Zero();
  5259. Matrix.RotationAxisToRef(axis, angle, result);
  5260. return result;
  5261. };
  5262. /**
  5263. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the passed axis.
  5264. */
  5265. Matrix.RotationAxisToRef = function (axis, angle, result) {
  5266. var s = Math.sin(-angle);
  5267. var c = Math.cos(-angle);
  5268. var c1 = 1 - c;
  5269. axis.normalize();
  5270. result.m[0] = (axis.x * axis.x) * c1 + c;
  5271. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  5272. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  5273. result.m[3] = 0.0;
  5274. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  5275. result.m[5] = (axis.y * axis.y) * c1 + c;
  5276. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  5277. result.m[7] = 0.0;
  5278. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  5279. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  5280. result.m[10] = (axis.z * axis.z) * c1 + c;
  5281. result.m[11] = 0.0;
  5282. result.m[15] = 1.0;
  5283. result._markAsUpdated();
  5284. };
  5285. /**
  5286. * Returns a new Matrix as a rotation matrix from the Euler angles (y, x, z).
  5287. */
  5288. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  5289. var result = new Matrix();
  5290. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  5291. return result;
  5292. };
  5293. /**
  5294. * Sets the passed matrix "result" as a rotation matrix from the Euler angles (y, x, z).
  5295. */
  5296. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  5297. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  5298. this._tempQuaternion.toRotationMatrix(result);
  5299. };
  5300. /**
  5301. * Returns a new Matrix as a scaling matrix from the passed floats (x, y, z).
  5302. */
  5303. Matrix.Scaling = function (x, y, z) {
  5304. var result = Matrix.Zero();
  5305. Matrix.ScalingToRef(x, y, z, result);
  5306. return result;
  5307. };
  5308. /**
  5309. * Sets the passed matrix "result" as a scaling matrix from the passed floats (x, y, z).
  5310. */
  5311. Matrix.ScalingToRef = function (x, y, z, result) {
  5312. result.m[0] = x;
  5313. result.m[1] = 0.0;
  5314. result.m[2] = 0.0;
  5315. result.m[3] = 0.0;
  5316. result.m[4] = 0.0;
  5317. result.m[5] = y;
  5318. result.m[6] = 0.0;
  5319. result.m[7] = 0.0;
  5320. result.m[8] = 0.0;
  5321. result.m[9] = 0.0;
  5322. result.m[10] = z;
  5323. result.m[11] = 0.0;
  5324. result.m[12] = 0.0;
  5325. result.m[13] = 0.0;
  5326. result.m[14] = 0.0;
  5327. result.m[15] = 1.0;
  5328. result._markAsUpdated();
  5329. };
  5330. /**
  5331. * Returns a new Matrix as a translation matrix from the passed floats (x, y, z).
  5332. */
  5333. Matrix.Translation = function (x, y, z) {
  5334. var result = Matrix.Identity();
  5335. Matrix.TranslationToRef(x, y, z, result);
  5336. return result;
  5337. };
  5338. /**
  5339. * Sets the passed matrix "result" as a translation matrix from the passed floats (x, y, z).
  5340. */
  5341. Matrix.TranslationToRef = function (x, y, z, result) {
  5342. Matrix.FromValuesToRef(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, x, y, z, 1.0, result);
  5343. };
  5344. /**
  5345. * Returns a new Matrix whose values are the interpolated values for "gradien" (float) between the ones of the matrices "startValue" and "endValue".
  5346. */
  5347. Matrix.Lerp = function (startValue, endValue, gradient) {
  5348. var result = Matrix.Zero();
  5349. for (var index = 0; index < 16; index++) {
  5350. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  5351. }
  5352. result._markAsUpdated();
  5353. return result;
  5354. };
  5355. /**
  5356. * Returns a new Matrix whose values are computed by :
  5357. * - decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices,
  5358. * - interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end,
  5359. * - recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices.
  5360. */
  5361. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  5362. var startScale = new Vector3(0, 0, 0);
  5363. var startRotation = new Quaternion();
  5364. var startTranslation = new Vector3(0, 0, 0);
  5365. startValue.decompose(startScale, startRotation, startTranslation);
  5366. var endScale = new Vector3(0, 0, 0);
  5367. var endRotation = new Quaternion();
  5368. var endTranslation = new Vector3(0, 0, 0);
  5369. endValue.decompose(endScale, endRotation, endTranslation);
  5370. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  5371. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  5372. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  5373. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  5374. };
  5375. /**
  5376. * Returns a new rotation Matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  5377. * This methods works for a Left-Handed system.
  5378. */
  5379. Matrix.LookAtLH = function (eye, target, up) {
  5380. var result = Matrix.Zero();
  5381. Matrix.LookAtLHToRef(eye, target, up, result);
  5382. return result;
  5383. };
  5384. /**
  5385. * Sets the passed "result" Matrix as a rotation matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  5386. * This methods works for a Left-Handed system.
  5387. */
  5388. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  5389. // Z axis
  5390. target.subtractToRef(eye, this._zAxis);
  5391. this._zAxis.normalize();
  5392. // X axis
  5393. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  5394. if (this._xAxis.lengthSquared() === 0) {
  5395. this._xAxis.x = 1.0;
  5396. }
  5397. else {
  5398. this._xAxis.normalize();
  5399. }
  5400. // Y axis
  5401. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  5402. this._yAxis.normalize();
  5403. // Eye angles
  5404. var ex = -Vector3.Dot(this._xAxis, eye);
  5405. var ey = -Vector3.Dot(this._yAxis, eye);
  5406. var ez = -Vector3.Dot(this._zAxis, eye);
  5407. return Matrix.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result);
  5408. };
  5409. /**
  5410. * Returns a new rotation Matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  5411. * This methods works for a Right-Handed system.
  5412. */
  5413. Matrix.LookAtRH = function (eye, target, up) {
  5414. var result = Matrix.Zero();
  5415. Matrix.LookAtRHToRef(eye, target, up, result);
  5416. return result;
  5417. };
  5418. /**
  5419. * Sets the passed "result" Matrix as a rotation matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  5420. * This methods works for a Left-Handed system.
  5421. */
  5422. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  5423. // Z axis
  5424. eye.subtractToRef(target, this._zAxis);
  5425. this._zAxis.normalize();
  5426. // X axis
  5427. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  5428. if (this._xAxis.lengthSquared() === 0) {
  5429. this._xAxis.x = 1.0;
  5430. }
  5431. else {
  5432. this._xAxis.normalize();
  5433. }
  5434. // Y axis
  5435. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  5436. this._yAxis.normalize();
  5437. // Eye angles
  5438. var ex = -Vector3.Dot(this._xAxis, eye);
  5439. var ey = -Vector3.Dot(this._yAxis, eye);
  5440. var ez = -Vector3.Dot(this._zAxis, eye);
  5441. return Matrix.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result);
  5442. };
  5443. /**
  5444. * Returns a new Matrix as a left-handed orthographic projection matrix computed from the passed floats : width and height of the projection plane, z near and far limits.
  5445. */
  5446. Matrix.OrthoLH = function (width, height, znear, zfar) {
  5447. var matrix = Matrix.Zero();
  5448. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  5449. return matrix;
  5450. };
  5451. /**
  5452. * Sets the passed matrix "result" as a left-handed orthographic projection matrix computed from the passed floats : width and height of the projection plane, z near and far limits.
  5453. */
  5454. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  5455. var n = znear;
  5456. var f = zfar;
  5457. var a = 2.0 / width;
  5458. var b = 2.0 / height;
  5459. var c = 2.0 / (f - n);
  5460. var d = -(f + n) / (f - n);
  5461. Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 0.0, 0.0, 0.0, d, 1.0, result);
  5462. };
  5463. /**
  5464. * Returns a new Matrix as a left-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  5465. */
  5466. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  5467. var matrix = Matrix.Zero();
  5468. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  5469. return matrix;
  5470. };
  5471. /**
  5472. * Sets the passed matrix "result" as a left-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  5473. */
  5474. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  5475. var n = znear;
  5476. var f = zfar;
  5477. var a = 2.0 / (right - left);
  5478. var b = 2.0 / (top - bottom);
  5479. var c = 2.0 / (f - n);
  5480. var d = -(f + n) / (f - n);
  5481. var i0 = (left + right) / (left - right);
  5482. var i1 = (top + bottom) / (bottom - top);
  5483. Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 0.0, i0, i1, d, 1.0, result);
  5484. };
  5485. /**
  5486. * Returns a new Matrix as a right-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  5487. */
  5488. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  5489. var matrix = Matrix.Zero();
  5490. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  5491. return matrix;
  5492. };
  5493. /**
  5494. * Sets the passed matrix "result" as a right-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  5495. */
  5496. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  5497. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  5498. result.m[10] *= -1.0;
  5499. };
  5500. /**
  5501. * Returns a new Matrix as a left-handed perspective projection matrix computed from the passed floats : width and height of the projection plane, z near and far limits.
  5502. */
  5503. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  5504. var matrix = Matrix.Zero();
  5505. var n = znear;
  5506. var f = zfar;
  5507. var a = 2.0 * n / width;
  5508. var b = 2.0 * n / height;
  5509. var c = (f + n) / (f - n);
  5510. var d = -2.0 * f * n / (f - n);
  5511. Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 1.0, 0.0, 0.0, d, 0.0, matrix);
  5512. return matrix;
  5513. };
  5514. /**
  5515. * Returns a new Matrix as a left-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  5516. */
  5517. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  5518. var matrix = Matrix.Zero();
  5519. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  5520. return matrix;
  5521. };
  5522. /**
  5523. * Sets the passed matrix "result" as a left-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  5524. */
  5525. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  5526. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  5527. var n = znear;
  5528. var f = zfar;
  5529. var t = 1.0 / (Math.tan(fov * 0.5));
  5530. var a = isVerticalFovFixed ? (t / aspect) : t;
  5531. var b = isVerticalFovFixed ? t : (t * aspect);
  5532. var c = (f + n) / (f - n);
  5533. var d = -2.0 * f * n / (f - n);
  5534. Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 1.0, 0.0, 0.0, d, 0.0, result);
  5535. };
  5536. /**
  5537. * Returns a new Matrix as a right-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  5538. */
  5539. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  5540. var matrix = Matrix.Zero();
  5541. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  5542. return matrix;
  5543. };
  5544. /**
  5545. * Sets the passed matrix "result" as a right-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  5546. */
  5547. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  5548. //alternatively this could be expressed as:
  5549. // m = PerspectiveFovLHToRef
  5550. // m[10] *= -1.0;
  5551. // m[11] *= -1.0;
  5552. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  5553. var n = znear;
  5554. var f = zfar;
  5555. var t = 1.0 / (Math.tan(fov * 0.5));
  5556. var a = isVerticalFovFixed ? (t / aspect) : t;
  5557. var b = isVerticalFovFixed ? t : (t * aspect);
  5558. var c = -(f + n) / (f - n);
  5559. var d = -2 * f * n / (f - n);
  5560. Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, -1.0, 0.0, 0.0, d, 0.0, result);
  5561. };
  5562. /**
  5563. * Sets the passed matrix "result" as a left-handed perspective projection matrix for WebVR computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  5564. */
  5565. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  5566. if (rightHanded === void 0) { rightHanded = false; }
  5567. var rightHandedFactor = rightHanded ? -1 : 1;
  5568. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  5569. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  5570. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  5571. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  5572. var xScale = 2.0 / (leftTan + rightTan);
  5573. var yScale = 2.0 / (upTan + downTan);
  5574. result.m[0] = xScale;
  5575. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  5576. result.m[5] = yScale;
  5577. result.m[6] = result.m[7] = 0.0;
  5578. result.m[8] = ((leftTan - rightTan) * xScale * 0.5); // * rightHandedFactor;
  5579. result.m[9] = -((upTan - downTan) * yScale * 0.5); // * rightHandedFactor;
  5580. //result.m[10] = -(znear + zfar) / (zfar - znear) * rightHandedFactor;
  5581. result.m[10] = -zfar / (znear - zfar);
  5582. result.m[11] = 1.0 * rightHandedFactor;
  5583. result.m[12] = result.m[13] = result.m[15] = 0.0;
  5584. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  5585. // result.m[14] = (znear * zfar) / (znear - zfar);
  5586. result._markAsUpdated();
  5587. };
  5588. /**
  5589. * Returns the final transformation matrix : world * view * projection * viewport
  5590. */
  5591. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  5592. var cw = viewport.width;
  5593. var ch = viewport.height;
  5594. var cx = viewport.x;
  5595. var cy = viewport.y;
  5596. var viewportMatrix = Matrix.FromValues(cw / 2.0, 0.0, 0.0, 0.0, 0.0, -ch / 2.0, 0.0, 0.0, 0.0, 0.0, zmax - zmin, 0.0, cx + cw / 2.0, ch / 2.0 + cy, zmin, 1);
  5597. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  5598. };
  5599. /**
  5600. * Returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the passed Matrix.
  5601. */
  5602. Matrix.GetAsMatrix2x2 = function (matrix) {
  5603. return new Float32Array([
  5604. matrix.m[0], matrix.m[1],
  5605. matrix.m[4], matrix.m[5]
  5606. ]);
  5607. };
  5608. /**
  5609. * Returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the passed Matrix.
  5610. */
  5611. Matrix.GetAsMatrix3x3 = function (matrix) {
  5612. return new Float32Array([
  5613. matrix.m[0], matrix.m[1], matrix.m[2],
  5614. matrix.m[4], matrix.m[5], matrix.m[6],
  5615. matrix.m[8], matrix.m[9], matrix.m[10]
  5616. ]);
  5617. };
  5618. /**
  5619. * Compute the transpose of the passed Matrix.
  5620. * Returns a new Matrix.
  5621. */
  5622. Matrix.Transpose = function (matrix) {
  5623. var result = new Matrix();
  5624. Matrix.TransposeToRef(matrix, result);
  5625. return result;
  5626. };
  5627. /**
  5628. * Compute the transpose of the passed Matrix and store it in the result matrix.
  5629. */
  5630. Matrix.TransposeToRef = function (matrix, result) {
  5631. result.m[0] = matrix.m[0];
  5632. result.m[1] = matrix.m[4];
  5633. result.m[2] = matrix.m[8];
  5634. result.m[3] = matrix.m[12];
  5635. result.m[4] = matrix.m[1];
  5636. result.m[5] = matrix.m[5];
  5637. result.m[6] = matrix.m[9];
  5638. result.m[7] = matrix.m[13];
  5639. result.m[8] = matrix.m[2];
  5640. result.m[9] = matrix.m[6];
  5641. result.m[10] = matrix.m[10];
  5642. result.m[11] = matrix.m[14];
  5643. result.m[12] = matrix.m[3];
  5644. result.m[13] = matrix.m[7];
  5645. result.m[14] = matrix.m[11];
  5646. result.m[15] = matrix.m[15];
  5647. };
  5648. /**
  5649. * Returns a new Matrix as the reflection matrix across the passed plane.
  5650. */
  5651. Matrix.Reflection = function (plane) {
  5652. var matrix = new Matrix();
  5653. Matrix.ReflectionToRef(plane, matrix);
  5654. return matrix;
  5655. };
  5656. /**
  5657. * Sets the passed matrix "result" as the reflection matrix across the passed plane.
  5658. */
  5659. Matrix.ReflectionToRef = function (plane, result) {
  5660. plane.normalize();
  5661. var x = plane.normal.x;
  5662. var y = plane.normal.y;
  5663. var z = plane.normal.z;
  5664. var temp = -2 * x;
  5665. var temp2 = -2 * y;
  5666. var temp3 = -2 * z;
  5667. result.m[0] = (temp * x) + 1;
  5668. result.m[1] = temp2 * x;
  5669. result.m[2] = temp3 * x;
  5670. result.m[3] = 0.0;
  5671. result.m[4] = temp * y;
  5672. result.m[5] = (temp2 * y) + 1;
  5673. result.m[6] = temp3 * y;
  5674. result.m[7] = 0.0;
  5675. result.m[8] = temp * z;
  5676. result.m[9] = temp2 * z;
  5677. result.m[10] = (temp3 * z) + 1;
  5678. result.m[11] = 0.0;
  5679. result.m[12] = temp * plane.d;
  5680. result.m[13] = temp2 * plane.d;
  5681. result.m[14] = temp3 * plane.d;
  5682. result.m[15] = 1.0;
  5683. result._markAsUpdated();
  5684. };
  5685. /**
  5686. * Sets the passed matrix "mat" as a rotation matrix composed from the 3 passed left handed axis.
  5687. */
  5688. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  5689. result.m[0] = xaxis.x;
  5690. result.m[1] = xaxis.y;
  5691. result.m[2] = xaxis.z;
  5692. result.m[3] = 0.0;
  5693. result.m[4] = yaxis.x;
  5694. result.m[5] = yaxis.y;
  5695. result.m[6] = yaxis.z;
  5696. result.m[7] = 0.0;
  5697. result.m[8] = zaxis.x;
  5698. result.m[9] = zaxis.y;
  5699. result.m[10] = zaxis.z;
  5700. result.m[11] = 0.0;
  5701. result.m[12] = 0.0;
  5702. result.m[13] = 0.0;
  5703. result.m[14] = 0.0;
  5704. result.m[15] = 1.0;
  5705. result._markAsUpdated();
  5706. };
  5707. /**
  5708. * Sets the passed matrix "result" as a rotation matrix according to the passed quaternion.
  5709. */
  5710. Matrix.FromQuaternionToRef = function (quat, result) {
  5711. var xx = quat.x * quat.x;
  5712. var yy = quat.y * quat.y;
  5713. var zz = quat.z * quat.z;
  5714. var xy = quat.x * quat.y;
  5715. var zw = quat.z * quat.w;
  5716. var zx = quat.z * quat.x;
  5717. var yw = quat.y * quat.w;
  5718. var yz = quat.y * quat.z;
  5719. var xw = quat.x * quat.w;
  5720. result.m[0] = 1.0 - (2.0 * (yy + zz));
  5721. result.m[1] = 2.0 * (xy + zw);
  5722. result.m[2] = 2.0 * (zx - yw);
  5723. result.m[3] = 0.0;
  5724. result.m[4] = 2.0 * (xy - zw);
  5725. result.m[5] = 1.0 - (2.0 * (zz + xx));
  5726. result.m[6] = 2.0 * (yz + xw);
  5727. result.m[7] = 0.0;
  5728. result.m[8] = 2.0 * (zx + yw);
  5729. result.m[9] = 2.0 * (yz - xw);
  5730. result.m[10] = 1.0 - (2.0 * (yy + xx));
  5731. result.m[11] = 0.0;
  5732. result.m[12] = 0.0;
  5733. result.m[13] = 0.0;
  5734. result.m[14] = 0.0;
  5735. result.m[15] = 1.0;
  5736. result._markAsUpdated();
  5737. };
  5738. Matrix._tempQuaternion = new Quaternion();
  5739. Matrix._xAxis = Vector3.Zero();
  5740. Matrix._yAxis = Vector3.Zero();
  5741. Matrix._zAxis = Vector3.Zero();
  5742. Matrix._updateFlagSeed = 0;
  5743. Matrix._identityReadOnly = Matrix.Identity();
  5744. return Matrix;
  5745. }());
  5746. BABYLON.Matrix = Matrix;
  5747. var Plane = /** @class */ (function () {
  5748. /**
  5749. * Creates a Plane object according to the passed floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  5750. */
  5751. function Plane(a, b, c, d) {
  5752. this.normal = new Vector3(a, b, c);
  5753. this.d = d;
  5754. }
  5755. /**
  5756. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  5757. */
  5758. Plane.prototype.asArray = function () {
  5759. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  5760. };
  5761. // Methods
  5762. /**
  5763. * Returns a new plane copied from the current Plane.
  5764. */
  5765. Plane.prototype.clone = function () {
  5766. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  5767. };
  5768. /**
  5769. * Returns the string "Plane".
  5770. */
  5771. Plane.prototype.getClassName = function () {
  5772. return "Plane";
  5773. };
  5774. /**
  5775. * Returns the Plane hash code.
  5776. */
  5777. Plane.prototype.getHashCode = function () {
  5778. var hash = this.normal.getHashCode();
  5779. hash = (hash * 397) ^ (this.d || 0);
  5780. return hash;
  5781. };
  5782. /**
  5783. * Normalize the current Plane in place.
  5784. * Returns the updated Plane.
  5785. */
  5786. Plane.prototype.normalize = function () {
  5787. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  5788. var magnitude = 0.0;
  5789. if (norm !== 0) {
  5790. magnitude = 1.0 / norm;
  5791. }
  5792. this.normal.x *= magnitude;
  5793. this.normal.y *= magnitude;
  5794. this.normal.z *= magnitude;
  5795. this.d *= magnitude;
  5796. return this;
  5797. };
  5798. /**
  5799. * Returns a new Plane as the result of the transformation of the current Plane by the passed matrix.
  5800. */
  5801. Plane.prototype.transform = function (transformation) {
  5802. var transposedMatrix = Matrix.Transpose(transformation);
  5803. var x = this.normal.x;
  5804. var y = this.normal.y;
  5805. var z = this.normal.z;
  5806. var d = this.d;
  5807. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  5808. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  5809. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  5810. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  5811. return new Plane(normalX, normalY, normalZ, finalD);
  5812. };
  5813. /**
  5814. * Returns the dot product (float) of the point coordinates and the plane normal.
  5815. */
  5816. Plane.prototype.dotCoordinate = function (point) {
  5817. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  5818. };
  5819. /**
  5820. * Updates the current Plane from the plane defined by the three passed points.
  5821. * Returns the updated Plane.
  5822. */
  5823. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  5824. var x1 = point2.x - point1.x;
  5825. var y1 = point2.y - point1.y;
  5826. var z1 = point2.z - point1.z;
  5827. var x2 = point3.x - point1.x;
  5828. var y2 = point3.y - point1.y;
  5829. var z2 = point3.z - point1.z;
  5830. var yz = (y1 * z2) - (z1 * y2);
  5831. var xz = (z1 * x2) - (x1 * z2);
  5832. var xy = (x1 * y2) - (y1 * x2);
  5833. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  5834. var invPyth;
  5835. if (pyth !== 0) {
  5836. invPyth = 1.0 / pyth;
  5837. }
  5838. else {
  5839. invPyth = 0.0;
  5840. }
  5841. this.normal.x = yz * invPyth;
  5842. this.normal.y = xz * invPyth;
  5843. this.normal.z = xy * invPyth;
  5844. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  5845. return this;
  5846. };
  5847. /**
  5848. * Boolean : True is the vector "direction" is the same side than the plane normal.
  5849. */
  5850. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  5851. var dot = Vector3.Dot(this.normal, direction);
  5852. return (dot <= epsilon);
  5853. };
  5854. /**
  5855. * Returns the signed distance (float) from the passed point to the Plane.
  5856. */
  5857. Plane.prototype.signedDistanceTo = function (point) {
  5858. return Vector3.Dot(point, this.normal) + this.d;
  5859. };
  5860. // Statics
  5861. /**
  5862. * Returns a new Plane from the passed array.
  5863. */
  5864. Plane.FromArray = function (array) {
  5865. return new Plane(array[0], array[1], array[2], array[3]);
  5866. };
  5867. /**
  5868. * Returns a new Plane defined by the three passed points.
  5869. */
  5870. Plane.FromPoints = function (point1, point2, point3) {
  5871. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  5872. result.copyFromPoints(point1, point2, point3);
  5873. return result;
  5874. };
  5875. /**
  5876. * Returns a new Plane the normal vector to this plane at the passed origin point.
  5877. * Note : the vector "normal" is updated because normalized.
  5878. */
  5879. Plane.FromPositionAndNormal = function (origin, normal) {
  5880. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  5881. normal.normalize();
  5882. result.normal = normal;
  5883. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  5884. return result;
  5885. };
  5886. /**
  5887. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the passed other point.
  5888. */
  5889. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  5890. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  5891. return Vector3.Dot(point, normal) + d;
  5892. };
  5893. return Plane;
  5894. }());
  5895. BABYLON.Plane = Plane;
  5896. var Viewport = /** @class */ (function () {
  5897. /**
  5898. * Creates a Viewport object located at (x, y) and sized (width, height).
  5899. */
  5900. function Viewport(x, y, width, height) {
  5901. this.x = x;
  5902. this.y = y;
  5903. this.width = width;
  5904. this.height = height;
  5905. }
  5906. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  5907. if (renderWidthOrEngine.getRenderWidth) {
  5908. var engine = renderWidthOrEngine;
  5909. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  5910. }
  5911. var renderWidth = renderWidthOrEngine;
  5912. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  5913. };
  5914. /**
  5915. * Returns a new Viewport copied from the current one.
  5916. */
  5917. Viewport.prototype.clone = function () {
  5918. return new Viewport(this.x, this.y, this.width, this.height);
  5919. };
  5920. return Viewport;
  5921. }());
  5922. BABYLON.Viewport = Viewport;
  5923. var Frustum = /** @class */ (function () {
  5924. function Frustum() {
  5925. }
  5926. /**
  5927. * Returns a new array of 6 Frustum planes computed by the passed transformation matrix.
  5928. */
  5929. Frustum.GetPlanes = function (transform) {
  5930. var frustumPlanes = [];
  5931. for (var index = 0; index < 6; index++) {
  5932. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  5933. }
  5934. Frustum.GetPlanesToRef(transform, frustumPlanes);
  5935. return frustumPlanes;
  5936. };
  5937. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  5938. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  5939. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  5940. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  5941. frustumPlane.d = transform.m[15] + transform.m[14];
  5942. frustumPlane.normalize();
  5943. };
  5944. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  5945. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  5946. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  5947. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  5948. frustumPlane.d = transform.m[15] - transform.m[14];
  5949. frustumPlane.normalize();
  5950. };
  5951. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  5952. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  5953. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  5954. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  5955. frustumPlane.d = transform.m[15] + transform.m[12];
  5956. frustumPlane.normalize();
  5957. };
  5958. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  5959. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  5960. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  5961. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  5962. frustumPlane.d = transform.m[15] - transform.m[12];
  5963. frustumPlane.normalize();
  5964. };
  5965. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  5966. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  5967. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  5968. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  5969. frustumPlane.d = transform.m[15] - transform.m[13];
  5970. frustumPlane.normalize();
  5971. };
  5972. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  5973. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  5974. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  5975. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  5976. frustumPlane.d = transform.m[15] + transform.m[13];
  5977. frustumPlane.normalize();
  5978. };
  5979. /**
  5980. * Sets the passed array "frustumPlanes" with the 6 Frustum planes computed by the passed transformation matrix.
  5981. */
  5982. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  5983. // Near
  5984. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  5985. // Far
  5986. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  5987. // Left
  5988. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  5989. // Right
  5990. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  5991. // Top
  5992. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  5993. // Bottom
  5994. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  5995. };
  5996. return Frustum;
  5997. }());
  5998. BABYLON.Frustum = Frustum;
  5999. var Space;
  6000. (function (Space) {
  6001. Space[Space["LOCAL"] = 0] = "LOCAL";
  6002. Space[Space["WORLD"] = 1] = "WORLD";
  6003. Space[Space["BONE"] = 2] = "BONE";
  6004. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  6005. var Axis = /** @class */ (function () {
  6006. function Axis() {
  6007. }
  6008. Axis.X = new Vector3(1.0, 0.0, 0.0);
  6009. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  6010. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  6011. return Axis;
  6012. }());
  6013. BABYLON.Axis = Axis;
  6014. ;
  6015. var BezierCurve = /** @class */ (function () {
  6016. function BezierCurve() {
  6017. }
  6018. /**
  6019. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the passed x1, y1, x2, y2 floats.
  6020. */
  6021. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  6022. // Extract X (which is equal to time here)
  6023. var f0 = 1 - 3 * x2 + 3 * x1;
  6024. var f1 = 3 * x2 - 6 * x1;
  6025. var f2 = 3 * x1;
  6026. var refinedT = t;
  6027. for (var i = 0; i < 5; i++) {
  6028. var refinedT2 = refinedT * refinedT;
  6029. var refinedT3 = refinedT2 * refinedT;
  6030. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  6031. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  6032. refinedT -= (x - t) * slope;
  6033. refinedT = Math.min(1, Math.max(0, refinedT));
  6034. }
  6035. // Resolve cubic bezier for the given x
  6036. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  6037. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  6038. Math.pow(refinedT, 3);
  6039. };
  6040. return BezierCurve;
  6041. }());
  6042. BABYLON.BezierCurve = BezierCurve;
  6043. var Orientation;
  6044. (function (Orientation) {
  6045. Orientation[Orientation["CW"] = 0] = "CW";
  6046. Orientation[Orientation["CCW"] = 1] = "CCW";
  6047. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  6048. var Angle = /** @class */ (function () {
  6049. /**
  6050. * Creates an Angle object of "radians" radians (float).
  6051. */
  6052. function Angle(radians) {
  6053. var _this = this;
  6054. /**
  6055. * Returns the Angle value in degrees (float).
  6056. */
  6057. this.degrees = function () { return _this._radians * 180.0 / Math.PI; };
  6058. /**
  6059. * Returns the Angle value in radians (float).
  6060. */
  6061. this.radians = function () { return _this._radians; };
  6062. this._radians = radians;
  6063. if (this._radians < 0.0)
  6064. this._radians += (2.0 * Math.PI);
  6065. }
  6066. /**
  6067. * Returns a new Angle object valued with the angle value in radians between the two passed vectors.
  6068. */
  6069. Angle.BetweenTwoPoints = function (a, b) {
  6070. var delta = b.subtract(a);
  6071. var theta = Math.atan2(delta.y, delta.x);
  6072. return new Angle(theta);
  6073. };
  6074. /**
  6075. * Returns a new Angle object from the passed float in radians.
  6076. */
  6077. Angle.FromRadians = function (radians) {
  6078. return new Angle(radians);
  6079. };
  6080. /**
  6081. * Returns a new Angle object from the passed float in degrees.
  6082. */
  6083. Angle.FromDegrees = function (degrees) {
  6084. return new Angle(degrees * Math.PI / 180.0);
  6085. };
  6086. return Angle;
  6087. }());
  6088. BABYLON.Angle = Angle;
  6089. var Arc2 = /** @class */ (function () {
  6090. /**
  6091. * Creates an Arc object from the three passed points : start, middle and end.
  6092. */
  6093. function Arc2(startPoint, midPoint, endPoint) {
  6094. this.startPoint = startPoint;
  6095. this.midPoint = midPoint;
  6096. this.endPoint = endPoint;
  6097. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  6098. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  6099. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  6100. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  6101. this.centerPoint = new Vector2((startToMid * (midPoint.y - endPoint.y) - midToEnd * (startPoint.y - midPoint.y)) / det, ((startPoint.x - midPoint.x) * midToEnd - (midPoint.x - endPoint.x) * startToMid) / det);
  6102. this.radius = this.centerPoint.subtract(this.startPoint).length();
  6103. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  6104. var a1 = this.startAngle.degrees();
  6105. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  6106. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  6107. // angles correction
  6108. if (a2 - a1 > +180.0)
  6109. a2 -= 360.0;
  6110. if (a2 - a1 < -180.0)
  6111. a2 += 360.0;
  6112. if (a3 - a2 > +180.0)
  6113. a3 -= 360.0;
  6114. if (a3 - a2 < -180.0)
  6115. a3 += 360.0;
  6116. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  6117. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  6118. }
  6119. return Arc2;
  6120. }());
  6121. BABYLON.Arc2 = Arc2;
  6122. var Path2 = /** @class */ (function () {
  6123. /**
  6124. * Creates a Path2 object from the starting 2D coordinates x and y.
  6125. */
  6126. function Path2(x, y) {
  6127. this._points = new Array();
  6128. this._length = 0.0;
  6129. this.closed = false;
  6130. this._points.push(new Vector2(x, y));
  6131. }
  6132. /**
  6133. * Adds a new segment until the passed coordinates (x, y) to the current Path2.
  6134. * Returns the updated Path2.
  6135. */
  6136. Path2.prototype.addLineTo = function (x, y) {
  6137. if (this.closed) {
  6138. //Tools.Error("cannot add lines to closed paths");
  6139. return this;
  6140. }
  6141. var newPoint = new Vector2(x, y);
  6142. var previousPoint = this._points[this._points.length - 1];
  6143. this._points.push(newPoint);
  6144. this._length += newPoint.subtract(previousPoint).length();
  6145. return this;
  6146. };
  6147. /**
  6148. * Adds _numberOfSegments_ segments according to the arc definition (middle point coordinates, end point coordinates, the arc start point being the current Path2 last point) to the current Path2.
  6149. * Returns the updated Path2.
  6150. */
  6151. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  6152. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  6153. if (this.closed) {
  6154. //Tools.Error("cannot add arcs to closed paths");
  6155. return this;
  6156. }
  6157. var startPoint = this._points[this._points.length - 1];
  6158. var midPoint = new Vector2(midX, midY);
  6159. var endPoint = new Vector2(endX, endY);
  6160. var arc = new Arc2(startPoint, midPoint, endPoint);
  6161. var increment = arc.angle.radians() / numberOfSegments;
  6162. if (arc.orientation === Orientation.CW)
  6163. increment *= -1;
  6164. var currentAngle = arc.startAngle.radians() + increment;
  6165. for (var i = 0; i < numberOfSegments; i++) {
  6166. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  6167. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  6168. this.addLineTo(x, y);
  6169. currentAngle += increment;
  6170. }
  6171. return this;
  6172. };
  6173. /**
  6174. * Closes the Path2.
  6175. * Returns the Path2.
  6176. */
  6177. Path2.prototype.close = function () {
  6178. this.closed = true;
  6179. return this;
  6180. };
  6181. /**
  6182. * Returns the Path2 total length (float).
  6183. */
  6184. Path2.prototype.length = function () {
  6185. var result = this._length;
  6186. if (!this.closed) {
  6187. var lastPoint = this._points[this._points.length - 1];
  6188. var firstPoint = this._points[0];
  6189. result += (firstPoint.subtract(lastPoint).length());
  6190. }
  6191. return result;
  6192. };
  6193. /**
  6194. * Returns the Path2 internal array of points.
  6195. */
  6196. Path2.prototype.getPoints = function () {
  6197. return this._points;
  6198. };
  6199. /**
  6200. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  6201. */
  6202. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  6203. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  6204. //Tools.Error("normalized length position should be between 0 and 1.");
  6205. return Vector2.Zero();
  6206. }
  6207. var lengthPosition = normalizedLengthPosition * this.length();
  6208. var previousOffset = 0;
  6209. for (var i = 0; i < this._points.length; i++) {
  6210. var j = (i + 1) % this._points.length;
  6211. var a = this._points[i];
  6212. var b = this._points[j];
  6213. var bToA = b.subtract(a);
  6214. var nextOffset = (bToA.length() + previousOffset);
  6215. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  6216. var dir = bToA.normalize();
  6217. var localOffset = lengthPosition - previousOffset;
  6218. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  6219. }
  6220. previousOffset = nextOffset;
  6221. }
  6222. //Tools.Error("internal error");
  6223. return Vector2.Zero();
  6224. };
  6225. /**
  6226. * Returns a new Path2 starting at the coordinates (x, y).
  6227. */
  6228. Path2.StartingAt = function (x, y) {
  6229. return new Path2(x, y);
  6230. };
  6231. return Path2;
  6232. }());
  6233. BABYLON.Path2 = Path2;
  6234. var Path3D = /** @class */ (function () {
  6235. /**
  6236. * new Path3D(path, normal, raw)
  6237. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  6238. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  6239. * path : an array of Vector3, the curve axis of the Path3D
  6240. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  6241. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  6242. */
  6243. function Path3D(path, firstNormal, raw) {
  6244. if (firstNormal === void 0) { firstNormal = null; }
  6245. this.path = path;
  6246. this._curve = new Array();
  6247. this._distances = new Array();
  6248. this._tangents = new Array();
  6249. this._normals = new Array();
  6250. this._binormals = new Array();
  6251. for (var p = 0; p < path.length; p++) {
  6252. this._curve[p] = path[p].clone(); // hard copy
  6253. }
  6254. this._raw = raw || false;
  6255. this._compute(firstNormal);
  6256. }
  6257. /**
  6258. * Returns the Path3D array of successive Vector3 designing its curve.
  6259. */
  6260. Path3D.prototype.getCurve = function () {
  6261. return this._curve;
  6262. };
  6263. /**
  6264. * Returns an array populated with tangent vectors on each Path3D curve point.
  6265. */
  6266. Path3D.prototype.getTangents = function () {
  6267. return this._tangents;
  6268. };
  6269. /**
  6270. * Returns an array populated with normal vectors on each Path3D curve point.
  6271. */
  6272. Path3D.prototype.getNormals = function () {
  6273. return this._normals;
  6274. };
  6275. /**
  6276. * Returns an array populated with binormal vectors on each Path3D curve point.
  6277. */
  6278. Path3D.prototype.getBinormals = function () {
  6279. return this._binormals;
  6280. };
  6281. /**
  6282. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  6283. */
  6284. Path3D.prototype.getDistances = function () {
  6285. return this._distances;
  6286. };
  6287. /**
  6288. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  6289. * Returns the same object updated.
  6290. */
  6291. Path3D.prototype.update = function (path, firstNormal) {
  6292. if (firstNormal === void 0) { firstNormal = null; }
  6293. for (var p = 0; p < path.length; p++) {
  6294. this._curve[p].x = path[p].x;
  6295. this._curve[p].y = path[p].y;
  6296. this._curve[p].z = path[p].z;
  6297. }
  6298. this._compute(firstNormal);
  6299. return this;
  6300. };
  6301. // private function compute() : computes tangents, normals and binormals
  6302. Path3D.prototype._compute = function (firstNormal) {
  6303. var l = this._curve.length;
  6304. // first and last tangents
  6305. this._tangents[0] = this._getFirstNonNullVector(0);
  6306. if (!this._raw) {
  6307. this._tangents[0].normalize();
  6308. }
  6309. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  6310. if (!this._raw) {
  6311. this._tangents[l - 1].normalize();
  6312. }
  6313. // normals and binormals at first point : arbitrary vector with _normalVector()
  6314. var tg0 = this._tangents[0];
  6315. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  6316. this._normals[0] = pp0;
  6317. if (!this._raw) {
  6318. this._normals[0].normalize();
  6319. }
  6320. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  6321. if (!this._raw) {
  6322. this._binormals[0].normalize();
  6323. }
  6324. this._distances[0] = 0.0;
  6325. // normals and binormals : next points
  6326. var prev; // previous vector (segment)
  6327. var cur; // current vector (segment)
  6328. var curTang; // current tangent
  6329. // previous normal
  6330. var prevBinor; // previous binormal
  6331. for (var i = 1; i < l; i++) {
  6332. // tangents
  6333. prev = this._getLastNonNullVector(i);
  6334. if (i < l - 1) {
  6335. cur = this._getFirstNonNullVector(i);
  6336. this._tangents[i] = prev.add(cur);
  6337. this._tangents[i].normalize();
  6338. }
  6339. this._distances[i] = this._distances[i - 1] + prev.length();
  6340. // normals and binormals
  6341. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  6342. curTang = this._tangents[i];
  6343. prevBinor = this._binormals[i - 1];
  6344. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  6345. if (!this._raw) {
  6346. this._normals[i].normalize();
  6347. }
  6348. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  6349. if (!this._raw) {
  6350. this._binormals[i].normalize();
  6351. }
  6352. }
  6353. };
  6354. // private function getFirstNonNullVector(index)
  6355. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  6356. Path3D.prototype._getFirstNonNullVector = function (index) {
  6357. var i = 1;
  6358. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  6359. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  6360. i++;
  6361. nNVector = this._curve[index + i].subtract(this._curve[index]);
  6362. }
  6363. return nNVector;
  6364. };
  6365. // private function getLastNonNullVector(index)
  6366. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  6367. Path3D.prototype._getLastNonNullVector = function (index) {
  6368. var i = 1;
  6369. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  6370. while (nLVector.length() === 0 && index > i + 1) {
  6371. i++;
  6372. nLVector = this._curve[index].subtract(this._curve[index - i]);
  6373. }
  6374. return nLVector;
  6375. };
  6376. // private function normalVector(v0, vt, va) :
  6377. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  6378. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  6379. Path3D.prototype._normalVector = function (v0, vt, va) {
  6380. var normal0;
  6381. var tgl = vt.length();
  6382. if (tgl === 0.0) {
  6383. tgl = 1.0;
  6384. }
  6385. if (va === undefined || va === null) {
  6386. var point;
  6387. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  6388. point = new Vector3(0.0, -1.0, 0.0);
  6389. }
  6390. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  6391. point = new Vector3(1.0, 0.0, 0.0);
  6392. }
  6393. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  6394. point = new Vector3(0.0, 0.0, 1.0);
  6395. }
  6396. else {
  6397. point = Vector3.Zero();
  6398. }
  6399. normal0 = Vector3.Cross(vt, point);
  6400. }
  6401. else {
  6402. normal0 = Vector3.Cross(vt, va);
  6403. Vector3.CrossToRef(normal0, vt, normal0);
  6404. }
  6405. normal0.normalize();
  6406. return normal0;
  6407. };
  6408. return Path3D;
  6409. }());
  6410. BABYLON.Path3D = Path3D;
  6411. var Curve3 = /** @class */ (function () {
  6412. /**
  6413. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  6414. * A Curve3 is designed from a series of successive Vector3.
  6415. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  6416. */
  6417. function Curve3(points) {
  6418. this._length = 0.0;
  6419. this._points = points;
  6420. this._length = this._computeLength(points);
  6421. }
  6422. /**
  6423. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  6424. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  6425. * @param v1 (Vector3) the control point
  6426. * @param v2 (Vector3) the end point of the Quadratic Bezier
  6427. * @param nbPoints (integer) the wanted number of points in the curve
  6428. */
  6429. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  6430. nbPoints = nbPoints > 2 ? nbPoints : 3;
  6431. var bez = new Array();
  6432. var equation = function (t, val0, val1, val2) {
  6433. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  6434. return res;
  6435. };
  6436. for (var i = 0; i <= nbPoints; i++) {
  6437. bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x), equation(i / nbPoints, v0.y, v1.y, v2.y), equation(i / nbPoints, v0.z, v1.z, v2.z)));
  6438. }
  6439. return new Curve3(bez);
  6440. };
  6441. /**
  6442. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  6443. * @param v0 (Vector3) the origin point of the Cubic Bezier
  6444. * @param v1 (Vector3) the first control point
  6445. * @param v2 (Vector3) the second control point
  6446. * @param v3 (Vector3) the end point of the Cubic Bezier
  6447. * @param nbPoints (integer) the wanted number of points in the curve
  6448. */
  6449. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  6450. nbPoints = nbPoints > 3 ? nbPoints : 4;
  6451. var bez = new Array();
  6452. var equation = function (t, val0, val1, val2, val3) {
  6453. var res = (1.0 - t) * (1.0 - t) * (1.0 - t) * val0 + 3.0 * t * (1.0 - t) * (1.0 - t) * val1 + 3.0 * t * t * (1.0 - t) * val2 + t * t * t * val3;
  6454. return res;
  6455. };
  6456. for (var i = 0; i <= nbPoints; i++) {
  6457. bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x, v3.x), equation(i / nbPoints, v0.y, v1.y, v2.y, v3.y), equation(i / nbPoints, v0.z, v1.z, v2.z, v3.z)));
  6458. }
  6459. return new Curve3(bez);
  6460. };
  6461. /**
  6462. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  6463. * @param p1 (Vector3) the origin point of the Hermite Spline
  6464. * @param t1 (Vector3) the tangent vector at the origin point
  6465. * @param p2 (Vector3) the end point of the Hermite Spline
  6466. * @param t2 (Vector3) the tangent vector at the end point
  6467. * @param nbPoints (integer) the wanted number of points in the curve
  6468. */
  6469. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  6470. var hermite = new Array();
  6471. var step = 1.0 / nbPoints;
  6472. for (var i = 0; i <= nbPoints; i++) {
  6473. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  6474. }
  6475. return new Curve3(hermite);
  6476. };
  6477. /**
  6478. * Returns a Curve3 object along a CatmullRom Spline curve :
  6479. * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
  6480. * @param nbPoints (integer) the wanted number of points between each curve control points.
  6481. */
  6482. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  6483. var totalPoints = new Array();
  6484. totalPoints.push(points[0].clone());
  6485. Array.prototype.push.apply(totalPoints, points);
  6486. totalPoints.push(points[points.length - 1].clone());
  6487. var catmullRom = new Array();
  6488. var step = 1.0 / nbPoints;
  6489. var amount = 0.0;
  6490. for (var i = 0; i < totalPoints.length - 3; i++) {
  6491. amount = 0;
  6492. for (var c = 0; c < nbPoints; c++) {
  6493. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  6494. amount += step;
  6495. }
  6496. }
  6497. i--;
  6498. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  6499. return new Curve3(catmullRom);
  6500. };
  6501. /**
  6502. * Returns the Curve3 stored array of successive Vector3
  6503. */
  6504. Curve3.prototype.getPoints = function () {
  6505. return this._points;
  6506. };
  6507. /**
  6508. * Returns the computed length (float) of the curve.
  6509. */
  6510. Curve3.prototype.length = function () {
  6511. return this._length;
  6512. };
  6513. /**
  6514. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  6515. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  6516. * curveA and curveB keep unchanged.
  6517. */
  6518. Curve3.prototype.continue = function (curve) {
  6519. var lastPoint = this._points[this._points.length - 1];
  6520. var continuedPoints = this._points.slice();
  6521. var curvePoints = curve.getPoints();
  6522. for (var i = 1; i < curvePoints.length; i++) {
  6523. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  6524. }
  6525. var continuedCurve = new Curve3(continuedPoints);
  6526. return continuedCurve;
  6527. };
  6528. Curve3.prototype._computeLength = function (path) {
  6529. var l = 0;
  6530. for (var i = 1; i < path.length; i++) {
  6531. l += (path[i].subtract(path[i - 1])).length();
  6532. }
  6533. return l;
  6534. };
  6535. return Curve3;
  6536. }());
  6537. BABYLON.Curve3 = Curve3;
  6538. // Vertex formats
  6539. var PositionNormalVertex = /** @class */ (function () {
  6540. function PositionNormalVertex(position, normal) {
  6541. if (position === void 0) { position = Vector3.Zero(); }
  6542. if (normal === void 0) { normal = Vector3.Up(); }
  6543. this.position = position;
  6544. this.normal = normal;
  6545. }
  6546. PositionNormalVertex.prototype.clone = function () {
  6547. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  6548. };
  6549. return PositionNormalVertex;
  6550. }());
  6551. BABYLON.PositionNormalVertex = PositionNormalVertex;
  6552. var PositionNormalTextureVertex = /** @class */ (function () {
  6553. function PositionNormalTextureVertex(position, normal, uv) {
  6554. if (position === void 0) { position = Vector3.Zero(); }
  6555. if (normal === void 0) { normal = Vector3.Up(); }
  6556. if (uv === void 0) { uv = Vector2.Zero(); }
  6557. this.position = position;
  6558. this.normal = normal;
  6559. this.uv = uv;
  6560. }
  6561. PositionNormalTextureVertex.prototype.clone = function () {
  6562. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  6563. };
  6564. return PositionNormalTextureVertex;
  6565. }());
  6566. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  6567. // Temporary pre-allocated objects for engine internal use
  6568. // usage in any internal function :
  6569. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  6570. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  6571. var Tmp = /** @class */ (function () {
  6572. function Tmp() {
  6573. }
  6574. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  6575. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  6576. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  6577. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  6578. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  6579. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  6580. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  6581. Matrix.Zero(), Matrix.Zero(),
  6582. Matrix.Zero(), Matrix.Zero(),
  6583. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  6584. return Tmp;
  6585. }());
  6586. BABYLON.Tmp = Tmp;
  6587. // Same as Tmp but not exported to keep it onyl for math functions to avoid conflicts
  6588. var MathTmp = /** @class */ (function () {
  6589. function MathTmp() {
  6590. }
  6591. MathTmp.Vector3 = [Vector3.Zero()];
  6592. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  6593. MathTmp.Quaternion = [Quaternion.Zero()];
  6594. return MathTmp;
  6595. }());
  6596. })(BABYLON || (BABYLON = {}));
  6597. //# sourceMappingURL=babylon.math.js.map
  6598. var BABYLON;
  6599. (function (BABYLON) {
  6600. var Scalar = /** @class */ (function () {
  6601. function Scalar() {
  6602. }
  6603. /**
  6604. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  6605. */
  6606. Scalar.WithinEpsilon = function (a, b, epsilon) {
  6607. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  6608. var num = a - b;
  6609. return -epsilon <= num && num <= epsilon;
  6610. };
  6611. /**
  6612. * Returns a string : the upper case translation of the number i to hexadecimal.
  6613. */
  6614. Scalar.ToHex = function (i) {
  6615. var str = i.toString(16);
  6616. if (i <= 15) {
  6617. return ("0" + str).toUpperCase();
  6618. }
  6619. return str.toUpperCase();
  6620. };
  6621. /**
  6622. * Returns -1 if value is negative and +1 is value is positive.
  6623. * Returns the value itself if it's equal to zero.
  6624. */
  6625. Scalar.Sign = function (value) {
  6626. value = +value; // convert to a number
  6627. if (value === 0 || isNaN(value))
  6628. return value;
  6629. return value > 0 ? 1 : -1;
  6630. };
  6631. /**
  6632. * Returns the value itself if it's between min and max.
  6633. * Returns min if the value is lower than min.
  6634. * Returns max if the value is greater than max.
  6635. */
  6636. Scalar.Clamp = function (value, min, max) {
  6637. if (min === void 0) { min = 0; }
  6638. if (max === void 0) { max = 1; }
  6639. return Math.min(max, Math.max(min, value));
  6640. };
  6641. /**
  6642. * Returns the log2 of value.
  6643. */
  6644. Scalar.Log2 = function (value) {
  6645. return Math.log(value) * Math.LOG2E;
  6646. };
  6647. /**
  6648. * Loops the value, so that it is never larger than length and never smaller than 0.
  6649. *
  6650. * This is similar to the modulo operator but it works with floating point numbers.
  6651. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  6652. * With t = 5 and length = 2.5, the result would be 0.0.
  6653. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  6654. */
  6655. Scalar.Repeat = function (value, length) {
  6656. return value - Math.floor(value / length) * length;
  6657. };
  6658. /**
  6659. * Normalize the value between 0.0 and 1.0 using min and max values
  6660. */
  6661. Scalar.Normalize = function (value, min, max) {
  6662. return (value - min) / (max - min);
  6663. };
  6664. /**
  6665. * Denormalize the value from 0.0 and 1.0 using min and max values
  6666. */
  6667. Scalar.Denormalize = function (normalized, min, max) {
  6668. return (normalized * (max - min) + min);
  6669. };
  6670. /**
  6671. * Calculates the shortest difference between two given angles given in degrees.
  6672. */
  6673. Scalar.DeltaAngle = function (current, target) {
  6674. var num = Scalar.Repeat(target - current, 360.0);
  6675. if (num > 180.0) {
  6676. num -= 360.0;
  6677. }
  6678. return num;
  6679. };
  6680. /**
  6681. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  6682. *
  6683. * The returned value will move back and forth between 0 and length
  6684. */
  6685. Scalar.PingPong = function (tx, length) {
  6686. var t = Scalar.Repeat(tx, length * 2.0);
  6687. return length - Math.abs(t - length);
  6688. };
  6689. /**
  6690. * Interpolates between min and max with smoothing at the limits.
  6691. *
  6692. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  6693. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  6694. */
  6695. Scalar.SmoothStep = function (from, to, tx) {
  6696. var t = Scalar.Clamp(tx);
  6697. t = -2.0 * t * t * t + 3.0 * t * t;
  6698. return to * t + from * (1.0 - t);
  6699. };
  6700. /**
  6701. * Moves a value current towards target.
  6702. *
  6703. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  6704. * Negative values of maxDelta pushes the value away from target.
  6705. */
  6706. Scalar.MoveTowards = function (current, target, maxDelta) {
  6707. var result = 0;
  6708. if (Math.abs(target - current) <= maxDelta) {
  6709. result = target;
  6710. }
  6711. else {
  6712. result = current + Scalar.Sign(target - current) * maxDelta;
  6713. }
  6714. return result;
  6715. };
  6716. /**
  6717. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  6718. *
  6719. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  6720. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  6721. */
  6722. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  6723. var num = Scalar.DeltaAngle(current, target);
  6724. var result = 0;
  6725. if (-maxDelta < num && num < maxDelta) {
  6726. result = target;
  6727. }
  6728. else {
  6729. target = current + num;
  6730. result = Scalar.MoveTowards(current, target, maxDelta);
  6731. }
  6732. return result;
  6733. };
  6734. /**
  6735. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  6736. */
  6737. Scalar.Lerp = function (start, end, amount) {
  6738. return start + ((end - start) * amount);
  6739. };
  6740. /**
  6741. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  6742. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  6743. */
  6744. Scalar.LerpAngle = function (start, end, amount) {
  6745. var num = Scalar.Repeat(end - start, 360.0);
  6746. if (num > 180.0) {
  6747. num -= 360.0;
  6748. }
  6749. return start + num * Scalar.Clamp(amount);
  6750. };
  6751. /**
  6752. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  6753. */
  6754. Scalar.InverseLerp = function (a, b, value) {
  6755. var result = 0;
  6756. if (a != b) {
  6757. result = Scalar.Clamp((value - a) / (b - a));
  6758. }
  6759. else {
  6760. result = 0.0;
  6761. }
  6762. return result;
  6763. };
  6764. /**
  6765. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  6766. */
  6767. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  6768. var squared = amount * amount;
  6769. var cubed = amount * squared;
  6770. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  6771. var part2 = (-2.0 * cubed) + (3.0 * squared);
  6772. var part3 = (cubed - (2.0 * squared)) + amount;
  6773. var part4 = cubed - squared;
  6774. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  6775. };
  6776. /**
  6777. * Returns a random float number between and min and max values
  6778. */
  6779. Scalar.RandomRange = function (min, max) {
  6780. if (min === max)
  6781. return min;
  6782. return ((Math.random() * (max - min)) + min);
  6783. };
  6784. /**
  6785. * This function returns percentage of a number in a given range.
  6786. *
  6787. * RangeToPercent(40,20,60) will return 0.5 (50%)
  6788. * RangeToPercent(34,0,100) will return 0.34 (34%)
  6789. */
  6790. Scalar.RangeToPercent = function (number, min, max) {
  6791. return ((number - min) / (max - min));
  6792. };
  6793. /**
  6794. * This function returns number that corresponds to the percentage in a given range.
  6795. *
  6796. * PercentToRange(0.34,0,100) will return 34.
  6797. */
  6798. Scalar.PercentToRange = function (percent, min, max) {
  6799. return ((max - min) * percent + min);
  6800. };
  6801. /**
  6802. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  6803. * @param angle The angle to normalize in radian.
  6804. * @return The converted angle.
  6805. */
  6806. Scalar.NormalizeRadians = function (angle) {
  6807. // More precise but slower version kept for reference.
  6808. // angle = angle % Tools.TwoPi;
  6809. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  6810. //if (angle > Math.PI) {
  6811. // angle -= Tools.TwoPi;
  6812. //}
  6813. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  6814. return angle;
  6815. };
  6816. /**
  6817. * Two pi constants convenient for computation.
  6818. */
  6819. Scalar.TwoPi = Math.PI * 2;
  6820. return Scalar;
  6821. }());
  6822. BABYLON.Scalar = Scalar;
  6823. })(BABYLON || (BABYLON = {}));
  6824. //# sourceMappingURL=babylon.math.scalar.js.map
  6825. //# sourceMappingURL=babylon.mixins.js.map
  6826. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  6827. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  6828. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  6829. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  6830. //# sourceMappingURL=babylon.webgl2.js.map
  6831. var BABYLON;
  6832. (function (BABYLON) {
  6833. var __decoratorInitialStore = {};
  6834. var __mergedStore = {};
  6835. var _copySource = function (creationFunction, source, instanciate) {
  6836. var destination = creationFunction();
  6837. // Tags
  6838. if (BABYLON.Tags) {
  6839. BABYLON.Tags.AddTagsTo(destination, source.tags);
  6840. }
  6841. var classStore = getMergedStore(destination);
  6842. // Properties
  6843. for (var property in classStore) {
  6844. var propertyDescriptor = classStore[property];
  6845. var sourceProperty = source[property];
  6846. var propertyType = propertyDescriptor.type;
  6847. if (sourceProperty !== undefined && sourceProperty !== null) {
  6848. switch (propertyType) {
  6849. case 0: // Value
  6850. case 6:// Mesh reference
  6851. destination[property] = sourceProperty;
  6852. break;
  6853. case 1:// Texture
  6854. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  6855. break;
  6856. case 2: // Color3
  6857. case 3: // FresnelParameters
  6858. case 4: // Vector2
  6859. case 5: // Vector3
  6860. case 7: // Color Curves
  6861. case 10:// Quaternion
  6862. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  6863. break;
  6864. }
  6865. }
  6866. }
  6867. return destination;
  6868. };
  6869. function getDirectStore(target) {
  6870. var classKey = target.getClassName();
  6871. if (!__decoratorInitialStore[classKey]) {
  6872. __decoratorInitialStore[classKey] = {};
  6873. }
  6874. return __decoratorInitialStore[classKey];
  6875. }
  6876. /**
  6877. * Return the list of properties flagged as serializable
  6878. * @param target: host object
  6879. */
  6880. function getMergedStore(target) {
  6881. var classKey = target.getClassName();
  6882. if (__mergedStore[classKey]) {
  6883. return __mergedStore[classKey];
  6884. }
  6885. __mergedStore[classKey] = {};
  6886. var store = __mergedStore[classKey];
  6887. var currentTarget = target;
  6888. var currentKey = classKey;
  6889. while (currentKey) {
  6890. var initialStore = __decoratorInitialStore[currentKey];
  6891. for (var property in initialStore) {
  6892. store[property] = initialStore[property];
  6893. }
  6894. var parent_1 = void 0;
  6895. var done = false;
  6896. do {
  6897. parent_1 = Object.getPrototypeOf(currentTarget);
  6898. if (!parent_1.getClassName) {
  6899. done = true;
  6900. break;
  6901. }
  6902. if (parent_1.getClassName() !== currentKey) {
  6903. break;
  6904. }
  6905. currentTarget = parent_1;
  6906. } while (parent_1);
  6907. if (done) {
  6908. break;
  6909. }
  6910. currentKey = parent_1.getClassName();
  6911. currentTarget = parent_1;
  6912. }
  6913. return store;
  6914. }
  6915. function generateSerializableMember(type, sourceName) {
  6916. return function (target, propertyKey) {
  6917. var classStore = getDirectStore(target);
  6918. if (!classStore[propertyKey]) {
  6919. classStore[propertyKey] = { type: type, sourceName: sourceName };
  6920. }
  6921. };
  6922. }
  6923. function generateExpandMember(setCallback, targetKey) {
  6924. if (targetKey === void 0) { targetKey = null; }
  6925. return function (target, propertyKey) {
  6926. var key = targetKey || ("_" + propertyKey);
  6927. Object.defineProperty(target, propertyKey, {
  6928. get: function () {
  6929. return this[key];
  6930. },
  6931. set: function (value) {
  6932. if (this[key] === value) {
  6933. return;
  6934. }
  6935. this[key] = value;
  6936. target[setCallback].apply(this);
  6937. },
  6938. enumerable: true,
  6939. configurable: true
  6940. });
  6941. };
  6942. }
  6943. function expandToProperty(callback, targetKey) {
  6944. if (targetKey === void 0) { targetKey = null; }
  6945. return generateExpandMember(callback, targetKey);
  6946. }
  6947. BABYLON.expandToProperty = expandToProperty;
  6948. function serialize(sourceName) {
  6949. return generateSerializableMember(0, sourceName); // value member
  6950. }
  6951. BABYLON.serialize = serialize;
  6952. function serializeAsTexture(sourceName) {
  6953. return generateSerializableMember(1, sourceName); // texture member
  6954. }
  6955. BABYLON.serializeAsTexture = serializeAsTexture;
  6956. function serializeAsColor3(sourceName) {
  6957. return generateSerializableMember(2, sourceName); // color3 member
  6958. }
  6959. BABYLON.serializeAsColor3 = serializeAsColor3;
  6960. function serializeAsFresnelParameters(sourceName) {
  6961. return generateSerializableMember(3, sourceName); // fresnel parameters member
  6962. }
  6963. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  6964. function serializeAsVector2(sourceName) {
  6965. return generateSerializableMember(4, sourceName); // vector2 member
  6966. }
  6967. BABYLON.serializeAsVector2 = serializeAsVector2;
  6968. function serializeAsVector3(sourceName) {
  6969. return generateSerializableMember(5, sourceName); // vector3 member
  6970. }
  6971. BABYLON.serializeAsVector3 = serializeAsVector3;
  6972. function serializeAsMeshReference(sourceName) {
  6973. return generateSerializableMember(6, sourceName); // mesh reference member
  6974. }
  6975. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  6976. function serializeAsColorCurves(sourceName) {
  6977. return generateSerializableMember(7, sourceName); // color curves
  6978. }
  6979. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  6980. function serializeAsColor4(sourceName) {
  6981. return generateSerializableMember(8, sourceName); // color 4
  6982. }
  6983. BABYLON.serializeAsColor4 = serializeAsColor4;
  6984. function serializeAsImageProcessingConfiguration(sourceName) {
  6985. return generateSerializableMember(9, sourceName); // image processing
  6986. }
  6987. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  6988. function serializeAsQuaternion(sourceName) {
  6989. return generateSerializableMember(10, sourceName); // quaternion member
  6990. }
  6991. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  6992. var SerializationHelper = /** @class */ (function () {
  6993. function SerializationHelper() {
  6994. }
  6995. SerializationHelper.Serialize = function (entity, serializationObject) {
  6996. if (!serializationObject) {
  6997. serializationObject = {};
  6998. }
  6999. // Tags
  7000. if (BABYLON.Tags) {
  7001. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  7002. }
  7003. var serializedProperties = getMergedStore(entity);
  7004. // Properties
  7005. for (var property in serializedProperties) {
  7006. var propertyDescriptor = serializedProperties[property];
  7007. var targetPropertyName = propertyDescriptor.sourceName || property;
  7008. var propertyType = propertyDescriptor.type;
  7009. var sourceProperty = entity[property];
  7010. if (sourceProperty !== undefined && sourceProperty !== null) {
  7011. switch (propertyType) {
  7012. case 0:// Value
  7013. serializationObject[targetPropertyName] = sourceProperty;
  7014. break;
  7015. case 1:// Texture
  7016. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7017. break;
  7018. case 2:// Color3
  7019. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7020. break;
  7021. case 3:// FresnelParameters
  7022. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7023. break;
  7024. case 4:// Vector2
  7025. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7026. break;
  7027. case 5:// Vector3
  7028. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7029. break;
  7030. case 6:// Mesh reference
  7031. serializationObject[targetPropertyName] = sourceProperty.id;
  7032. break;
  7033. case 7:// Color Curves
  7034. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7035. break;
  7036. case 8:// Color 4
  7037. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7038. break;
  7039. case 9:// Image Processing
  7040. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7041. break;
  7042. }
  7043. }
  7044. }
  7045. return serializationObject;
  7046. };
  7047. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  7048. if (rootUrl === void 0) { rootUrl = null; }
  7049. var destination = creationFunction();
  7050. if (!rootUrl) {
  7051. rootUrl = "";
  7052. }
  7053. // Tags
  7054. if (BABYLON.Tags) {
  7055. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7056. }
  7057. var classStore = getMergedStore(destination);
  7058. // Properties
  7059. for (var property in classStore) {
  7060. var propertyDescriptor = classStore[property];
  7061. var sourceProperty = source[propertyDescriptor.sourceName || property];
  7062. var propertyType = propertyDescriptor.type;
  7063. if (sourceProperty !== undefined && sourceProperty !== null) {
  7064. var dest = destination;
  7065. switch (propertyType) {
  7066. case 0:// Value
  7067. dest[property] = sourceProperty;
  7068. break;
  7069. case 1:// Texture
  7070. if (scene) {
  7071. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  7072. }
  7073. break;
  7074. case 2:// Color3
  7075. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  7076. break;
  7077. case 3:// FresnelParameters
  7078. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  7079. break;
  7080. case 4:// Vector2
  7081. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  7082. break;
  7083. case 5:// Vector3
  7084. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  7085. break;
  7086. case 6:// Mesh reference
  7087. if (scene) {
  7088. dest[property] = scene.getLastMeshByID(sourceProperty);
  7089. }
  7090. break;
  7091. case 7:// Color Curves
  7092. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  7093. break;
  7094. case 8:// Color 4
  7095. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  7096. break;
  7097. case 9:// Image Processing
  7098. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  7099. break;
  7100. }
  7101. }
  7102. }
  7103. return destination;
  7104. };
  7105. SerializationHelper.Clone = function (creationFunction, source) {
  7106. return _copySource(creationFunction, source, false);
  7107. };
  7108. SerializationHelper.Instanciate = function (creationFunction, source) {
  7109. return _copySource(creationFunction, source, true);
  7110. };
  7111. return SerializationHelper;
  7112. }());
  7113. BABYLON.SerializationHelper = SerializationHelper;
  7114. })(BABYLON || (BABYLON = {}));
  7115. //# sourceMappingURL=babylon.decorators.js.map
  7116. var BABYLON;
  7117. (function (BABYLON) {
  7118. /**
  7119. * Wrapper class for promise with external resolve and reject.
  7120. */
  7121. var Deferred = /** @class */ (function () {
  7122. /**
  7123. * Constructor for this deferred object.
  7124. */
  7125. function Deferred() {
  7126. var _this = this;
  7127. this.promise = new Promise(function (resolve, reject) {
  7128. _this._resolve = resolve;
  7129. _this._reject = reject;
  7130. });
  7131. }
  7132. Object.defineProperty(Deferred.prototype, "resolve", {
  7133. /**
  7134. * The resolve method of the promise associated with this deferred object.
  7135. */
  7136. get: function () {
  7137. return this._resolve;
  7138. },
  7139. enumerable: true,
  7140. configurable: true
  7141. });
  7142. Object.defineProperty(Deferred.prototype, "reject", {
  7143. /**
  7144. * The reject method of the promise associated with this deferred object.
  7145. */
  7146. get: function () {
  7147. return this._reject;
  7148. },
  7149. enumerable: true,
  7150. configurable: true
  7151. });
  7152. return Deferred;
  7153. }());
  7154. BABYLON.Deferred = Deferred;
  7155. })(BABYLON || (BABYLON = {}));
  7156. //# sourceMappingURL=babylon.deferred.js.map
  7157. var BABYLON;
  7158. (function (BABYLON) {
  7159. /**
  7160. * A class serves as a medium between the observable and its observers
  7161. */
  7162. var EventState = /** @class */ (function () {
  7163. /**
  7164. * Create a new EventState
  7165. * @param mask defines the mask associated with this state
  7166. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  7167. * @param target defines the original target of the state
  7168. * @param currentTarget defines the current target of the state
  7169. */
  7170. function EventState(mask, skipNextObservers, target, currentTarget) {
  7171. if (skipNextObservers === void 0) { skipNextObservers = false; }
  7172. this.initalize(mask, skipNextObservers, target, currentTarget);
  7173. }
  7174. /**
  7175. * Initialize the current event state
  7176. * @param mask defines the mask associated with this state
  7177. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  7178. * @param target defines the original target of the state
  7179. * @param currentTarget defines the current target of the state
  7180. * @returns the current event state
  7181. */
  7182. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  7183. if (skipNextObservers === void 0) { skipNextObservers = false; }
  7184. this.mask = mask;
  7185. this.skipNextObservers = skipNextObservers;
  7186. this.target = target;
  7187. this.currentTarget = currentTarget;
  7188. return this;
  7189. };
  7190. return EventState;
  7191. }());
  7192. BABYLON.EventState = EventState;
  7193. /**
  7194. * Represent an Observer registered to a given Observable object.
  7195. */
  7196. var Observer = /** @class */ (function () {
  7197. /**
  7198. * Creates a new observer
  7199. * @param callback defines the callback to call when the observer is notified
  7200. * @param mask defines the mask of the observer (used to filter notifications)
  7201. * @param scope defines the current scope used to restore the JS context
  7202. */
  7203. function Observer(
  7204. /**
  7205. * Defines the callback to call when the observer is notified
  7206. */
  7207. callback,
  7208. /**
  7209. * Defines the mask of the observer (used to filter notifications)
  7210. */
  7211. mask,
  7212. /**
  7213. * Defines the current scope used to restore the JS context
  7214. */
  7215. scope) {
  7216. if (scope === void 0) { scope = null; }
  7217. this.callback = callback;
  7218. this.mask = mask;
  7219. this.scope = scope;
  7220. /** @ignore */
  7221. this._willBeUnregistered = false;
  7222. /**
  7223. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  7224. */
  7225. this.unregisterOnNextCall = false;
  7226. }
  7227. return Observer;
  7228. }());
  7229. BABYLON.Observer = Observer;
  7230. /**
  7231. * Represent a list of observers registered to multiple Observables object.
  7232. */
  7233. var MultiObserver = /** @class */ (function () {
  7234. function MultiObserver() {
  7235. }
  7236. /**
  7237. * Release associated resources
  7238. */
  7239. MultiObserver.prototype.dispose = function () {
  7240. if (this._observers && this._observables) {
  7241. for (var index = 0; index < this._observers.length; index++) {
  7242. this._observables[index].remove(this._observers[index]);
  7243. }
  7244. }
  7245. this._observers = null;
  7246. this._observables = null;
  7247. };
  7248. /**
  7249. * Raise a callback when one of the observable will notify
  7250. * @param observables defines a list of observables to watch
  7251. * @param callback defines the callback to call on notification
  7252. * @param mask defines the mask used to filter notifications
  7253. * @param scope defines the current scope used to restore the JS context
  7254. * @returns the new MultiObserver
  7255. */
  7256. MultiObserver.Watch = function (observables, callback, mask, scope) {
  7257. if (mask === void 0) { mask = -1; }
  7258. if (scope === void 0) { scope = null; }
  7259. var result = new MultiObserver();
  7260. result._observers = new Array();
  7261. result._observables = observables;
  7262. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  7263. var observable = observables_1[_i];
  7264. var observer = observable.add(callback, mask, false, scope);
  7265. if (observer) {
  7266. result._observers.push(observer);
  7267. }
  7268. }
  7269. return result;
  7270. };
  7271. return MultiObserver;
  7272. }());
  7273. BABYLON.MultiObserver = MultiObserver;
  7274. /**
  7275. * The Observable class is a simple implementation of the Observable pattern.
  7276. * There's one slight particularity though: a given Observable can notify its observer using a particular mask value, only the Observers registered with this mask value will be notified.
  7277. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  7278. * For instance you may have a given Observable that have four different types of notifications: Move (mask = 0x01), Stop (mask = 0x02), Turn Right (mask = 0X04), Turn Left (mask = 0X08).
  7279. * A given observer can register itself with only Move and Stop (mask = 0x03), then it will only be notified when one of these two occurs and will never be for Turn Left/Right.
  7280. */
  7281. var Observable = /** @class */ (function () {
  7282. /**
  7283. * Creates a new observable
  7284. * @param onObserverAdded defines a callback to call when a new observer is added
  7285. */
  7286. function Observable(onObserverAdded) {
  7287. this._observers = new Array();
  7288. this._eventState = new EventState(0);
  7289. if (onObserverAdded) {
  7290. this._onObserverAdded = onObserverAdded;
  7291. }
  7292. }
  7293. /**
  7294. * Create a new Observer with the specified callback
  7295. * @param callback the callback that will be executed for that Observer
  7296. * @param mask the mask used to filter observers
  7297. * @param insertFirst if true the callback will be inserted at the first position, hence executed before the others ones. If false (default behavior) the callback will be inserted at the last position, executed after all the others already present.
  7298. * @param scope optional scope for the callback to be called from
  7299. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  7300. * @returns the new observer created for the callback
  7301. */
  7302. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  7303. if (mask === void 0) { mask = -1; }
  7304. if (insertFirst === void 0) { insertFirst = false; }
  7305. if (scope === void 0) { scope = null; }
  7306. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  7307. if (!callback) {
  7308. return null;
  7309. }
  7310. var observer = new Observer(callback, mask, scope);
  7311. observer.unregisterOnNextCall = unregisterOnFirstCall;
  7312. if (insertFirst) {
  7313. this._observers.unshift(observer);
  7314. }
  7315. else {
  7316. this._observers.push(observer);
  7317. }
  7318. if (this._onObserverAdded) {
  7319. this._onObserverAdded(observer);
  7320. }
  7321. return observer;
  7322. };
  7323. /**
  7324. * Remove an Observer from the Observable object
  7325. * @param observer the instance of the Observer to remove
  7326. * @returns false if it doesn't belong to this Observable
  7327. */
  7328. Observable.prototype.remove = function (observer) {
  7329. if (!observer) {
  7330. return false;
  7331. }
  7332. var index = this._observers.indexOf(observer);
  7333. if (index !== -1) {
  7334. this._observers.splice(index, 1);
  7335. return true;
  7336. }
  7337. return false;
  7338. };
  7339. /**
  7340. * Remove a callback from the Observable object
  7341. * @param callback the callback to remove
  7342. * @param scope optional scope. If used only the callbacks with this scope will be removed
  7343. * @returns false if it doesn't belong to this Observable
  7344. */
  7345. Observable.prototype.removeCallback = function (callback, scope) {
  7346. for (var index = 0; index < this._observers.length; index++) {
  7347. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  7348. this._observers.splice(index, 1);
  7349. return true;
  7350. }
  7351. }
  7352. return false;
  7353. };
  7354. Observable.prototype._deferUnregister = function (observer) {
  7355. var _this = this;
  7356. observer.unregisterOnNextCall = false;
  7357. observer._willBeUnregistered = true;
  7358. BABYLON.Tools.SetImmediate(function () {
  7359. _this.remove(observer);
  7360. });
  7361. };
  7362. /**
  7363. * Notify all Observers by calling their respective callback with the given data
  7364. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  7365. * @param eventData defines the data to send to all observers
  7366. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  7367. * @param target defines the original target of the state
  7368. * @param currentTarget defines the current target of the state
  7369. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  7370. */
  7371. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  7372. if (mask === void 0) { mask = -1; }
  7373. if (!this._observers.length) {
  7374. return true;
  7375. }
  7376. var state = this._eventState;
  7377. state.mask = mask;
  7378. state.target = target;
  7379. state.currentTarget = currentTarget;
  7380. state.skipNextObservers = false;
  7381. state.lastReturnValue = eventData;
  7382. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  7383. var obs = _a[_i];
  7384. if (obs._willBeUnregistered) {
  7385. continue;
  7386. }
  7387. if (obs.mask & mask) {
  7388. if (obs.scope) {
  7389. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  7390. }
  7391. else {
  7392. state.lastReturnValue = obs.callback(eventData, state);
  7393. }
  7394. if (obs.unregisterOnNextCall) {
  7395. this._deferUnregister(obs);
  7396. }
  7397. }
  7398. if (state.skipNextObservers) {
  7399. return false;
  7400. }
  7401. }
  7402. return true;
  7403. };
  7404. /**
  7405. * Calling this will execute each callback, expecting it to be a promise or return a value.
  7406. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  7407. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  7408. * and it is crucial that all callbacks will be executed.
  7409. * The order of the callbacks is kept, callbacks are not executed parallel.
  7410. *
  7411. * @param eventData The data to be sent to each callback
  7412. * @param mask is used to filter observers defaults to -1
  7413. * @param target defines the callback target (see EventState)
  7414. * @param currentTarget defines he current object in the bubbling phase
  7415. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  7416. */
  7417. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  7418. var _this = this;
  7419. if (mask === void 0) { mask = -1; }
  7420. // create an empty promise
  7421. var p = Promise.resolve(eventData);
  7422. // no observers? return this promise.
  7423. if (!this._observers.length) {
  7424. return p;
  7425. }
  7426. var state = this._eventState;
  7427. state.mask = mask;
  7428. state.target = target;
  7429. state.currentTarget = currentTarget;
  7430. state.skipNextObservers = false;
  7431. // execute one callback after another (not using Promise.all, the order is important)
  7432. this._observers.forEach(function (obs) {
  7433. if (state.skipNextObservers) {
  7434. return;
  7435. }
  7436. if (obs._willBeUnregistered) {
  7437. return;
  7438. }
  7439. if (obs.mask & mask) {
  7440. if (obs.scope) {
  7441. p = p.then(function (lastReturnedValue) {
  7442. state.lastReturnValue = lastReturnedValue;
  7443. return obs.callback.apply(obs.scope, [eventData, state]);
  7444. });
  7445. }
  7446. else {
  7447. p = p.then(function (lastReturnedValue) {
  7448. state.lastReturnValue = lastReturnedValue;
  7449. return obs.callback(eventData, state);
  7450. });
  7451. }
  7452. if (obs.unregisterOnNextCall) {
  7453. _this._deferUnregister(obs);
  7454. }
  7455. }
  7456. });
  7457. // return the eventData
  7458. return p.then(function () { return eventData; });
  7459. };
  7460. /**
  7461. * Notify a specific observer
  7462. * @param observer defines the observer to notify
  7463. * @param eventData defines the data to be sent to each callback
  7464. * @param mask is used to filter observers defaults to -1
  7465. */
  7466. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  7467. if (mask === void 0) { mask = -1; }
  7468. var state = this._eventState;
  7469. state.mask = mask;
  7470. state.skipNextObservers = false;
  7471. observer.callback(eventData, state);
  7472. };
  7473. /**
  7474. * Gets a boolean indicating if the observable has at least one observer
  7475. * @returns true is the Observable has at least one Observer registered
  7476. */
  7477. Observable.prototype.hasObservers = function () {
  7478. return this._observers.length > 0;
  7479. };
  7480. /**
  7481. * Clear the list of observers
  7482. */
  7483. Observable.prototype.clear = function () {
  7484. this._observers = new Array();
  7485. this._onObserverAdded = null;
  7486. };
  7487. /**
  7488. * Clone the current observable
  7489. * @returns a new observable
  7490. */
  7491. Observable.prototype.clone = function () {
  7492. var result = new Observable();
  7493. result._observers = this._observers.slice(0);
  7494. return result;
  7495. };
  7496. /**
  7497. * Does this observable handles observer registered with a given mask
  7498. * @param mask defines the mask to be tested
  7499. * @return whether or not one observer registered with the given mask is handeled
  7500. **/
  7501. Observable.prototype.hasSpecificMask = function (mask) {
  7502. if (mask === void 0) { mask = -1; }
  7503. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  7504. var obs = _a[_i];
  7505. if (obs.mask & mask || obs.mask === mask) {
  7506. return true;
  7507. }
  7508. }
  7509. return false;
  7510. };
  7511. return Observable;
  7512. }());
  7513. BABYLON.Observable = Observable;
  7514. })(BABYLON || (BABYLON = {}));
  7515. //# sourceMappingURL=babylon.observable.js.map
  7516. var BABYLON;
  7517. (function (BABYLON) {
  7518. var SmartArray = /** @class */ (function () {
  7519. function SmartArray(capacity) {
  7520. this.length = 0;
  7521. this.data = new Array(capacity);
  7522. this._id = SmartArray._GlobalId++;
  7523. }
  7524. SmartArray.prototype.push = function (value) {
  7525. this.data[this.length++] = value;
  7526. if (this.length > this.data.length) {
  7527. this.data.length *= 2;
  7528. }
  7529. };
  7530. SmartArray.prototype.forEach = function (func) {
  7531. for (var index = 0; index < this.length; index++) {
  7532. func(this.data[index]);
  7533. }
  7534. };
  7535. SmartArray.prototype.sort = function (compareFn) {
  7536. this.data.sort(compareFn);
  7537. };
  7538. SmartArray.prototype.reset = function () {
  7539. this.length = 0;
  7540. };
  7541. SmartArray.prototype.dispose = function () {
  7542. this.reset();
  7543. if (this.data) {
  7544. this.data.length = 0;
  7545. this.data = [];
  7546. }
  7547. };
  7548. SmartArray.prototype.concat = function (array) {
  7549. if (array.length === 0) {
  7550. return;
  7551. }
  7552. if (this.length + array.length > this.data.length) {
  7553. this.data.length = (this.length + array.length) * 2;
  7554. }
  7555. for (var index = 0; index < array.length; index++) {
  7556. this.data[this.length++] = (array.data || array)[index];
  7557. }
  7558. };
  7559. SmartArray.prototype.indexOf = function (value) {
  7560. var position = this.data.indexOf(value);
  7561. if (position >= this.length) {
  7562. return -1;
  7563. }
  7564. return position;
  7565. };
  7566. SmartArray.prototype.contains = function (value) {
  7567. return this.data.indexOf(value) !== -1;
  7568. };
  7569. // Statics
  7570. SmartArray._GlobalId = 0;
  7571. return SmartArray;
  7572. }());
  7573. BABYLON.SmartArray = SmartArray;
  7574. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  7575. __extends(SmartArrayNoDuplicate, _super);
  7576. function SmartArrayNoDuplicate() {
  7577. var _this = _super !== null && _super.apply(this, arguments) || this;
  7578. _this._duplicateId = 0;
  7579. return _this;
  7580. }
  7581. SmartArrayNoDuplicate.prototype.push = function (value) {
  7582. _super.prototype.push.call(this, value);
  7583. if (!value.__smartArrayFlags) {
  7584. value.__smartArrayFlags = {};
  7585. }
  7586. value.__smartArrayFlags[this._id] = this._duplicateId;
  7587. };
  7588. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  7589. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  7590. return false;
  7591. }
  7592. this.push(value);
  7593. return true;
  7594. };
  7595. SmartArrayNoDuplicate.prototype.reset = function () {
  7596. _super.prototype.reset.call(this);
  7597. this._duplicateId++;
  7598. };
  7599. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  7600. if (array.length === 0) {
  7601. return;
  7602. }
  7603. if (this.length + array.length > this.data.length) {
  7604. this.data.length = (this.length + array.length) * 2;
  7605. }
  7606. for (var index = 0; index < array.length; index++) {
  7607. var item = (array.data || array)[index];
  7608. this.pushNoDuplicate(item);
  7609. }
  7610. };
  7611. return SmartArrayNoDuplicate;
  7612. }(SmartArray));
  7613. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  7614. })(BABYLON || (BABYLON = {}));
  7615. //# sourceMappingURL=babylon.smartArray.js.map
  7616. var BABYLON;
  7617. (function (BABYLON) {
  7618. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  7619. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  7620. var LoadFileError = /** @class */ (function (_super) {
  7621. __extends(LoadFileError, _super);
  7622. function LoadFileError(message, request) {
  7623. var _this = _super.call(this, message) || this;
  7624. _this.request = request;
  7625. _this.name = "LoadFileError";
  7626. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  7627. return _this;
  7628. }
  7629. // Polyfill for Object.setPrototypeOf if necessary.
  7630. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  7631. return LoadFileError;
  7632. }(Error));
  7633. BABYLON.LoadFileError = LoadFileError;
  7634. var RetryStrategy = /** @class */ (function () {
  7635. function RetryStrategy() {
  7636. }
  7637. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  7638. if (maxRetries === void 0) { maxRetries = 3; }
  7639. if (baseInterval === void 0) { baseInterval = 500; }
  7640. return function (url, request, retryIndex) {
  7641. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  7642. return -1;
  7643. }
  7644. return Math.pow(2, retryIndex) * baseInterval;
  7645. };
  7646. };
  7647. return RetryStrategy;
  7648. }());
  7649. BABYLON.RetryStrategy = RetryStrategy;
  7650. // Screenshots
  7651. var screenshotCanvas;
  7652. var cloneValue = function (source, destinationObject) {
  7653. if (!source)
  7654. return null;
  7655. if (source instanceof BABYLON.Mesh) {
  7656. return null;
  7657. }
  7658. if (source instanceof BABYLON.SubMesh) {
  7659. return source.clone(destinationObject);
  7660. }
  7661. else if (source.clone) {
  7662. return source.clone();
  7663. }
  7664. return null;
  7665. };
  7666. var Tools = /** @class */ (function () {
  7667. function Tools() {
  7668. }
  7669. /**
  7670. * Interpolates between a and b via alpha
  7671. * @param a The lower value (returned when alpha = 0)
  7672. * @param b The upper value (returned when alpha = 1)
  7673. * @param alpha The interpolation-factor
  7674. * @return The mixed value
  7675. */
  7676. Tools.Mix = function (a, b, alpha) {
  7677. return a * (1 - alpha) + b * alpha;
  7678. };
  7679. Tools.Instantiate = function (className) {
  7680. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  7681. return Tools.RegisteredExternalClasses[className];
  7682. }
  7683. var arr = className.split(".");
  7684. var fn = (window || this);
  7685. for (var i = 0, len = arr.length; i < len; i++) {
  7686. fn = fn[arr[i]];
  7687. }
  7688. if (typeof fn !== "function") {
  7689. return null;
  7690. }
  7691. return fn;
  7692. };
  7693. /**
  7694. * Provides a slice function that will work even on IE
  7695. * @param data defines the array to slice
  7696. * @returns the new sliced array
  7697. */
  7698. Tools.Slice = function (data) {
  7699. if (data.slice) {
  7700. return data.slice();
  7701. }
  7702. return Array.prototype.slice.call(data);
  7703. };
  7704. Tools.SetImmediate = function (action) {
  7705. if (window.setImmediate) {
  7706. window.setImmediate(action);
  7707. }
  7708. else {
  7709. setTimeout(action, 1);
  7710. }
  7711. };
  7712. Tools.IsExponentOfTwo = function (value) {
  7713. var count = 1;
  7714. do {
  7715. count *= 2;
  7716. } while (count < value);
  7717. return count === value;
  7718. };
  7719. /**
  7720. * Find the next highest power of two.
  7721. * @param x Number to start search from.
  7722. * @return Next highest power of two.
  7723. */
  7724. Tools.CeilingPOT = function (x) {
  7725. x--;
  7726. x |= x >> 1;
  7727. x |= x >> 2;
  7728. x |= x >> 4;
  7729. x |= x >> 8;
  7730. x |= x >> 16;
  7731. x++;
  7732. return x;
  7733. };
  7734. /**
  7735. * Find the next lowest power of two.
  7736. * @param x Number to start search from.
  7737. * @return Next lowest power of two.
  7738. */
  7739. Tools.FloorPOT = function (x) {
  7740. x = x | (x >> 1);
  7741. x = x | (x >> 2);
  7742. x = x | (x >> 4);
  7743. x = x | (x >> 8);
  7744. x = x | (x >> 16);
  7745. return x - (x >> 1);
  7746. };
  7747. /**
  7748. * Find the nearest power of two.
  7749. * @param x Number to start search from.
  7750. * @return Next nearest power of two.
  7751. */
  7752. Tools.NearestPOT = function (x) {
  7753. var c = Tools.CeilingPOT(x);
  7754. var f = Tools.FloorPOT(x);
  7755. return (c - x) > (x - f) ? f : c;
  7756. };
  7757. Tools.GetExponentOfTwo = function (value, max, mode) {
  7758. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  7759. var pot;
  7760. switch (mode) {
  7761. case BABYLON.Engine.SCALEMODE_FLOOR:
  7762. pot = Tools.FloorPOT(value);
  7763. break;
  7764. case BABYLON.Engine.SCALEMODE_NEAREST:
  7765. pot = Tools.NearestPOT(value);
  7766. break;
  7767. case BABYLON.Engine.SCALEMODE_CEILING:
  7768. default:
  7769. pot = Tools.CeilingPOT(value);
  7770. break;
  7771. }
  7772. return Math.min(pot, max);
  7773. };
  7774. Tools.GetFilename = function (path) {
  7775. var index = path.lastIndexOf("/");
  7776. if (index < 0)
  7777. return path;
  7778. return path.substring(index + 1);
  7779. };
  7780. /**
  7781. * Extracts the "folder" part of a path (everything before the filename).
  7782. * @param uri The URI to extract the info from
  7783. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  7784. * @returns The "folder" part of the path
  7785. */
  7786. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  7787. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  7788. var index = uri.lastIndexOf("/");
  7789. if (index < 0) {
  7790. if (returnUnchangedIfNoSlash) {
  7791. return uri;
  7792. }
  7793. return "";
  7794. }
  7795. return uri.substring(0, index + 1);
  7796. };
  7797. Tools.GetDOMTextContent = function (element) {
  7798. var result = "";
  7799. var child = element.firstChild;
  7800. while (child) {
  7801. if (child.nodeType === 3) {
  7802. result += child.textContent;
  7803. }
  7804. child = child.nextSibling;
  7805. }
  7806. return result;
  7807. };
  7808. Tools.ToDegrees = function (angle) {
  7809. return angle * 180 / Math.PI;
  7810. };
  7811. Tools.ToRadians = function (angle) {
  7812. return angle * Math.PI / 180;
  7813. };
  7814. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  7815. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  7816. var output = "";
  7817. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  7818. var i = 0;
  7819. var bytes = new Uint8Array(buffer);
  7820. while (i < bytes.length) {
  7821. chr1 = bytes[i++];
  7822. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  7823. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  7824. enc1 = chr1 >> 2;
  7825. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  7826. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  7827. enc4 = chr3 & 63;
  7828. if (isNaN(chr2)) {
  7829. enc3 = enc4 = 64;
  7830. }
  7831. else if (isNaN(chr3)) {
  7832. enc4 = 64;
  7833. }
  7834. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  7835. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  7836. }
  7837. return "data:image/png;base64," + output;
  7838. };
  7839. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  7840. if (bias === void 0) { bias = null; }
  7841. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  7842. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  7843. for (var index = indexStart; index < indexStart + indexCount; index++) {
  7844. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  7845. minimum = BABYLON.Vector3.Minimize(current, minimum);
  7846. maximum = BABYLON.Vector3.Maximize(current, maximum);
  7847. }
  7848. if (bias) {
  7849. minimum.x -= minimum.x * bias.x + bias.y;
  7850. minimum.y -= minimum.y * bias.x + bias.y;
  7851. minimum.z -= minimum.z * bias.x + bias.y;
  7852. maximum.x += maximum.x * bias.x + bias.y;
  7853. maximum.y += maximum.y * bias.x + bias.y;
  7854. maximum.z += maximum.z * bias.x + bias.y;
  7855. }
  7856. return {
  7857. minimum: minimum,
  7858. maximum: maximum
  7859. };
  7860. };
  7861. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  7862. if (bias === void 0) { bias = null; }
  7863. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  7864. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  7865. if (!stride) {
  7866. stride = 3;
  7867. }
  7868. for (var index = start; index < start + count; index++) {
  7869. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  7870. minimum = BABYLON.Vector3.Minimize(current, minimum);
  7871. maximum = BABYLON.Vector3.Maximize(current, maximum);
  7872. }
  7873. if (bias) {
  7874. minimum.x -= minimum.x * bias.x + bias.y;
  7875. minimum.y -= minimum.y * bias.x + bias.y;
  7876. minimum.z -= minimum.z * bias.x + bias.y;
  7877. maximum.x += maximum.x * bias.x + bias.y;
  7878. maximum.y += maximum.y * bias.x + bias.y;
  7879. maximum.z += maximum.z * bias.x + bias.y;
  7880. }
  7881. return {
  7882. minimum: minimum,
  7883. maximum: maximum
  7884. };
  7885. };
  7886. Tools.Vector2ArrayFeeder = function (array) {
  7887. return function (index) {
  7888. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  7889. var length = isFloatArray ? array.length / 2 : array.length;
  7890. if (index >= length) {
  7891. return null;
  7892. }
  7893. if (isFloatArray) {
  7894. var fa = array;
  7895. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  7896. }
  7897. var a = array;
  7898. return a[index];
  7899. };
  7900. };
  7901. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  7902. if (bias === void 0) { bias = null; }
  7903. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  7904. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  7905. var i = 0;
  7906. var cur = feeder(i++);
  7907. while (cur) {
  7908. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  7909. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  7910. cur = feeder(i++);
  7911. }
  7912. if (bias) {
  7913. minimum.x -= minimum.x * bias.x + bias.y;
  7914. minimum.y -= minimum.y * bias.x + bias.y;
  7915. maximum.x += maximum.x * bias.x + bias.y;
  7916. maximum.y += maximum.y * bias.x + bias.y;
  7917. }
  7918. return {
  7919. minimum: minimum,
  7920. maximum: maximum
  7921. };
  7922. };
  7923. Tools.MakeArray = function (obj, allowsNullUndefined) {
  7924. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  7925. return null;
  7926. return Array.isArray(obj) ? obj : [obj];
  7927. };
  7928. // Misc.
  7929. Tools.GetPointerPrefix = function () {
  7930. var eventPrefix = "pointer";
  7931. // Check if pointer events are supported
  7932. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  7933. eventPrefix = "mouse";
  7934. }
  7935. return eventPrefix;
  7936. };
  7937. /**
  7938. * @param func - the function to be called
  7939. * @param requester - the object that will request the next frame. Falls back to window.
  7940. */
  7941. Tools.QueueNewFrame = function (func, requester) {
  7942. if (!Tools.IsWindowObjectExist()) {
  7943. return setTimeout(func, 16);
  7944. }
  7945. if (!requester) {
  7946. requester = window;
  7947. }
  7948. if (requester.requestAnimationFrame) {
  7949. return requester.requestAnimationFrame(func);
  7950. }
  7951. else if (requester.msRequestAnimationFrame) {
  7952. return requester.msRequestAnimationFrame(func);
  7953. }
  7954. else if (requester.webkitRequestAnimationFrame) {
  7955. return requester.webkitRequestAnimationFrame(func);
  7956. }
  7957. else if (requester.mozRequestAnimationFrame) {
  7958. return requester.mozRequestAnimationFrame(func);
  7959. }
  7960. else if (requester.oRequestAnimationFrame) {
  7961. return requester.oRequestAnimationFrame(func);
  7962. }
  7963. else {
  7964. return window.setTimeout(func, 16);
  7965. }
  7966. };
  7967. Tools.RequestFullscreen = function (element) {
  7968. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  7969. if (!requestFunction)
  7970. return;
  7971. requestFunction.call(element);
  7972. };
  7973. Tools.ExitFullscreen = function () {
  7974. if (document.exitFullscreen) {
  7975. document.exitFullscreen();
  7976. }
  7977. else if (document.mozCancelFullScreen) {
  7978. document.mozCancelFullScreen();
  7979. }
  7980. else if (document.webkitCancelFullScreen) {
  7981. document.webkitCancelFullScreen();
  7982. }
  7983. else if (document.msCancelFullScreen) {
  7984. document.msCancelFullScreen();
  7985. }
  7986. };
  7987. Tools.SetCorsBehavior = function (url, element) {
  7988. if (url && url.indexOf("data:") === 0) {
  7989. return;
  7990. }
  7991. if (Tools.CorsBehavior) {
  7992. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  7993. element.crossOrigin = Tools.CorsBehavior;
  7994. }
  7995. else {
  7996. var result = Tools.CorsBehavior(url);
  7997. if (result) {
  7998. element.crossOrigin = result;
  7999. }
  8000. }
  8001. }
  8002. };
  8003. // External files
  8004. Tools.CleanUrl = function (url) {
  8005. url = url.replace(/#/mg, "%23");
  8006. return url;
  8007. };
  8008. Tools.LoadImage = function (url, onLoad, onError, database) {
  8009. if (url instanceof ArrayBuffer) {
  8010. url = Tools.EncodeArrayBufferTobase64(url);
  8011. }
  8012. url = Tools.CleanUrl(url);
  8013. url = Tools.PreprocessUrl(url);
  8014. var img = new Image();
  8015. Tools.SetCorsBehavior(url, img);
  8016. var loadHandler = function () {
  8017. img.removeEventListener("load", loadHandler);
  8018. img.removeEventListener("error", errorHandler);
  8019. onLoad(img);
  8020. };
  8021. var errorHandler = function (err) {
  8022. img.removeEventListener("load", loadHandler);
  8023. img.removeEventListener("error", errorHandler);
  8024. Tools.Error("Error while trying to load image: " + url);
  8025. if (onError) {
  8026. onError("Error while trying to load image: " + url, err);
  8027. }
  8028. };
  8029. img.addEventListener("load", loadHandler);
  8030. img.addEventListener("error", errorHandler);
  8031. var noIndexedDB = function () {
  8032. img.src = url;
  8033. };
  8034. var loadFromIndexedDB = function () {
  8035. if (database) {
  8036. database.loadImageFromDB(url, img);
  8037. }
  8038. };
  8039. //ANY database to do!
  8040. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  8041. database.openAsync(loadFromIndexedDB, noIndexedDB);
  8042. }
  8043. else {
  8044. if (url.indexOf("file:") !== -1) {
  8045. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  8046. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  8047. try {
  8048. var blobURL;
  8049. try {
  8050. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  8051. }
  8052. catch (ex) {
  8053. // Chrome doesn't support oneTimeOnly parameter
  8054. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  8055. }
  8056. img.src = blobURL;
  8057. }
  8058. catch (e) {
  8059. img.src = "";
  8060. }
  8061. return img;
  8062. }
  8063. }
  8064. noIndexedDB();
  8065. }
  8066. return img;
  8067. };
  8068. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  8069. url = Tools.CleanUrl(url);
  8070. url = Tools.PreprocessUrl(url);
  8071. // If file and file input are set
  8072. if (url.indexOf("file:") !== -1) {
  8073. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  8074. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  8075. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  8076. }
  8077. }
  8078. var loadUrl = Tools.BaseUrl + url;
  8079. var aborted = false;
  8080. var fileRequest = {
  8081. onCompleteObservable: new BABYLON.Observable(),
  8082. abort: function () { return aborted = true; },
  8083. };
  8084. var requestFile = function () {
  8085. var request = new XMLHttpRequest();
  8086. var retryHandle = null;
  8087. fileRequest.abort = function () {
  8088. aborted = true;
  8089. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  8090. request.abort();
  8091. }
  8092. if (retryHandle !== null) {
  8093. clearTimeout(retryHandle);
  8094. retryHandle = null;
  8095. }
  8096. };
  8097. var retryLoop = function (retryIndex) {
  8098. request.open('GET', loadUrl, true);
  8099. if (useArrayBuffer) {
  8100. request.responseType = "arraybuffer";
  8101. }
  8102. if (onProgress) {
  8103. request.addEventListener("progress", onProgress);
  8104. }
  8105. var onLoadEnd = function () {
  8106. request.removeEventListener("loadend", onLoadEnd);
  8107. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  8108. fileRequest.onCompleteObservable.clear();
  8109. };
  8110. request.addEventListener("loadend", onLoadEnd);
  8111. var onReadyStateChange = function () {
  8112. if (aborted) {
  8113. return;
  8114. }
  8115. // In case of undefined state in some browsers.
  8116. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  8117. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  8118. request.removeEventListener("readystatechange", onReadyStateChange);
  8119. if (request.status >= 200 && request.status < 300 || (!Tools.IsWindowObjectExist() && (request.status === 0))) {
  8120. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  8121. return;
  8122. }
  8123. var retryStrategy = Tools.DefaultRetryStrategy;
  8124. if (retryStrategy) {
  8125. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  8126. if (waitTime !== -1) {
  8127. // Prevent the request from completing for retry.
  8128. request.removeEventListener("loadend", onLoadEnd);
  8129. request = new XMLHttpRequest();
  8130. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  8131. return;
  8132. }
  8133. }
  8134. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  8135. if (onError) {
  8136. onError(request, e);
  8137. }
  8138. else {
  8139. throw e;
  8140. }
  8141. }
  8142. };
  8143. request.addEventListener("readystatechange", onReadyStateChange);
  8144. request.send();
  8145. };
  8146. retryLoop(0);
  8147. };
  8148. // Caching all files
  8149. if (database && database.enableSceneOffline) {
  8150. var noIndexedDB_1 = function () {
  8151. if (!aborted) {
  8152. requestFile();
  8153. }
  8154. };
  8155. var loadFromIndexedDB = function () {
  8156. // TODO: database needs to support aborting and should return a IFileRequest
  8157. if (aborted) {
  8158. return;
  8159. }
  8160. if (database) {
  8161. database.loadFileFromDB(url, function (data) {
  8162. if (!aborted) {
  8163. onSuccess(data);
  8164. }
  8165. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  8166. }, onProgress ? function (event) {
  8167. if (!aborted) {
  8168. onProgress(event);
  8169. }
  8170. } : undefined, noIndexedDB_1, useArrayBuffer);
  8171. }
  8172. };
  8173. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  8174. }
  8175. else {
  8176. requestFile();
  8177. }
  8178. return fileRequest;
  8179. };
  8180. /**
  8181. * Load a script (identified by an url). When the url returns, the
  8182. * content of this file is added into a new script element, attached to the DOM (body element)
  8183. */
  8184. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  8185. var head = document.getElementsByTagName('head')[0];
  8186. var script = document.createElement('script');
  8187. script.type = 'text/javascript';
  8188. script.src = scriptUrl;
  8189. script.onload = function () {
  8190. if (onSuccess) {
  8191. onSuccess();
  8192. }
  8193. };
  8194. script.onerror = function (e) {
  8195. if (onError) {
  8196. onError("Unable to load script", e);
  8197. }
  8198. };
  8199. head.appendChild(script);
  8200. };
  8201. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  8202. var reader = new FileReader();
  8203. var request = {
  8204. onCompleteObservable: new BABYLON.Observable(),
  8205. abort: function () { return reader.abort(); },
  8206. };
  8207. reader.onloadend = function (e) {
  8208. request.onCompleteObservable.notifyObservers(request);
  8209. };
  8210. reader.onload = function (e) {
  8211. //target doesn't have result from ts 1.3
  8212. callback(e.target['result']);
  8213. };
  8214. reader.onprogress = progressCallback;
  8215. reader.readAsDataURL(fileToLoad);
  8216. return request;
  8217. };
  8218. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  8219. var reader = new FileReader();
  8220. var request = {
  8221. onCompleteObservable: new BABYLON.Observable(),
  8222. abort: function () { return reader.abort(); },
  8223. };
  8224. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  8225. reader.onerror = function (e) {
  8226. Tools.Log("Error while reading file: " + fileToLoad.name);
  8227. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  8228. };
  8229. reader.onload = function (e) {
  8230. //target doesn't have result from ts 1.3
  8231. callback(e.target['result']);
  8232. };
  8233. if (progressCallBack) {
  8234. reader.onprogress = progressCallBack;
  8235. }
  8236. if (!useArrayBuffer) {
  8237. // Asynchronous read
  8238. reader.readAsText(fileToLoad);
  8239. }
  8240. else {
  8241. reader.readAsArrayBuffer(fileToLoad);
  8242. }
  8243. return request;
  8244. };
  8245. //returns a downloadable url to a file content.
  8246. Tools.FileAsURL = function (content) {
  8247. var fileBlob = new Blob([content]);
  8248. var url = window.URL || window.webkitURL;
  8249. var link = url.createObjectURL(fileBlob);
  8250. return link;
  8251. };
  8252. // Misc.
  8253. Tools.Format = function (value, decimals) {
  8254. if (decimals === void 0) { decimals = 2; }
  8255. return value.toFixed(decimals);
  8256. };
  8257. Tools.CheckExtends = function (v, min, max) {
  8258. if (v.x < min.x)
  8259. min.x = v.x;
  8260. if (v.y < min.y)
  8261. min.y = v.y;
  8262. if (v.z < min.z)
  8263. min.z = v.z;
  8264. if (v.x > max.x)
  8265. max.x = v.x;
  8266. if (v.y > max.y)
  8267. max.y = v.y;
  8268. if (v.z > max.z)
  8269. max.z = v.z;
  8270. };
  8271. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  8272. for (var prop in source) {
  8273. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  8274. continue;
  8275. }
  8276. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  8277. continue;
  8278. }
  8279. var sourceValue = source[prop];
  8280. var typeOfSourceValue = typeof sourceValue;
  8281. if (typeOfSourceValue === "function") {
  8282. continue;
  8283. }
  8284. if (typeOfSourceValue === "object") {
  8285. if (sourceValue instanceof Array) {
  8286. destination[prop] = [];
  8287. if (sourceValue.length > 0) {
  8288. if (typeof sourceValue[0] == "object") {
  8289. for (var index = 0; index < sourceValue.length; index++) {
  8290. var clonedValue = cloneValue(sourceValue[index], destination);
  8291. if (destination[prop].indexOf(clonedValue) === -1) {
  8292. destination[prop].push(clonedValue);
  8293. }
  8294. }
  8295. }
  8296. else {
  8297. destination[prop] = sourceValue.slice(0);
  8298. }
  8299. }
  8300. }
  8301. else {
  8302. destination[prop] = cloneValue(sourceValue, destination);
  8303. }
  8304. }
  8305. else {
  8306. destination[prop] = sourceValue;
  8307. }
  8308. }
  8309. };
  8310. Tools.IsEmpty = function (obj) {
  8311. for (var i in obj) {
  8312. if (obj.hasOwnProperty(i)) {
  8313. return false;
  8314. }
  8315. }
  8316. return true;
  8317. };
  8318. Tools.RegisterTopRootEvents = function (events) {
  8319. for (var index = 0; index < events.length; index++) {
  8320. var event = events[index];
  8321. window.addEventListener(event.name, event.handler, false);
  8322. try {
  8323. if (window.parent) {
  8324. window.parent.addEventListener(event.name, event.handler, false);
  8325. }
  8326. }
  8327. catch (e) {
  8328. // Silently fails...
  8329. }
  8330. }
  8331. };
  8332. Tools.UnregisterTopRootEvents = function (events) {
  8333. for (var index = 0; index < events.length; index++) {
  8334. var event = events[index];
  8335. window.removeEventListener(event.name, event.handler);
  8336. try {
  8337. if (window.parent) {
  8338. window.parent.removeEventListener(event.name, event.handler);
  8339. }
  8340. }
  8341. catch (e) {
  8342. // Silently fails...
  8343. }
  8344. }
  8345. };
  8346. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  8347. if (mimeType === void 0) { mimeType = "image/png"; }
  8348. // Read the contents of the framebuffer
  8349. var numberOfChannelsByLine = width * 4;
  8350. var halfHeight = height / 2;
  8351. //Reading datas from WebGL
  8352. var data = engine.readPixels(0, 0, width, height);
  8353. //To flip image on Y axis.
  8354. for (var i = 0; i < halfHeight; i++) {
  8355. for (var j = 0; j < numberOfChannelsByLine; j++) {
  8356. var currentCell = j + i * numberOfChannelsByLine;
  8357. var targetLine = height - i - 1;
  8358. var targetCell = j + targetLine * numberOfChannelsByLine;
  8359. var temp = data[currentCell];
  8360. data[currentCell] = data[targetCell];
  8361. data[targetCell] = temp;
  8362. }
  8363. }
  8364. // Create a 2D canvas to store the result
  8365. if (!screenshotCanvas) {
  8366. screenshotCanvas = document.createElement('canvas');
  8367. }
  8368. screenshotCanvas.width = width;
  8369. screenshotCanvas.height = height;
  8370. var context = screenshotCanvas.getContext('2d');
  8371. if (context) {
  8372. // Copy the pixels to a 2D canvas
  8373. var imageData = context.createImageData(width, height);
  8374. var castData = (imageData.data);
  8375. castData.set(data);
  8376. context.putImageData(imageData, 0, 0);
  8377. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  8378. }
  8379. };
  8380. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  8381. if (mimeType === void 0) { mimeType = "image/png"; }
  8382. var base64Image = screenshotCanvas.toDataURL(mimeType);
  8383. if (successCallback) {
  8384. successCallback(base64Image);
  8385. }
  8386. else {
  8387. // We need HTMLCanvasElement.toBlob for HD screenshots
  8388. if (!screenshotCanvas.toBlob) {
  8389. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  8390. screenshotCanvas.toBlob = function (callback, type, quality) {
  8391. var _this = this;
  8392. setTimeout(function () {
  8393. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  8394. for (var i = 0; i < len; i++) {
  8395. arr[i] = binStr.charCodeAt(i);
  8396. }
  8397. callback(new Blob([arr], { type: type || 'image/png' }));
  8398. });
  8399. };
  8400. }
  8401. screenshotCanvas.toBlob(function (blob) {
  8402. var url = URL.createObjectURL(blob);
  8403. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  8404. if (("download" in document.createElement("a"))) {
  8405. var a = window.document.createElement("a");
  8406. a.href = url;
  8407. if (fileName) {
  8408. a.setAttribute("download", fileName);
  8409. }
  8410. else {
  8411. var date = new Date();
  8412. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  8413. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  8414. }
  8415. window.document.body.appendChild(a);
  8416. a.addEventListener("click", function () {
  8417. if (a.parentElement) {
  8418. a.parentElement.removeChild(a);
  8419. }
  8420. });
  8421. a.click();
  8422. }
  8423. else {
  8424. var newWindow = window.open("");
  8425. if (!newWindow)
  8426. return;
  8427. var img = newWindow.document.createElement("img");
  8428. img.onload = function () {
  8429. // no longer need to read the blob so it's revoked
  8430. URL.revokeObjectURL(url);
  8431. };
  8432. img.src = url;
  8433. newWindow.document.body.appendChild(img);
  8434. }
  8435. });
  8436. }
  8437. };
  8438. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  8439. if (mimeType === void 0) { mimeType = "image/png"; }
  8440. var width;
  8441. var height;
  8442. // If a precision value is specified
  8443. if (size.precision) {
  8444. width = Math.round(engine.getRenderWidth() * size.precision);
  8445. height = Math.round(width / engine.getAspectRatio(camera));
  8446. }
  8447. else if (size.width && size.height) {
  8448. width = size.width;
  8449. height = size.height;
  8450. }
  8451. else if (size.width && !size.height) {
  8452. width = size.width;
  8453. height = Math.round(width / engine.getAspectRatio(camera));
  8454. }
  8455. else if (size.height && !size.width) {
  8456. height = size.height;
  8457. width = Math.round(height * engine.getAspectRatio(camera));
  8458. }
  8459. else if (!isNaN(size)) {
  8460. height = size;
  8461. width = size;
  8462. }
  8463. else {
  8464. Tools.Error("Invalid 'size' parameter !");
  8465. return;
  8466. }
  8467. if (!screenshotCanvas) {
  8468. screenshotCanvas = document.createElement('canvas');
  8469. }
  8470. screenshotCanvas.width = width;
  8471. screenshotCanvas.height = height;
  8472. var renderContext = screenshotCanvas.getContext("2d");
  8473. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  8474. var newWidth = width;
  8475. var newHeight = newWidth / ratio;
  8476. if (newHeight > height) {
  8477. newHeight = height;
  8478. newWidth = newHeight * ratio;
  8479. }
  8480. var offsetX = Math.max(0, width - newWidth) / 2;
  8481. var offsetY = Math.max(0, height - newHeight) / 2;
  8482. var renderingCanvas = engine.getRenderingCanvas();
  8483. if (renderContext && renderingCanvas) {
  8484. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  8485. }
  8486. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  8487. };
  8488. /**
  8489. * Generates an image screenshot from the specified camera.
  8490. *
  8491. * @param engine The engine to use for rendering
  8492. * @param camera The camera to use for rendering
  8493. * @param size This parameter can be set to a single number or to an object with the
  8494. * following (optional) properties: precision, width, height. If a single number is passed,
  8495. * it will be used for both width and height. If an object is passed, the screenshot size
  8496. * will be derived from the parameters. The precision property is a multiplier allowing
  8497. * rendering at a higher or lower resolution.
  8498. * @param successCallback The callback receives a single parameter which contains the
  8499. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  8500. * src parameter of an <img> to display it.
  8501. * @param mimeType The MIME type of the screenshot image (default: image/png).
  8502. * Check your browser for supported MIME types.
  8503. * @param samples Texture samples (default: 1)
  8504. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  8505. * @param fileName A name for for the downloaded file.
  8506. * @constructor
  8507. */
  8508. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  8509. if (mimeType === void 0) { mimeType = "image/png"; }
  8510. if (samples === void 0) { samples = 1; }
  8511. if (antialiasing === void 0) { antialiasing = false; }
  8512. var width;
  8513. var height;
  8514. //If a precision value is specified
  8515. if (size.precision) {
  8516. width = Math.round(engine.getRenderWidth() * size.precision);
  8517. height = Math.round(width / engine.getAspectRatio(camera));
  8518. size = { width: width, height: height };
  8519. }
  8520. else if (size.width && size.height) {
  8521. width = size.width;
  8522. height = size.height;
  8523. }
  8524. else if (size.width && !size.height) {
  8525. width = size.width;
  8526. height = Math.round(width / engine.getAspectRatio(camera));
  8527. size = { width: width, height: height };
  8528. }
  8529. else if (size.height && !size.width) {
  8530. height = size.height;
  8531. width = Math.round(height * engine.getAspectRatio(camera));
  8532. size = { width: width, height: height };
  8533. }
  8534. else if (!isNaN(size)) {
  8535. height = size;
  8536. width = size;
  8537. }
  8538. else {
  8539. Tools.Error("Invalid 'size' parameter !");
  8540. return;
  8541. }
  8542. var scene = camera.getScene();
  8543. var previousCamera = null;
  8544. if (scene.activeCamera !== camera) {
  8545. previousCamera = scene.activeCamera;
  8546. scene.activeCamera = camera;
  8547. }
  8548. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  8549. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8550. texture.renderList = null;
  8551. texture.samples = samples;
  8552. if (antialiasing) {
  8553. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  8554. }
  8555. texture.onAfterRenderObservable.add(function () {
  8556. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  8557. });
  8558. scene.incrementRenderId();
  8559. scene.resetCachedMaterial();
  8560. texture.render(true);
  8561. texture.dispose();
  8562. if (previousCamera) {
  8563. scene.activeCamera = previousCamera;
  8564. }
  8565. camera.getProjectionMatrix(true); // Force cache refresh;
  8566. };
  8567. // XHR response validator for local file scenario
  8568. Tools.ValidateXHRData = function (xhr, dataType) {
  8569. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  8570. if (dataType === void 0) { dataType = 7; }
  8571. try {
  8572. if (dataType & 1) {
  8573. if (xhr.responseText && xhr.responseText.length > 0) {
  8574. return true;
  8575. }
  8576. else if (dataType === 1) {
  8577. return false;
  8578. }
  8579. }
  8580. if (dataType & 2) {
  8581. // Check header width and height since there is no "TGA" magic number
  8582. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  8583. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  8584. return true;
  8585. }
  8586. else if (dataType === 2) {
  8587. return false;
  8588. }
  8589. }
  8590. if (dataType & 4) {
  8591. // Check for the "DDS" magic number
  8592. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  8593. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  8594. return true;
  8595. }
  8596. else {
  8597. return false;
  8598. }
  8599. }
  8600. }
  8601. catch (e) {
  8602. // Global protection
  8603. }
  8604. return false;
  8605. };
  8606. /**
  8607. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  8608. * Be aware Math.random() could cause collisions, but:
  8609. * "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"
  8610. */
  8611. Tools.RandomId = function () {
  8612. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  8613. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  8614. return v.toString(16);
  8615. });
  8616. };
  8617. /**
  8618. * Test if the given uri is a base64 string.
  8619. * @param uri The uri to test
  8620. * @return True if the uri is a base64 string or false otherwise.
  8621. */
  8622. Tools.IsBase64 = function (uri) {
  8623. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  8624. };
  8625. /**
  8626. * Decode the given base64 uri.
  8627. * @param uri The uri to decode
  8628. * @return The decoded base64 data.
  8629. */
  8630. Tools.DecodeBase64 = function (uri) {
  8631. var decodedString = atob(uri.split(",")[1]);
  8632. var bufferLength = decodedString.length;
  8633. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  8634. for (var i = 0; i < bufferLength; i++) {
  8635. bufferView[i] = decodedString.charCodeAt(i);
  8636. }
  8637. return bufferView.buffer;
  8638. };
  8639. Object.defineProperty(Tools, "NoneLogLevel", {
  8640. get: function () {
  8641. return Tools._NoneLogLevel;
  8642. },
  8643. enumerable: true,
  8644. configurable: true
  8645. });
  8646. Object.defineProperty(Tools, "MessageLogLevel", {
  8647. get: function () {
  8648. return Tools._MessageLogLevel;
  8649. },
  8650. enumerable: true,
  8651. configurable: true
  8652. });
  8653. Object.defineProperty(Tools, "WarningLogLevel", {
  8654. get: function () {
  8655. return Tools._WarningLogLevel;
  8656. },
  8657. enumerable: true,
  8658. configurable: true
  8659. });
  8660. Object.defineProperty(Tools, "ErrorLogLevel", {
  8661. get: function () {
  8662. return Tools._ErrorLogLevel;
  8663. },
  8664. enumerable: true,
  8665. configurable: true
  8666. });
  8667. Object.defineProperty(Tools, "AllLogLevel", {
  8668. get: function () {
  8669. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  8670. },
  8671. enumerable: true,
  8672. configurable: true
  8673. });
  8674. Tools._AddLogEntry = function (entry) {
  8675. Tools._LogCache = entry + Tools._LogCache;
  8676. if (Tools.OnNewCacheEntry) {
  8677. Tools.OnNewCacheEntry(entry);
  8678. }
  8679. };
  8680. Tools._FormatMessage = function (message) {
  8681. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  8682. var date = new Date();
  8683. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  8684. };
  8685. Tools._LogDisabled = function (message) {
  8686. // nothing to do
  8687. };
  8688. Tools._LogEnabled = function (message) {
  8689. var formattedMessage = Tools._FormatMessage(message);
  8690. console.log("BJS - " + formattedMessage);
  8691. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  8692. Tools._AddLogEntry(entry);
  8693. };
  8694. Tools._WarnDisabled = function (message) {
  8695. // nothing to do
  8696. };
  8697. Tools._WarnEnabled = function (message) {
  8698. var formattedMessage = Tools._FormatMessage(message);
  8699. console.warn("BJS - " + formattedMessage);
  8700. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  8701. Tools._AddLogEntry(entry);
  8702. };
  8703. Tools._ErrorDisabled = function (message) {
  8704. // nothing to do
  8705. };
  8706. Tools._ErrorEnabled = function (message) {
  8707. Tools.errorsCount++;
  8708. var formattedMessage = Tools._FormatMessage(message);
  8709. console.error("BJS - " + formattedMessage);
  8710. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  8711. Tools._AddLogEntry(entry);
  8712. };
  8713. Object.defineProperty(Tools, "LogCache", {
  8714. get: function () {
  8715. return Tools._LogCache;
  8716. },
  8717. enumerable: true,
  8718. configurable: true
  8719. });
  8720. Tools.ClearLogCache = function () {
  8721. Tools._LogCache = "";
  8722. Tools.errorsCount = 0;
  8723. };
  8724. Object.defineProperty(Tools, "LogLevels", {
  8725. set: function (level) {
  8726. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  8727. Tools.Log = Tools._LogEnabled;
  8728. }
  8729. else {
  8730. Tools.Log = Tools._LogDisabled;
  8731. }
  8732. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  8733. Tools.Warn = Tools._WarnEnabled;
  8734. }
  8735. else {
  8736. Tools.Warn = Tools._WarnDisabled;
  8737. }
  8738. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  8739. Tools.Error = Tools._ErrorEnabled;
  8740. }
  8741. else {
  8742. Tools.Error = Tools._ErrorDisabled;
  8743. }
  8744. },
  8745. enumerable: true,
  8746. configurable: true
  8747. });
  8748. Tools.IsWindowObjectExist = function () {
  8749. return (typeof window) !== "undefined";
  8750. };
  8751. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  8752. get: function () {
  8753. return Tools._PerformanceNoneLogLevel;
  8754. },
  8755. enumerable: true,
  8756. configurable: true
  8757. });
  8758. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  8759. get: function () {
  8760. return Tools._PerformanceUserMarkLogLevel;
  8761. },
  8762. enumerable: true,
  8763. configurable: true
  8764. });
  8765. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  8766. get: function () {
  8767. return Tools._PerformanceConsoleLogLevel;
  8768. },
  8769. enumerable: true,
  8770. configurable: true
  8771. });
  8772. Object.defineProperty(Tools, "PerformanceLogLevel", {
  8773. set: function (level) {
  8774. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  8775. Tools.StartPerformanceCounter = Tools._StartUserMark;
  8776. Tools.EndPerformanceCounter = Tools._EndUserMark;
  8777. return;
  8778. }
  8779. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  8780. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  8781. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  8782. return;
  8783. }
  8784. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  8785. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  8786. },
  8787. enumerable: true,
  8788. configurable: true
  8789. });
  8790. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  8791. };
  8792. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  8793. };
  8794. Tools._StartUserMark = function (counterName, condition) {
  8795. if (condition === void 0) { condition = true; }
  8796. if (!Tools._performance) {
  8797. if (!Tools.IsWindowObjectExist()) {
  8798. return;
  8799. }
  8800. Tools._performance = window.performance;
  8801. }
  8802. if (!condition || !Tools._performance.mark) {
  8803. return;
  8804. }
  8805. Tools._performance.mark(counterName + "-Begin");
  8806. };
  8807. Tools._EndUserMark = function (counterName, condition) {
  8808. if (condition === void 0) { condition = true; }
  8809. if (!condition || !Tools._performance.mark) {
  8810. return;
  8811. }
  8812. Tools._performance.mark(counterName + "-End");
  8813. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  8814. };
  8815. Tools._StartPerformanceConsole = function (counterName, condition) {
  8816. if (condition === void 0) { condition = true; }
  8817. if (!condition) {
  8818. return;
  8819. }
  8820. Tools._StartUserMark(counterName, condition);
  8821. if (console.time) {
  8822. console.time(counterName);
  8823. }
  8824. };
  8825. Tools._EndPerformanceConsole = function (counterName, condition) {
  8826. if (condition === void 0) { condition = true; }
  8827. if (!condition) {
  8828. return;
  8829. }
  8830. Tools._EndUserMark(counterName, condition);
  8831. if (console.time) {
  8832. console.timeEnd(counterName);
  8833. }
  8834. };
  8835. Object.defineProperty(Tools, "Now", {
  8836. get: function () {
  8837. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  8838. return window.performance.now();
  8839. }
  8840. return new Date().getTime();
  8841. },
  8842. enumerable: true,
  8843. configurable: true
  8844. });
  8845. /**
  8846. * This method will return the name of the class used to create the instance of the given object.
  8847. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  8848. * @param object the object to get the class name from
  8849. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  8850. */
  8851. Tools.GetClassName = function (object, isType) {
  8852. if (isType === void 0) { isType = false; }
  8853. var name = null;
  8854. if (!isType && object.getClassName) {
  8855. name = object.getClassName();
  8856. }
  8857. else {
  8858. if (object instanceof Object) {
  8859. var classObj = isType ? object : Object.getPrototypeOf(object);
  8860. name = classObj.constructor["__bjsclassName__"];
  8861. }
  8862. if (!name) {
  8863. name = typeof object;
  8864. }
  8865. }
  8866. return name;
  8867. };
  8868. Tools.First = function (array, predicate) {
  8869. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  8870. var el = array_1[_i];
  8871. if (predicate(el)) {
  8872. return el;
  8873. }
  8874. }
  8875. return null;
  8876. };
  8877. /**
  8878. * This method will return the name of the full name of the class, including its owning module (if any).
  8879. * 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).
  8880. * @param object the object to get the class name from
  8881. * @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.
  8882. */
  8883. Tools.getFullClassName = function (object, isType) {
  8884. if (isType === void 0) { isType = false; }
  8885. var className = null;
  8886. var moduleName = null;
  8887. if (!isType && object.getClassName) {
  8888. className = object.getClassName();
  8889. }
  8890. else {
  8891. if (object instanceof Object) {
  8892. var classObj = isType ? object : Object.getPrototypeOf(object);
  8893. className = classObj.constructor["__bjsclassName__"];
  8894. moduleName = classObj.constructor["__bjsmoduleName__"];
  8895. }
  8896. if (!className) {
  8897. className = typeof object;
  8898. }
  8899. }
  8900. if (!className) {
  8901. return null;
  8902. }
  8903. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  8904. };
  8905. /**
  8906. * 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.
  8907. * @param array
  8908. */
  8909. Tools.arrayOrStringFeeder = function (array) {
  8910. return function (index) {
  8911. if (index >= array.length) {
  8912. return null;
  8913. }
  8914. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  8915. if (val && val.getHashCode) {
  8916. val = val.getHashCode();
  8917. }
  8918. if (typeof val === "string") {
  8919. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  8920. }
  8921. return val;
  8922. };
  8923. };
  8924. /**
  8925. * Compute the hashCode of a stream of number
  8926. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  8927. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  8928. * @return the hash code computed
  8929. */
  8930. Tools.hashCodeFromStream = function (feeder) {
  8931. // Based from here: http://stackoverflow.com/a/7616484/802124
  8932. var hash = 0;
  8933. var index = 0;
  8934. var chr = feeder(index++);
  8935. while (chr != null) {
  8936. hash = ((hash << 5) - hash) + chr;
  8937. hash |= 0; // Convert to 32bit integer
  8938. chr = feeder(index++);
  8939. }
  8940. return hash;
  8941. };
  8942. /**
  8943. * Returns a promise that resolves after the given amount of time.
  8944. * @param delay Number of milliseconds to delay
  8945. * @returns Promise that resolves after the given amount of time
  8946. */
  8947. Tools.DelayAsync = function (delay) {
  8948. return new Promise(function (resolve) {
  8949. setTimeout(function () {
  8950. resolve();
  8951. }, delay);
  8952. });
  8953. };
  8954. Tools.BaseUrl = "";
  8955. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  8956. /**
  8957. * Default behaviour for cors in the application.
  8958. * It can be a string if the expected behavior is identical in the entire app.
  8959. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  8960. */
  8961. Tools.CorsBehavior = "anonymous";
  8962. Tools.UseFallbackTexture = true;
  8963. /**
  8964. * Use this object to register external classes like custom textures or material
  8965. * to allow the laoders to instantiate them
  8966. */
  8967. Tools.RegisteredExternalClasses = {};
  8968. // Used in case of a texture loading problem
  8969. 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";
  8970. Tools.PreprocessUrl = function (url) {
  8971. return url;
  8972. };
  8973. // Logs
  8974. Tools._NoneLogLevel = 0;
  8975. Tools._MessageLogLevel = 1;
  8976. Tools._WarningLogLevel = 2;
  8977. Tools._ErrorLogLevel = 4;
  8978. Tools._LogCache = "";
  8979. Tools.errorsCount = 0;
  8980. Tools.Log = Tools._LogEnabled;
  8981. Tools.Warn = Tools._WarnEnabled;
  8982. Tools.Error = Tools._ErrorEnabled;
  8983. // Performances
  8984. Tools._PerformanceNoneLogLevel = 0;
  8985. Tools._PerformanceUserMarkLogLevel = 1;
  8986. Tools._PerformanceConsoleLogLevel = 2;
  8987. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  8988. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  8989. return Tools;
  8990. }());
  8991. BABYLON.Tools = Tools;
  8992. /**
  8993. * This class is used to track a performance counter which is number based.
  8994. * The user has access to many properties which give statistics of different nature
  8995. *
  8996. * The implementer can track two kinds of Performance Counter: time and count
  8997. * 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.
  8998. * 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.
  8999. */
  9000. var PerfCounter = /** @class */ (function () {
  9001. function PerfCounter() {
  9002. this._startMonitoringTime = 0;
  9003. this._min = 0;
  9004. this._max = 0;
  9005. this._average = 0;
  9006. this._lastSecAverage = 0;
  9007. this._current = 0;
  9008. this._totalValueCount = 0;
  9009. this._totalAccumulated = 0;
  9010. this._lastSecAccumulated = 0;
  9011. this._lastSecTime = 0;
  9012. this._lastSecValueCount = 0;
  9013. }
  9014. Object.defineProperty(PerfCounter.prototype, "min", {
  9015. /**
  9016. * Returns the smallest value ever
  9017. */
  9018. get: function () {
  9019. return this._min;
  9020. },
  9021. enumerable: true,
  9022. configurable: true
  9023. });
  9024. Object.defineProperty(PerfCounter.prototype, "max", {
  9025. /**
  9026. * Returns the biggest value ever
  9027. */
  9028. get: function () {
  9029. return this._max;
  9030. },
  9031. enumerable: true,
  9032. configurable: true
  9033. });
  9034. Object.defineProperty(PerfCounter.prototype, "average", {
  9035. /**
  9036. * Returns the average value since the performance counter is running
  9037. */
  9038. get: function () {
  9039. return this._average;
  9040. },
  9041. enumerable: true,
  9042. configurable: true
  9043. });
  9044. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  9045. /**
  9046. * Returns the average value of the last second the counter was monitored
  9047. */
  9048. get: function () {
  9049. return this._lastSecAverage;
  9050. },
  9051. enumerable: true,
  9052. configurable: true
  9053. });
  9054. Object.defineProperty(PerfCounter.prototype, "current", {
  9055. /**
  9056. * Returns the current value
  9057. */
  9058. get: function () {
  9059. return this._current;
  9060. },
  9061. enumerable: true,
  9062. configurable: true
  9063. });
  9064. Object.defineProperty(PerfCounter.prototype, "total", {
  9065. get: function () {
  9066. return this._totalAccumulated;
  9067. },
  9068. enumerable: true,
  9069. configurable: true
  9070. });
  9071. Object.defineProperty(PerfCounter.prototype, "count", {
  9072. get: function () {
  9073. return this._totalValueCount;
  9074. },
  9075. enumerable: true,
  9076. configurable: true
  9077. });
  9078. /**
  9079. * Call this method to start monitoring a new frame.
  9080. * 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.
  9081. */
  9082. PerfCounter.prototype.fetchNewFrame = function () {
  9083. this._totalValueCount++;
  9084. this._current = 0;
  9085. this._lastSecValueCount++;
  9086. };
  9087. /**
  9088. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  9089. * @param newCount the count value to add to the monitored count
  9090. * @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.
  9091. */
  9092. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  9093. if (!PerfCounter.Enabled) {
  9094. return;
  9095. }
  9096. this._current += newCount;
  9097. if (fetchResult) {
  9098. this._fetchResult();
  9099. }
  9100. };
  9101. /**
  9102. * Start monitoring this performance counter
  9103. */
  9104. PerfCounter.prototype.beginMonitoring = function () {
  9105. if (!PerfCounter.Enabled) {
  9106. return;
  9107. }
  9108. this._startMonitoringTime = Tools.Now;
  9109. };
  9110. /**
  9111. * Compute the time lapsed since the previous beginMonitoring() call.
  9112. * @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
  9113. */
  9114. PerfCounter.prototype.endMonitoring = function (newFrame) {
  9115. if (newFrame === void 0) { newFrame = true; }
  9116. if (!PerfCounter.Enabled) {
  9117. return;
  9118. }
  9119. if (newFrame) {
  9120. this.fetchNewFrame();
  9121. }
  9122. var currentTime = Tools.Now;
  9123. this._current = currentTime - this._startMonitoringTime;
  9124. if (newFrame) {
  9125. this._fetchResult();
  9126. }
  9127. };
  9128. PerfCounter.prototype._fetchResult = function () {
  9129. this._totalAccumulated += this._current;
  9130. this._lastSecAccumulated += this._current;
  9131. // Min/Max update
  9132. this._min = Math.min(this._min, this._current);
  9133. this._max = Math.max(this._max, this._current);
  9134. this._average = this._totalAccumulated / this._totalValueCount;
  9135. // Reset last sec?
  9136. var now = Tools.Now;
  9137. if ((now - this._lastSecTime) > 1000) {
  9138. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  9139. this._lastSecTime = now;
  9140. this._lastSecAccumulated = 0;
  9141. this._lastSecValueCount = 0;
  9142. }
  9143. };
  9144. PerfCounter.Enabled = true;
  9145. return PerfCounter;
  9146. }());
  9147. BABYLON.PerfCounter = PerfCounter;
  9148. /**
  9149. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  9150. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  9151. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  9152. * @param name The name of the class, case should be preserved
  9153. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  9154. */
  9155. function className(name, module) {
  9156. return function (target) {
  9157. target["__bjsclassName__"] = name;
  9158. target["__bjsmoduleName__"] = (module != null) ? module : null;
  9159. };
  9160. }
  9161. BABYLON.className = className;
  9162. /**
  9163. * An implementation of a loop for asynchronous functions.
  9164. */
  9165. var AsyncLoop = /** @class */ (function () {
  9166. /**
  9167. * Constroctor.
  9168. * @param iterations the number of iterations.
  9169. * @param _fn the function to run each iteration
  9170. * @param _successCallback the callback that will be called upon succesful execution
  9171. * @param offset starting offset.
  9172. */
  9173. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  9174. if (offset === void 0) { offset = 0; }
  9175. this.iterations = iterations;
  9176. this._fn = _fn;
  9177. this._successCallback = _successCallback;
  9178. this.index = offset - 1;
  9179. this._done = false;
  9180. }
  9181. /**
  9182. * Execute the next iteration. Must be called after the last iteration was finished.
  9183. */
  9184. AsyncLoop.prototype.executeNext = function () {
  9185. if (!this._done) {
  9186. if (this.index + 1 < this.iterations) {
  9187. ++this.index;
  9188. this._fn(this);
  9189. }
  9190. else {
  9191. this.breakLoop();
  9192. }
  9193. }
  9194. };
  9195. /**
  9196. * Break the loop and run the success callback.
  9197. */
  9198. AsyncLoop.prototype.breakLoop = function () {
  9199. this._done = true;
  9200. this._successCallback();
  9201. };
  9202. /**
  9203. * Helper function
  9204. */
  9205. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  9206. if (offset === void 0) { offset = 0; }
  9207. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  9208. loop.executeNext();
  9209. return loop;
  9210. };
  9211. /**
  9212. * A for-loop that will run a given number of iterations synchronous and the rest async.
  9213. * @param iterations total number of iterations
  9214. * @param syncedIterations number of synchronous iterations in each async iteration.
  9215. * @param fn the function to call each iteration.
  9216. * @param callback a success call back that will be called when iterating stops.
  9217. * @param breakFunction a break condition (optional)
  9218. * @param timeout timeout settings for the setTimeout function. default - 0.
  9219. * @constructor
  9220. */
  9221. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  9222. if (timeout === void 0) { timeout = 0; }
  9223. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  9224. if (breakFunction && breakFunction())
  9225. loop.breakLoop();
  9226. else {
  9227. setTimeout(function () {
  9228. for (var i = 0; i < syncedIterations; ++i) {
  9229. var iteration = (loop.index * syncedIterations) + i;
  9230. if (iteration >= iterations)
  9231. break;
  9232. fn(iteration);
  9233. if (breakFunction && breakFunction()) {
  9234. loop.breakLoop();
  9235. break;
  9236. }
  9237. }
  9238. loop.executeNext();
  9239. }, timeout);
  9240. }
  9241. }, callback);
  9242. };
  9243. return AsyncLoop;
  9244. }());
  9245. BABYLON.AsyncLoop = AsyncLoop;
  9246. })(BABYLON || (BABYLON = {}));
  9247. //# sourceMappingURL=babylon.tools.js.map
  9248. var BABYLON;
  9249. (function (BABYLON) {
  9250. var PromiseStates;
  9251. (function (PromiseStates) {
  9252. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  9253. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  9254. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  9255. })(PromiseStates || (PromiseStates = {}));
  9256. var FulFillmentAgregator = /** @class */ (function () {
  9257. function FulFillmentAgregator() {
  9258. this.count = 0;
  9259. this.target = 0;
  9260. this.results = [];
  9261. }
  9262. return FulFillmentAgregator;
  9263. }());
  9264. var InternalPromise = /** @class */ (function () {
  9265. function InternalPromise(resolver) {
  9266. var _this = this;
  9267. this._state = PromiseStates.Pending;
  9268. this._children = new Array();
  9269. this._rejectWasConsumed = false;
  9270. if (!resolver) {
  9271. return;
  9272. }
  9273. try {
  9274. resolver(function (value) {
  9275. _this._resolve(value);
  9276. }, function (reason) {
  9277. _this._reject(reason);
  9278. });
  9279. }
  9280. catch (e) {
  9281. this._reject(e);
  9282. }
  9283. }
  9284. InternalPromise.prototype.catch = function (onRejected) {
  9285. return this.then(undefined, onRejected);
  9286. };
  9287. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  9288. var _this = this;
  9289. var newPromise = new InternalPromise();
  9290. newPromise._onFulfilled = onFulfilled;
  9291. newPromise._onRejected = onRejected;
  9292. // Composition
  9293. this._children.push(newPromise);
  9294. if (this._state !== PromiseStates.Pending) {
  9295. BABYLON.Tools.SetImmediate(function () {
  9296. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  9297. var returnedValue = newPromise._resolve(_this._result);
  9298. if (returnedValue !== undefined && returnedValue !== null) {
  9299. if (returnedValue._state !== undefined) {
  9300. var returnedPromise = returnedValue;
  9301. newPromise._children.push(returnedPromise);
  9302. newPromise = returnedPromise;
  9303. }
  9304. else {
  9305. newPromise._result = returnedValue;
  9306. }
  9307. }
  9308. }
  9309. else {
  9310. newPromise._reject(_this._reason);
  9311. }
  9312. });
  9313. }
  9314. return newPromise;
  9315. };
  9316. InternalPromise.prototype._moveChildren = function (children) {
  9317. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  9318. if (this._state === PromiseStates.Fulfilled) {
  9319. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  9320. var child = _b[_i];
  9321. child._resolve(this._result);
  9322. }
  9323. }
  9324. else if (this._state === PromiseStates.Rejected) {
  9325. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  9326. var child = _d[_c];
  9327. child._reject(this._reason);
  9328. }
  9329. }
  9330. var _a;
  9331. };
  9332. InternalPromise.prototype._resolve = function (value) {
  9333. try {
  9334. this._state = PromiseStates.Fulfilled;
  9335. this._result = value;
  9336. var returnedValue = null;
  9337. if (this._onFulfilled) {
  9338. returnedValue = this._onFulfilled(value);
  9339. }
  9340. if (returnedValue !== undefined && returnedValue !== null) {
  9341. if (returnedValue._state !== undefined) {
  9342. // Transmit children
  9343. var returnedPromise = returnedValue;
  9344. returnedPromise._moveChildren(this._children);
  9345. }
  9346. else {
  9347. value = returnedValue;
  9348. }
  9349. }
  9350. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  9351. var child = _a[_i];
  9352. child._resolve(value);
  9353. }
  9354. this._children.length = 0;
  9355. delete this._onFulfilled;
  9356. delete this._onRejected;
  9357. return returnedValue;
  9358. }
  9359. catch (e) {
  9360. this._reject(e, true);
  9361. }
  9362. return null;
  9363. };
  9364. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  9365. if (onLocalThrow === void 0) { onLocalThrow = false; }
  9366. this._state = PromiseStates.Rejected;
  9367. this._reason = reason;
  9368. if (this._onRejected && !onLocalThrow) {
  9369. try {
  9370. this._onRejected(reason);
  9371. this._rejectWasConsumed = true;
  9372. }
  9373. catch (e) {
  9374. reason = e;
  9375. }
  9376. }
  9377. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  9378. var child = _a[_i];
  9379. if (this._rejectWasConsumed) {
  9380. child._resolve(null);
  9381. }
  9382. else {
  9383. child._reject(reason);
  9384. }
  9385. }
  9386. this._children.length = 0;
  9387. delete this._onFulfilled;
  9388. delete this._onRejected;
  9389. };
  9390. InternalPromise.resolve = function (value) {
  9391. var newPromise = new InternalPromise();
  9392. newPromise._resolve(value);
  9393. return newPromise;
  9394. };
  9395. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  9396. promise.then(function (value) {
  9397. agregator.results[index] = value;
  9398. agregator.count++;
  9399. if (agregator.count === agregator.target) {
  9400. agregator.rootPromise._resolve(agregator.results);
  9401. }
  9402. return null;
  9403. }, function (reason) {
  9404. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  9405. agregator.rootPromise._reject(reason);
  9406. }
  9407. });
  9408. };
  9409. InternalPromise.all = function (promises) {
  9410. var newPromise = new InternalPromise();
  9411. var agregator = new FulFillmentAgregator();
  9412. agregator.target = promises.length;
  9413. agregator.rootPromise = newPromise;
  9414. if (promises.length) {
  9415. for (var index = 0; index < promises.length; index++) {
  9416. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  9417. }
  9418. }
  9419. else {
  9420. newPromise._resolve([]);
  9421. }
  9422. return newPromise;
  9423. };
  9424. return InternalPromise;
  9425. }());
  9426. /**
  9427. * Helper class that provides a small promise polyfill
  9428. */
  9429. var PromisePolyfill = /** @class */ (function () {
  9430. function PromisePolyfill() {
  9431. }
  9432. /**
  9433. * Static function used to check if the polyfill is required
  9434. * If this is the case then the function will inject the polyfill to window.Promise
  9435. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  9436. */
  9437. PromisePolyfill.Apply = function (force) {
  9438. if (force === void 0) { force = false; }
  9439. if (force || typeof Promise === 'undefined') {
  9440. var root = window;
  9441. root.Promise = InternalPromise;
  9442. }
  9443. };
  9444. return PromisePolyfill;
  9445. }());
  9446. BABYLON.PromisePolyfill = PromisePolyfill;
  9447. })(BABYLON || (BABYLON = {}));
  9448. //# sourceMappingURL=babylon.promise.js.map
  9449. var BABYLON;
  9450. (function (BABYLON) {
  9451. var _AlphaState = /** @class */ (function () {
  9452. /**
  9453. * Initializes the state.
  9454. */
  9455. function _AlphaState() {
  9456. this._isAlphaBlendDirty = false;
  9457. this._isBlendFunctionParametersDirty = false;
  9458. this._isBlendEquationParametersDirty = false;
  9459. this._isBlendConstantsDirty = false;
  9460. this._alphaBlend = false;
  9461. this._blendFunctionParameters = new Array(4);
  9462. this._blendEquationParameters = new Array(2);
  9463. this._blendConstants = new Array(4);
  9464. this.reset();
  9465. }
  9466. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  9467. get: function () {
  9468. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  9469. },
  9470. enumerable: true,
  9471. configurable: true
  9472. });
  9473. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  9474. get: function () {
  9475. return this._alphaBlend;
  9476. },
  9477. set: function (value) {
  9478. if (this._alphaBlend === value) {
  9479. return;
  9480. }
  9481. this._alphaBlend = value;
  9482. this._isAlphaBlendDirty = true;
  9483. },
  9484. enumerable: true,
  9485. configurable: true
  9486. });
  9487. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  9488. if (this._blendConstants[0] === r &&
  9489. this._blendConstants[1] === g &&
  9490. this._blendConstants[2] === b &&
  9491. this._blendConstants[3] === a) {
  9492. return;
  9493. }
  9494. this._blendConstants[0] = r;
  9495. this._blendConstants[1] = g;
  9496. this._blendConstants[2] = b;
  9497. this._blendConstants[3] = a;
  9498. this._isBlendConstantsDirty = true;
  9499. };
  9500. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  9501. if (this._blendFunctionParameters[0] === value0 &&
  9502. this._blendFunctionParameters[1] === value1 &&
  9503. this._blendFunctionParameters[2] === value2 &&
  9504. this._blendFunctionParameters[3] === value3) {
  9505. return;
  9506. }
  9507. this._blendFunctionParameters[0] = value0;
  9508. this._blendFunctionParameters[1] = value1;
  9509. this._blendFunctionParameters[2] = value2;
  9510. this._blendFunctionParameters[3] = value3;
  9511. this._isBlendFunctionParametersDirty = true;
  9512. };
  9513. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  9514. if (this._blendEquationParameters[0] === rgb &&
  9515. this._blendEquationParameters[1] === alpha) {
  9516. return;
  9517. }
  9518. this._blendEquationParameters[0] = rgb;
  9519. this._blendEquationParameters[1] = alpha;
  9520. this._isBlendEquationParametersDirty = true;
  9521. };
  9522. _AlphaState.prototype.reset = function () {
  9523. this._alphaBlend = false;
  9524. this._blendFunctionParameters[0] = null;
  9525. this._blendFunctionParameters[1] = null;
  9526. this._blendFunctionParameters[2] = null;
  9527. this._blendFunctionParameters[3] = null;
  9528. this._blendEquationParameters[0] = null;
  9529. this._blendEquationParameters[1] = null;
  9530. this._blendConstants[0] = null;
  9531. this._blendConstants[1] = null;
  9532. this._blendConstants[2] = null;
  9533. this._blendConstants[3] = null;
  9534. this._isAlphaBlendDirty = true;
  9535. this._isBlendFunctionParametersDirty = false;
  9536. this._isBlendEquationParametersDirty = false;
  9537. this._isBlendConstantsDirty = false;
  9538. };
  9539. _AlphaState.prototype.apply = function (gl) {
  9540. if (!this.isDirty) {
  9541. return;
  9542. }
  9543. // Alpha blend
  9544. if (this._isAlphaBlendDirty) {
  9545. if (this._alphaBlend) {
  9546. gl.enable(gl.BLEND);
  9547. }
  9548. else {
  9549. gl.disable(gl.BLEND);
  9550. }
  9551. this._isAlphaBlendDirty = false;
  9552. }
  9553. // Alpha function
  9554. if (this._isBlendFunctionParametersDirty) {
  9555. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  9556. this._isBlendFunctionParametersDirty = false;
  9557. }
  9558. // Alpha equation
  9559. if (this._isBlendEquationParametersDirty) {
  9560. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  9561. this._isBlendEquationParametersDirty = false;
  9562. }
  9563. // Constants
  9564. if (this._isBlendConstantsDirty) {
  9565. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  9566. this._isBlendConstantsDirty = false;
  9567. }
  9568. };
  9569. return _AlphaState;
  9570. }());
  9571. BABYLON._AlphaState = _AlphaState;
  9572. })(BABYLON || (BABYLON = {}));
  9573. //# sourceMappingURL=babylon.alphaCullingState.js.map
  9574. var BABYLON;
  9575. (function (BABYLON) {
  9576. var _DepthCullingState = /** @class */ (function () {
  9577. /**
  9578. * Initializes the state.
  9579. */
  9580. function _DepthCullingState() {
  9581. this._isDepthTestDirty = false;
  9582. this._isDepthMaskDirty = false;
  9583. this._isDepthFuncDirty = false;
  9584. this._isCullFaceDirty = false;
  9585. this._isCullDirty = false;
  9586. this._isZOffsetDirty = false;
  9587. this._isFrontFaceDirty = false;
  9588. this.reset();
  9589. }
  9590. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  9591. get: function () {
  9592. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  9593. },
  9594. enumerable: true,
  9595. configurable: true
  9596. });
  9597. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  9598. get: function () {
  9599. return this._zOffset;
  9600. },
  9601. set: function (value) {
  9602. if (this._zOffset === value) {
  9603. return;
  9604. }
  9605. this._zOffset = value;
  9606. this._isZOffsetDirty = true;
  9607. },
  9608. enumerable: true,
  9609. configurable: true
  9610. });
  9611. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  9612. get: function () {
  9613. return this._cullFace;
  9614. },
  9615. set: function (value) {
  9616. if (this._cullFace === value) {
  9617. return;
  9618. }
  9619. this._cullFace = value;
  9620. this._isCullFaceDirty = true;
  9621. },
  9622. enumerable: true,
  9623. configurable: true
  9624. });
  9625. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  9626. get: function () {
  9627. return this._cull;
  9628. },
  9629. set: function (value) {
  9630. if (this._cull === value) {
  9631. return;
  9632. }
  9633. this._cull = value;
  9634. this._isCullDirty = true;
  9635. },
  9636. enumerable: true,
  9637. configurable: true
  9638. });
  9639. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  9640. get: function () {
  9641. return this._depthFunc;
  9642. },
  9643. set: function (value) {
  9644. if (this._depthFunc === value) {
  9645. return;
  9646. }
  9647. this._depthFunc = value;
  9648. this._isDepthFuncDirty = true;
  9649. },
  9650. enumerable: true,
  9651. configurable: true
  9652. });
  9653. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  9654. get: function () {
  9655. return this._depthMask;
  9656. },
  9657. set: function (value) {
  9658. if (this._depthMask === value) {
  9659. return;
  9660. }
  9661. this._depthMask = value;
  9662. this._isDepthMaskDirty = true;
  9663. },
  9664. enumerable: true,
  9665. configurable: true
  9666. });
  9667. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  9668. get: function () {
  9669. return this._depthTest;
  9670. },
  9671. set: function (value) {
  9672. if (this._depthTest === value) {
  9673. return;
  9674. }
  9675. this._depthTest = value;
  9676. this._isDepthTestDirty = true;
  9677. },
  9678. enumerable: true,
  9679. configurable: true
  9680. });
  9681. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  9682. get: function () {
  9683. return this._frontFace;
  9684. },
  9685. set: function (value) {
  9686. if (this._frontFace === value) {
  9687. return;
  9688. }
  9689. this._frontFace = value;
  9690. this._isFrontFaceDirty = true;
  9691. },
  9692. enumerable: true,
  9693. configurable: true
  9694. });
  9695. _DepthCullingState.prototype.reset = function () {
  9696. this._depthMask = true;
  9697. this._depthTest = true;
  9698. this._depthFunc = null;
  9699. this._cullFace = null;
  9700. this._cull = null;
  9701. this._zOffset = 0;
  9702. this._frontFace = null;
  9703. this._isDepthTestDirty = true;
  9704. this._isDepthMaskDirty = true;
  9705. this._isDepthFuncDirty = false;
  9706. this._isCullFaceDirty = false;
  9707. this._isCullDirty = false;
  9708. this._isZOffsetDirty = false;
  9709. this._isFrontFaceDirty = false;
  9710. };
  9711. _DepthCullingState.prototype.apply = function (gl) {
  9712. if (!this.isDirty) {
  9713. return;
  9714. }
  9715. // Cull
  9716. if (this._isCullDirty) {
  9717. if (this.cull) {
  9718. gl.enable(gl.CULL_FACE);
  9719. }
  9720. else {
  9721. gl.disable(gl.CULL_FACE);
  9722. }
  9723. this._isCullDirty = false;
  9724. }
  9725. // Cull face
  9726. if (this._isCullFaceDirty) {
  9727. gl.cullFace(this.cullFace);
  9728. this._isCullFaceDirty = false;
  9729. }
  9730. // Depth mask
  9731. if (this._isDepthMaskDirty) {
  9732. gl.depthMask(this.depthMask);
  9733. this._isDepthMaskDirty = false;
  9734. }
  9735. // Depth test
  9736. if (this._isDepthTestDirty) {
  9737. if (this.depthTest) {
  9738. gl.enable(gl.DEPTH_TEST);
  9739. }
  9740. else {
  9741. gl.disable(gl.DEPTH_TEST);
  9742. }
  9743. this._isDepthTestDirty = false;
  9744. }
  9745. // Depth func
  9746. if (this._isDepthFuncDirty) {
  9747. gl.depthFunc(this.depthFunc);
  9748. this._isDepthFuncDirty = false;
  9749. }
  9750. // zOffset
  9751. if (this._isZOffsetDirty) {
  9752. if (this.zOffset) {
  9753. gl.enable(gl.POLYGON_OFFSET_FILL);
  9754. gl.polygonOffset(this.zOffset, 0);
  9755. }
  9756. else {
  9757. gl.disable(gl.POLYGON_OFFSET_FILL);
  9758. }
  9759. this._isZOffsetDirty = false;
  9760. }
  9761. // Front face
  9762. if (this._isFrontFaceDirty) {
  9763. gl.frontFace(this.frontFace);
  9764. this._isFrontFaceDirty = false;
  9765. }
  9766. };
  9767. return _DepthCullingState;
  9768. }());
  9769. BABYLON._DepthCullingState = _DepthCullingState;
  9770. })(BABYLON || (BABYLON = {}));
  9771. //# sourceMappingURL=babylon.depthCullingState.js.map
  9772. var BABYLON;
  9773. (function (BABYLON) {
  9774. var _StencilState = /** @class */ (function () {
  9775. function _StencilState() {
  9776. this._isStencilTestDirty = false;
  9777. this._isStencilMaskDirty = false;
  9778. this._isStencilFuncDirty = false;
  9779. this._isStencilOpDirty = false;
  9780. this.reset();
  9781. }
  9782. Object.defineProperty(_StencilState.prototype, "isDirty", {
  9783. get: function () {
  9784. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  9785. },
  9786. enumerable: true,
  9787. configurable: true
  9788. });
  9789. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  9790. get: function () {
  9791. return this._stencilFunc;
  9792. },
  9793. set: function (value) {
  9794. if (this._stencilFunc === value) {
  9795. return;
  9796. }
  9797. this._stencilFunc = value;
  9798. this._isStencilFuncDirty = true;
  9799. },
  9800. enumerable: true,
  9801. configurable: true
  9802. });
  9803. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  9804. get: function () {
  9805. return this._stencilFuncRef;
  9806. },
  9807. set: function (value) {
  9808. if (this._stencilFuncRef === value) {
  9809. return;
  9810. }
  9811. this._stencilFuncRef = value;
  9812. this._isStencilFuncDirty = true;
  9813. },
  9814. enumerable: true,
  9815. configurable: true
  9816. });
  9817. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  9818. get: function () {
  9819. return this._stencilFuncMask;
  9820. },
  9821. set: function (value) {
  9822. if (this._stencilFuncMask === value) {
  9823. return;
  9824. }
  9825. this._stencilFuncMask = value;
  9826. this._isStencilFuncDirty = true;
  9827. },
  9828. enumerable: true,
  9829. configurable: true
  9830. });
  9831. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  9832. get: function () {
  9833. return this._stencilOpStencilFail;
  9834. },
  9835. set: function (value) {
  9836. if (this._stencilOpStencilFail === value) {
  9837. return;
  9838. }
  9839. this._stencilOpStencilFail = value;
  9840. this._isStencilOpDirty = true;
  9841. },
  9842. enumerable: true,
  9843. configurable: true
  9844. });
  9845. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  9846. get: function () {
  9847. return this._stencilOpDepthFail;
  9848. },
  9849. set: function (value) {
  9850. if (this._stencilOpDepthFail === value) {
  9851. return;
  9852. }
  9853. this._stencilOpDepthFail = value;
  9854. this._isStencilOpDirty = true;
  9855. },
  9856. enumerable: true,
  9857. configurable: true
  9858. });
  9859. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  9860. get: function () {
  9861. return this._stencilOpStencilDepthPass;
  9862. },
  9863. set: function (value) {
  9864. if (this._stencilOpStencilDepthPass === value) {
  9865. return;
  9866. }
  9867. this._stencilOpStencilDepthPass = value;
  9868. this._isStencilOpDirty = true;
  9869. },
  9870. enumerable: true,
  9871. configurable: true
  9872. });
  9873. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  9874. get: function () {
  9875. return this._stencilMask;
  9876. },
  9877. set: function (value) {
  9878. if (this._stencilMask === value) {
  9879. return;
  9880. }
  9881. this._stencilMask = value;
  9882. this._isStencilMaskDirty = true;
  9883. },
  9884. enumerable: true,
  9885. configurable: true
  9886. });
  9887. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  9888. get: function () {
  9889. return this._stencilTest;
  9890. },
  9891. set: function (value) {
  9892. if (this._stencilTest === value) {
  9893. return;
  9894. }
  9895. this._stencilTest = value;
  9896. this._isStencilTestDirty = true;
  9897. },
  9898. enumerable: true,
  9899. configurable: true
  9900. });
  9901. _StencilState.prototype.reset = function () {
  9902. this._stencilTest = false;
  9903. this._stencilMask = 0xFF;
  9904. this._stencilFunc = BABYLON.Engine.ALWAYS;
  9905. this._stencilFuncRef = 1;
  9906. this._stencilFuncMask = 0xFF;
  9907. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  9908. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  9909. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  9910. this._isStencilTestDirty = true;
  9911. this._isStencilMaskDirty = true;
  9912. this._isStencilFuncDirty = true;
  9913. this._isStencilOpDirty = true;
  9914. };
  9915. _StencilState.prototype.apply = function (gl) {
  9916. if (!this.isDirty) {
  9917. return;
  9918. }
  9919. // Stencil test
  9920. if (this._isStencilTestDirty) {
  9921. if (this.stencilTest) {
  9922. gl.enable(gl.STENCIL_TEST);
  9923. }
  9924. else {
  9925. gl.disable(gl.STENCIL_TEST);
  9926. }
  9927. this._isStencilTestDirty = false;
  9928. }
  9929. // Stencil mask
  9930. if (this._isStencilMaskDirty) {
  9931. gl.stencilMask(this.stencilMask);
  9932. this._isStencilMaskDirty = false;
  9933. }
  9934. // Stencil func
  9935. if (this._isStencilFuncDirty) {
  9936. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  9937. this._isStencilFuncDirty = false;
  9938. }
  9939. // Stencil op
  9940. if (this._isStencilOpDirty) {
  9941. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  9942. this._isStencilOpDirty = false;
  9943. }
  9944. };
  9945. return _StencilState;
  9946. }());
  9947. BABYLON._StencilState = _StencilState;
  9948. })(BABYLON || (BABYLON = {}));
  9949. //# sourceMappingURL=babylon.stencilState.js.map
  9950. var BABYLON;
  9951. (function (BABYLON) {
  9952. var compileShader = function (gl, source, type, defines, shaderVersion) {
  9953. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  9954. };
  9955. var compileRawShader = function (gl, source, type) {
  9956. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  9957. gl.shaderSource(shader, source);
  9958. gl.compileShader(shader);
  9959. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  9960. var log = gl.getShaderInfoLog(shader);
  9961. if (log) {
  9962. throw new Error(log);
  9963. }
  9964. }
  9965. if (!shader) {
  9966. throw new Error("Something went wrong while compile the shader.");
  9967. }
  9968. return shader;
  9969. };
  9970. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  9971. var magFilter = gl.NEAREST;
  9972. var minFilter = gl.NEAREST;
  9973. switch (samplingMode) {
  9974. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  9975. magFilter = gl.LINEAR;
  9976. if (generateMipMaps) {
  9977. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  9978. }
  9979. else {
  9980. minFilter = gl.LINEAR;
  9981. }
  9982. break;
  9983. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  9984. magFilter = gl.LINEAR;
  9985. if (generateMipMaps) {
  9986. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  9987. }
  9988. else {
  9989. minFilter = gl.LINEAR;
  9990. }
  9991. break;
  9992. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  9993. magFilter = gl.NEAREST;
  9994. if (generateMipMaps) {
  9995. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  9996. }
  9997. else {
  9998. minFilter = gl.NEAREST;
  9999. }
  10000. break;
  10001. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  10002. magFilter = gl.NEAREST;
  10003. if (generateMipMaps) {
  10004. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  10005. }
  10006. else {
  10007. minFilter = gl.NEAREST;
  10008. }
  10009. break;
  10010. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  10011. magFilter = gl.NEAREST;
  10012. if (generateMipMaps) {
  10013. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  10014. }
  10015. else {
  10016. minFilter = gl.LINEAR;
  10017. }
  10018. break;
  10019. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  10020. magFilter = gl.NEAREST;
  10021. if (generateMipMaps) {
  10022. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  10023. }
  10024. else {
  10025. minFilter = gl.LINEAR;
  10026. }
  10027. break;
  10028. case BABYLON.Texture.NEAREST_LINEAR:
  10029. magFilter = gl.NEAREST;
  10030. minFilter = gl.LINEAR;
  10031. break;
  10032. case BABYLON.Texture.NEAREST_NEAREST:
  10033. magFilter = gl.NEAREST;
  10034. minFilter = gl.NEAREST;
  10035. break;
  10036. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  10037. magFilter = gl.LINEAR;
  10038. if (generateMipMaps) {
  10039. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  10040. }
  10041. else {
  10042. minFilter = gl.NEAREST;
  10043. }
  10044. break;
  10045. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  10046. magFilter = gl.LINEAR;
  10047. if (generateMipMaps) {
  10048. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  10049. }
  10050. else {
  10051. minFilter = gl.NEAREST;
  10052. }
  10053. break;
  10054. case BABYLON.Texture.LINEAR_LINEAR:
  10055. magFilter = gl.LINEAR;
  10056. minFilter = gl.LINEAR;
  10057. break;
  10058. case BABYLON.Texture.LINEAR_NEAREST:
  10059. magFilter = gl.LINEAR;
  10060. minFilter = gl.NEAREST;
  10061. break;
  10062. }
  10063. return {
  10064. min: minFilter,
  10065. mag: magFilter
  10066. };
  10067. };
  10068. var partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  10069. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  10070. var img;
  10071. var onload = function () {
  10072. loadedImages[index] = img;
  10073. loadedImages._internalCount++;
  10074. if (scene) {
  10075. scene._removePendingData(img);
  10076. }
  10077. if (loadedImages._internalCount === 6) {
  10078. onfinish(loadedImages);
  10079. }
  10080. };
  10081. var onerror = function (message, exception) {
  10082. if (scene) {
  10083. scene._removePendingData(img);
  10084. }
  10085. if (onErrorCallBack) {
  10086. onErrorCallBack(message, exception);
  10087. }
  10088. };
  10089. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  10090. if (scene) {
  10091. scene._addPendingData(img);
  10092. }
  10093. };
  10094. var cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  10095. if (onError === void 0) { onError = null; }
  10096. var loadedImages = [];
  10097. loadedImages._internalCount = 0;
  10098. for (var index = 0; index < 6; index++) {
  10099. partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  10100. }
  10101. };
  10102. var BufferPointer = /** @class */ (function () {
  10103. function BufferPointer() {
  10104. }
  10105. return BufferPointer;
  10106. }());
  10107. var InstancingAttributeInfo = /** @class */ (function () {
  10108. function InstancingAttributeInfo() {
  10109. }
  10110. return InstancingAttributeInfo;
  10111. }());
  10112. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  10113. /**
  10114. * Define options used to create a render target texture
  10115. */
  10116. var RenderTargetCreationOptions = /** @class */ (function () {
  10117. function RenderTargetCreationOptions() {
  10118. }
  10119. return RenderTargetCreationOptions;
  10120. }());
  10121. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  10122. /**
  10123. * Regroup several parameters relative to the browser in use
  10124. */
  10125. var EngineCapabilities = /** @class */ (function () {
  10126. function EngineCapabilities() {
  10127. }
  10128. return EngineCapabilities;
  10129. }());
  10130. BABYLON.EngineCapabilities = EngineCapabilities;
  10131. /**
  10132. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  10133. */
  10134. var Engine = /** @class */ (function () {
  10135. /**
  10136. * @constructor
  10137. * @param canvasOrContext defines the canvas or WebGL context to use for rendering
  10138. * @param antialias defines enable antialiasing (default: false)
  10139. * @param options defines further options to be sent to the getContext() function
  10140. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  10141. */
  10142. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  10143. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  10144. var _this = this;
  10145. // Public members
  10146. this.forcePOTTextures = false;
  10147. this.isFullscreen = false;
  10148. this.isPointerLock = false;
  10149. this.cullBackFaces = true;
  10150. this.renderEvenInBackground = true;
  10151. this.preventCacheWipeBetweenFrames = false;
  10152. // To enable/disable IDB support and avoid XHR on .manifest
  10153. this.enableOfflineSupport = false;
  10154. this.scenes = new Array();
  10155. this.postProcesses = new Array();
  10156. // Observables
  10157. /**
  10158. * Observable event triggered each time the rendering canvas is resized
  10159. */
  10160. this.onResizeObservable = new BABYLON.Observable();
  10161. /**
  10162. * Observable event triggered each time the canvas loses focus
  10163. */
  10164. this.onCanvasBlurObservable = new BABYLON.Observable();
  10165. /**
  10166. * Observable event triggered each time the canvas gains focus
  10167. */
  10168. this.onCanvasFocusObservable = new BABYLON.Observable();
  10169. /**
  10170. * Observable event triggered each time the canvas receives pointerout event
  10171. */
  10172. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  10173. /**
  10174. * Observable event triggered before each texture is initialized
  10175. */
  10176. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  10177. //WebVR
  10178. this._vrDisplay = undefined;
  10179. this._vrSupported = false;
  10180. this._vrExclusivePointerMode = false;
  10181. // Uniform buffers list
  10182. this.disableUniformBuffers = false;
  10183. this._uniformBuffers = new Array();
  10184. // Observables
  10185. /**
  10186. * Observable raised when the engine begins a new frame
  10187. */
  10188. this.onBeginFrameObservable = new BABYLON.Observable();
  10189. /**
  10190. * Observable raised when the engine ends the current frame
  10191. */
  10192. this.onEndFrameObservable = new BABYLON.Observable();
  10193. /**
  10194. * Observable raised when the engine is about to compile a shader
  10195. */
  10196. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  10197. /**
  10198. * Observable raised when the engine has jsut compiled a shader
  10199. */
  10200. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  10201. this._windowIsBackground = false;
  10202. this._webGLVersion = 1.0;
  10203. this._badOS = false;
  10204. this._badDesktopOS = false;
  10205. /**
  10206. * Gets or sets a value indicating if we want to disable texture binding optmization.
  10207. * This could be required on some buggy drivers which wants to have textures bound in a progressive order
  10208. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is.
  10209. */
  10210. this.disableTextureBindingOptimization = false;
  10211. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  10212. this.onVRRequestPresentComplete = new BABYLON.Observable();
  10213. this.onVRRequestPresentStart = new BABYLON.Observable();
  10214. this._colorWrite = true;
  10215. this._drawCalls = new BABYLON.PerfCounter();
  10216. this._textureCollisions = new BABYLON.PerfCounter();
  10217. this._renderingQueueLaunched = false;
  10218. this._activeRenderLoops = new Array();
  10219. // Deterministic lockstepMaxSteps
  10220. this._deterministicLockstep = false;
  10221. this._lockstepMaxSteps = 4;
  10222. // Lost context
  10223. this.onContextLostObservable = new BABYLON.Observable();
  10224. this.onContextRestoredObservable = new BABYLON.Observable();
  10225. this._contextWasLost = false;
  10226. this._doNotHandleContextLost = false;
  10227. // FPS
  10228. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  10229. this._fps = 60;
  10230. this._deltaTime = 0;
  10231. /**
  10232. * Turn this value on if you want to pause FPS computation when in background
  10233. */
  10234. this.disablePerformanceMonitorInBackground = false;
  10235. // States
  10236. this._depthCullingState = new BABYLON._DepthCullingState();
  10237. this._stencilState = new BABYLON._StencilState();
  10238. this._alphaState = new BABYLON._AlphaState();
  10239. this._alphaMode = Engine.ALPHA_DISABLE;
  10240. // Cache
  10241. this._internalTexturesCache = new Array();
  10242. this._activeChannel = 0;
  10243. this._currentTextureChannel = -1;
  10244. this._boundTexturesCache = {};
  10245. this._compiledEffects = {};
  10246. this._vertexAttribArraysEnabled = [];
  10247. this._uintIndicesCurrentlySet = false;
  10248. this._currentBoundBuffer = new Array();
  10249. this._currentBufferPointers = new Array();
  10250. this._currentInstanceLocations = new Array();
  10251. this._currentInstanceBuffers = new Array();
  10252. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  10253. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  10254. this._vaoRecordInProgress = false;
  10255. this._mustWipeVertexAttributes = false;
  10256. this._nextFreeTextureSlots = new Array();
  10257. this._maxSimultaneousTextures = 0;
  10258. this._activeRequests = new Array();
  10259. // Hardware supported Compressed Textures
  10260. this._texturesSupported = new Array();
  10261. this._onVRFullScreenTriggered = function () {
  10262. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  10263. //get the old size before we change
  10264. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  10265. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  10266. //get the width and height, change the render size
  10267. var leftEye = _this._vrDisplay.getEyeParameters('left');
  10268. _this.setHardwareScalingLevel(1);
  10269. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  10270. }
  10271. else {
  10272. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  10273. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  10274. }
  10275. };
  10276. this._boundUniforms = {};
  10277. // Register promises
  10278. BABYLON.PromisePolyfill.Apply();
  10279. var canvas = null;
  10280. Engine.Instances.push(this);
  10281. if (!canvasOrContext) {
  10282. return;
  10283. }
  10284. options = options || {};
  10285. if (canvasOrContext.getContext) {
  10286. canvas = canvasOrContext;
  10287. this._renderingCanvas = canvas;
  10288. if (antialias != null) {
  10289. options.antialias = antialias;
  10290. }
  10291. if (options.deterministicLockstep === undefined) {
  10292. options.deterministicLockstep = false;
  10293. }
  10294. if (options.lockstepMaxSteps === undefined) {
  10295. options.lockstepMaxSteps = 4;
  10296. }
  10297. if (options.preserveDrawingBuffer === undefined) {
  10298. options.preserveDrawingBuffer = false;
  10299. }
  10300. if (options.audioEngine === undefined) {
  10301. options.audioEngine = true;
  10302. }
  10303. if (options.stencil === undefined) {
  10304. options.stencil = true;
  10305. }
  10306. this._deterministicLockstep = options.deterministicLockstep;
  10307. this._lockstepMaxSteps = options.lockstepMaxSteps;
  10308. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  10309. // Exceptions
  10310. if (navigator && navigator.userAgent) {
  10311. var ua = navigator.userAgent;
  10312. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  10313. var exception = _a[_i];
  10314. var key = exception.key;
  10315. var targets = exception.targets;
  10316. if (ua.indexOf(key) > -1) {
  10317. if (exception.capture && exception.captureConstraint) {
  10318. var capture = exception.capture;
  10319. var constraint = exception.captureConstraint;
  10320. var regex = new RegExp(capture);
  10321. var matches = regex.exec(ua);
  10322. if (matches && matches.length > 0) {
  10323. var capturedValue = parseInt(matches[matches.length - 1]);
  10324. if (capturedValue >= constraint) {
  10325. continue;
  10326. }
  10327. }
  10328. }
  10329. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  10330. var target = targets_1[_b];
  10331. switch (target) {
  10332. case "uniformBuffer":
  10333. this.disableUniformBuffers = true;
  10334. break;
  10335. case "textureBindingOptimization":
  10336. this.disableTextureBindingOptimization = true;
  10337. break;
  10338. }
  10339. }
  10340. break;
  10341. }
  10342. }
  10343. }
  10344. // GL
  10345. if (!options.disableWebGL2Support) {
  10346. try {
  10347. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  10348. if (this._gl) {
  10349. this._webGLVersion = 2.0;
  10350. }
  10351. }
  10352. catch (e) {
  10353. // Do nothing
  10354. }
  10355. }
  10356. if (!this._gl) {
  10357. if (!canvas) {
  10358. throw new Error("The provided canvas is null or undefined.");
  10359. }
  10360. try {
  10361. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  10362. }
  10363. catch (e) {
  10364. throw new Error("WebGL not supported");
  10365. }
  10366. }
  10367. if (!this._gl) {
  10368. throw new Error("WebGL not supported");
  10369. }
  10370. this._onCanvasFocus = function () {
  10371. _this.onCanvasFocusObservable.notifyObservers(_this);
  10372. };
  10373. this._onCanvasBlur = function () {
  10374. _this.onCanvasBlurObservable.notifyObservers(_this);
  10375. };
  10376. canvas.addEventListener("focus", this._onCanvasFocus);
  10377. canvas.addEventListener("blur", this._onCanvasBlur);
  10378. this._onBlur = function () {
  10379. if (_this.disablePerformanceMonitorInBackground) {
  10380. _this._performanceMonitor.disable();
  10381. }
  10382. _this._windowIsBackground = true;
  10383. };
  10384. this._onFocus = function () {
  10385. if (_this.disablePerformanceMonitorInBackground) {
  10386. _this._performanceMonitor.enable();
  10387. }
  10388. _this._windowIsBackground = false;
  10389. };
  10390. this._onCanvasPointerOut = function () {
  10391. _this.onCanvasPointerOutObservable.notifyObservers(_this);
  10392. };
  10393. window.addEventListener("blur", this._onBlur);
  10394. window.addEventListener("focus", this._onFocus);
  10395. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  10396. // Context lost
  10397. if (!this._doNotHandleContextLost) {
  10398. this._onContextLost = function (evt) {
  10399. evt.preventDefault();
  10400. _this._contextWasLost = true;
  10401. BABYLON.Tools.Warn("WebGL context lost.");
  10402. _this.onContextLostObservable.notifyObservers(_this);
  10403. };
  10404. this._onContextRestored = function (evt) {
  10405. // Adding a timeout to avoid race condition at browser level
  10406. setTimeout(function () {
  10407. // Rebuild gl context
  10408. _this._initGLContext();
  10409. // Rebuild effects
  10410. _this._rebuildEffects();
  10411. // Rebuild textures
  10412. _this._rebuildInternalTextures();
  10413. // Rebuild buffers
  10414. _this._rebuildBuffers();
  10415. // Cache
  10416. _this.wipeCaches(true);
  10417. BABYLON.Tools.Warn("WebGL context successfully restored.");
  10418. _this.onContextRestoredObservable.notifyObservers(_this);
  10419. _this._contextWasLost = false;
  10420. }, 0);
  10421. };
  10422. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  10423. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  10424. }
  10425. }
  10426. else {
  10427. this._gl = canvasOrContext;
  10428. this._renderingCanvas = this._gl.canvas;
  10429. if (this._gl.renderbufferStorageMultisample) {
  10430. this._webGLVersion = 2.0;
  10431. }
  10432. options.stencil = this._gl.getContextAttributes().stencil;
  10433. }
  10434. // Viewport
  10435. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  10436. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  10437. this.resize();
  10438. this._isStencilEnable = options.stencil ? true : false;
  10439. this._initGLContext();
  10440. if (canvas) {
  10441. // Fullscreen
  10442. this._onFullscreenChange = function () {
  10443. if (document.fullscreen !== undefined) {
  10444. _this.isFullscreen = document.fullscreen;
  10445. }
  10446. else if (document.mozFullScreen !== undefined) {
  10447. _this.isFullscreen = document.mozFullScreen;
  10448. }
  10449. else if (document.webkitIsFullScreen !== undefined) {
  10450. _this.isFullscreen = document.webkitIsFullScreen;
  10451. }
  10452. else if (document.msIsFullScreen !== undefined) {
  10453. _this.isFullscreen = document.msIsFullScreen;
  10454. }
  10455. // Pointer lock
  10456. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  10457. canvas.requestPointerLock = canvas.requestPointerLock ||
  10458. canvas.msRequestPointerLock ||
  10459. canvas.mozRequestPointerLock ||
  10460. canvas.webkitRequestPointerLock;
  10461. if (canvas.requestPointerLock) {
  10462. canvas.requestPointerLock();
  10463. }
  10464. }
  10465. };
  10466. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  10467. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  10468. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  10469. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  10470. // Pointer lock
  10471. this._onPointerLockChange = function () {
  10472. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  10473. document.webkitPointerLockElement === canvas ||
  10474. document.msPointerLockElement === canvas ||
  10475. document.pointerLockElement === canvas);
  10476. };
  10477. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  10478. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  10479. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  10480. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  10481. this._onVRDisplayPointerRestricted = function () {
  10482. if (canvas) {
  10483. canvas.requestPointerLock();
  10484. }
  10485. };
  10486. this._onVRDisplayPointerUnrestricted = function () {
  10487. document.exitPointerLock();
  10488. };
  10489. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  10490. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  10491. }
  10492. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  10493. Engine.audioEngine = new BABYLON.AudioEngine();
  10494. }
  10495. // Prepare buffer pointers
  10496. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  10497. this._currentBufferPointers[i] = new BufferPointer();
  10498. }
  10499. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  10500. // Load WebVR Devices
  10501. if (options.autoEnableWebVR) {
  10502. this.initWebVR();
  10503. }
  10504. // Detect if we are running on a faulty buggy OS.
  10505. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  10506. // Detect if we are running on a faulty buggy desktop OS.
  10507. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  10508. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  10509. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  10510. }
  10511. Object.defineProperty(Engine, "LastCreatedEngine", {
  10512. get: function () {
  10513. if (Engine.Instances.length === 0) {
  10514. return null;
  10515. }
  10516. return Engine.Instances[Engine.Instances.length - 1];
  10517. },
  10518. enumerable: true,
  10519. configurable: true
  10520. });
  10521. Object.defineProperty(Engine, "LastCreatedScene", {
  10522. get: function () {
  10523. var lastCreatedEngine = Engine.LastCreatedEngine;
  10524. if (!lastCreatedEngine) {
  10525. return null;
  10526. }
  10527. if (lastCreatedEngine.scenes.length === 0) {
  10528. return null;
  10529. }
  10530. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  10531. },
  10532. enumerable: true,
  10533. configurable: true
  10534. });
  10535. /**
  10536. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  10537. */
  10538. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  10539. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  10540. var engine = Engine.Instances[engineIndex];
  10541. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  10542. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  10543. }
  10544. }
  10545. };
  10546. Object.defineProperty(Engine, "NEVER", {
  10547. get: function () {
  10548. return Engine._NEVER;
  10549. },
  10550. enumerable: true,
  10551. configurable: true
  10552. });
  10553. Object.defineProperty(Engine, "ALWAYS", {
  10554. get: function () {
  10555. return Engine._ALWAYS;
  10556. },
  10557. enumerable: true,
  10558. configurable: true
  10559. });
  10560. Object.defineProperty(Engine, "LESS", {
  10561. get: function () {
  10562. return Engine._LESS;
  10563. },
  10564. enumerable: true,
  10565. configurable: true
  10566. });
  10567. Object.defineProperty(Engine, "EQUAL", {
  10568. get: function () {
  10569. return Engine._EQUAL;
  10570. },
  10571. enumerable: true,
  10572. configurable: true
  10573. });
  10574. Object.defineProperty(Engine, "LEQUAL", {
  10575. get: function () {
  10576. return Engine._LEQUAL;
  10577. },
  10578. enumerable: true,
  10579. configurable: true
  10580. });
  10581. Object.defineProperty(Engine, "GREATER", {
  10582. get: function () {
  10583. return Engine._GREATER;
  10584. },
  10585. enumerable: true,
  10586. configurable: true
  10587. });
  10588. Object.defineProperty(Engine, "GEQUAL", {
  10589. get: function () {
  10590. return Engine._GEQUAL;
  10591. },
  10592. enumerable: true,
  10593. configurable: true
  10594. });
  10595. Object.defineProperty(Engine, "NOTEQUAL", {
  10596. get: function () {
  10597. return Engine._NOTEQUAL;
  10598. },
  10599. enumerable: true,
  10600. configurable: true
  10601. });
  10602. Object.defineProperty(Engine, "KEEP", {
  10603. get: function () {
  10604. return Engine._KEEP;
  10605. },
  10606. enumerable: true,
  10607. configurable: true
  10608. });
  10609. Object.defineProperty(Engine, "REPLACE", {
  10610. get: function () {
  10611. return Engine._REPLACE;
  10612. },
  10613. enumerable: true,
  10614. configurable: true
  10615. });
  10616. Object.defineProperty(Engine, "INCR", {
  10617. get: function () {
  10618. return Engine._INCR;
  10619. },
  10620. enumerable: true,
  10621. configurable: true
  10622. });
  10623. Object.defineProperty(Engine, "DECR", {
  10624. get: function () {
  10625. return Engine._DECR;
  10626. },
  10627. enumerable: true,
  10628. configurable: true
  10629. });
  10630. Object.defineProperty(Engine, "INVERT", {
  10631. get: function () {
  10632. return Engine._INVERT;
  10633. },
  10634. enumerable: true,
  10635. configurable: true
  10636. });
  10637. Object.defineProperty(Engine, "INCR_WRAP", {
  10638. get: function () {
  10639. return Engine._INCR_WRAP;
  10640. },
  10641. enumerable: true,
  10642. configurable: true
  10643. });
  10644. Object.defineProperty(Engine, "DECR_WRAP", {
  10645. get: function () {
  10646. return Engine._DECR_WRAP;
  10647. },
  10648. enumerable: true,
  10649. configurable: true
  10650. });
  10651. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  10652. get: function () {
  10653. return Engine._ALPHA_DISABLE;
  10654. },
  10655. enumerable: true,
  10656. configurable: true
  10657. });
  10658. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  10659. get: function () {
  10660. return Engine._ALPHA_ONEONE;
  10661. },
  10662. enumerable: true,
  10663. configurable: true
  10664. });
  10665. Object.defineProperty(Engine, "ALPHA_ADD", {
  10666. get: function () {
  10667. return Engine._ALPHA_ADD;
  10668. },
  10669. enumerable: true,
  10670. configurable: true
  10671. });
  10672. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  10673. get: function () {
  10674. return Engine._ALPHA_COMBINE;
  10675. },
  10676. enumerable: true,
  10677. configurable: true
  10678. });
  10679. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  10680. get: function () {
  10681. return Engine._ALPHA_SUBTRACT;
  10682. },
  10683. enumerable: true,
  10684. configurable: true
  10685. });
  10686. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  10687. get: function () {
  10688. return Engine._ALPHA_MULTIPLY;
  10689. },
  10690. enumerable: true,
  10691. configurable: true
  10692. });
  10693. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  10694. get: function () {
  10695. return Engine._ALPHA_MAXIMIZED;
  10696. },
  10697. enumerable: true,
  10698. configurable: true
  10699. });
  10700. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  10701. get: function () {
  10702. return Engine._ALPHA_PREMULTIPLIED;
  10703. },
  10704. enumerable: true,
  10705. configurable: true
  10706. });
  10707. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  10708. get: function () {
  10709. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  10710. },
  10711. enumerable: true,
  10712. configurable: true
  10713. });
  10714. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  10715. get: function () {
  10716. return Engine._ALPHA_INTERPOLATE;
  10717. },
  10718. enumerable: true,
  10719. configurable: true
  10720. });
  10721. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  10722. get: function () {
  10723. return Engine._ALPHA_SCREENMODE;
  10724. },
  10725. enumerable: true,
  10726. configurable: true
  10727. });
  10728. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  10729. get: function () {
  10730. return Engine._DELAYLOADSTATE_NONE;
  10731. },
  10732. enumerable: true,
  10733. configurable: true
  10734. });
  10735. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  10736. get: function () {
  10737. return Engine._DELAYLOADSTATE_LOADED;
  10738. },
  10739. enumerable: true,
  10740. configurable: true
  10741. });
  10742. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  10743. get: function () {
  10744. return Engine._DELAYLOADSTATE_LOADING;
  10745. },
  10746. enumerable: true,
  10747. configurable: true
  10748. });
  10749. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  10750. get: function () {
  10751. return Engine._DELAYLOADSTATE_NOTLOADED;
  10752. },
  10753. enumerable: true,
  10754. configurable: true
  10755. });
  10756. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  10757. get: function () {
  10758. return Engine._TEXTUREFORMAT_ALPHA;
  10759. },
  10760. enumerable: true,
  10761. configurable: true
  10762. });
  10763. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  10764. get: function () {
  10765. return Engine._TEXTUREFORMAT_LUMINANCE;
  10766. },
  10767. enumerable: true,
  10768. configurable: true
  10769. });
  10770. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  10771. get: function () {
  10772. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  10773. },
  10774. enumerable: true,
  10775. configurable: true
  10776. });
  10777. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  10778. get: function () {
  10779. return Engine._TEXTUREFORMAT_RGB;
  10780. },
  10781. enumerable: true,
  10782. configurable: true
  10783. });
  10784. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  10785. get: function () {
  10786. return Engine._TEXTUREFORMAT_RGBA;
  10787. },
  10788. enumerable: true,
  10789. configurable: true
  10790. });
  10791. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  10792. get: function () {
  10793. return Engine._TEXTURETYPE_UNSIGNED_INT;
  10794. },
  10795. enumerable: true,
  10796. configurable: true
  10797. });
  10798. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  10799. get: function () {
  10800. return Engine._TEXTURETYPE_FLOAT;
  10801. },
  10802. enumerable: true,
  10803. configurable: true
  10804. });
  10805. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  10806. get: function () {
  10807. return Engine._TEXTURETYPE_HALF_FLOAT;
  10808. },
  10809. enumerable: true,
  10810. configurable: true
  10811. });
  10812. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  10813. get: function () {
  10814. return Engine._SCALEMODE_FLOOR;
  10815. },
  10816. enumerable: true,
  10817. configurable: true
  10818. });
  10819. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  10820. get: function () {
  10821. return Engine._SCALEMODE_NEAREST;
  10822. },
  10823. enumerable: true,
  10824. configurable: true
  10825. });
  10826. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  10827. get: function () {
  10828. return Engine._SCALEMODE_CEILING;
  10829. },
  10830. enumerable: true,
  10831. configurable: true
  10832. });
  10833. Object.defineProperty(Engine, "Version", {
  10834. get: function () {
  10835. return "3.2.0-alpha7";
  10836. },
  10837. enumerable: true,
  10838. configurable: true
  10839. });
  10840. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  10841. get: function () {
  10842. return this._vrExclusivePointerMode;
  10843. },
  10844. enumerable: true,
  10845. configurable: true
  10846. });
  10847. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  10848. get: function () {
  10849. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  10850. },
  10851. enumerable: true,
  10852. configurable: true
  10853. });
  10854. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  10855. get: function () {
  10856. return this._webGLVersion < 2 || this.forcePOTTextures;
  10857. },
  10858. enumerable: true,
  10859. configurable: true
  10860. });
  10861. Object.defineProperty(Engine.prototype, "badOS", {
  10862. get: function () {
  10863. return this._badOS;
  10864. },
  10865. enumerable: true,
  10866. configurable: true
  10867. });
  10868. Object.defineProperty(Engine.prototype, "badDesktopOS", {
  10869. get: function () {
  10870. return this._badDesktopOS;
  10871. },
  10872. enumerable: true,
  10873. configurable: true
  10874. });
  10875. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  10876. get: function () {
  10877. return this._performanceMonitor;
  10878. },
  10879. enumerable: true,
  10880. configurable: true
  10881. });
  10882. Object.defineProperty(Engine.prototype, "texturesSupported", {
  10883. get: function () {
  10884. return this._texturesSupported;
  10885. },
  10886. enumerable: true,
  10887. configurable: true
  10888. });
  10889. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  10890. get: function () {
  10891. return this._textureFormatInUse;
  10892. },
  10893. enumerable: true,
  10894. configurable: true
  10895. });
  10896. Object.defineProperty(Engine.prototype, "currentViewport", {
  10897. get: function () {
  10898. return this._cachedViewport;
  10899. },
  10900. enumerable: true,
  10901. configurable: true
  10902. });
  10903. Object.defineProperty(Engine.prototype, "emptyTexture", {
  10904. // Empty texture
  10905. get: function () {
  10906. if (!this._emptyTexture) {
  10907. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  10908. }
  10909. return this._emptyTexture;
  10910. },
  10911. enumerable: true,
  10912. configurable: true
  10913. });
  10914. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  10915. get: function () {
  10916. if (!this._emptyTexture3D) {
  10917. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  10918. }
  10919. return this._emptyTexture3D;
  10920. },
  10921. enumerable: true,
  10922. configurable: true
  10923. });
  10924. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  10925. get: function () {
  10926. if (!this._emptyCubeTexture) {
  10927. var faceData = new Uint8Array(4);
  10928. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  10929. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  10930. }
  10931. return this._emptyCubeTexture;
  10932. },
  10933. enumerable: true,
  10934. configurable: true
  10935. });
  10936. Engine.prototype._rebuildInternalTextures = function () {
  10937. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  10938. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  10939. var internalTexture = currentState_1[_i];
  10940. internalTexture._rebuild();
  10941. }
  10942. };
  10943. Engine.prototype._rebuildEffects = function () {
  10944. for (var key in this._compiledEffects) {
  10945. var effect = this._compiledEffects[key];
  10946. effect._prepareEffect();
  10947. }
  10948. BABYLON.Effect.ResetCache();
  10949. };
  10950. Engine.prototype._rebuildBuffers = function () {
  10951. // Index / Vertex
  10952. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  10953. var scene = _a[_i];
  10954. scene.resetCachedMaterial();
  10955. scene._rebuildGeometries();
  10956. scene._rebuildTextures();
  10957. }
  10958. // Uniforms
  10959. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  10960. var uniformBuffer = _c[_b];
  10961. uniformBuffer._rebuild();
  10962. }
  10963. };
  10964. Engine.prototype._initGLContext = function () {
  10965. // Caps
  10966. this._caps = new EngineCapabilities();
  10967. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  10968. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  10969. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  10970. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  10971. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  10972. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  10973. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  10974. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  10975. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  10976. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  10977. // Infos
  10978. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  10979. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  10980. if (rendererInfo != null) {
  10981. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  10982. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  10983. }
  10984. if (!this._glVendor) {
  10985. this._glVendor = "Unknown vendor";
  10986. }
  10987. if (!this._glRenderer) {
  10988. this._glRenderer = "Unknown renderer";
  10989. }
  10990. // Constants
  10991. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  10992. if (this._gl.RGBA16F !== 0x881A) {
  10993. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  10994. }
  10995. if (this._gl.RGBA32F !== 0x8814) {
  10996. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  10997. }
  10998. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  10999. this._gl.DEPTH24_STENCIL8 = 35056;
  11000. }
  11001. // Extensions
  11002. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  11003. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  11004. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  11005. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  11006. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  11007. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  11008. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  11009. 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');
  11010. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  11011. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  11012. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  11013. this._caps.highPrecisionShaderSupported = true;
  11014. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  11015. if (this._caps.timerQuery) {
  11016. if (this._webGLVersion === 1) {
  11017. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  11018. }
  11019. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  11020. }
  11021. // Checks if some of the format renders first to allow the use of webgl inspector.
  11022. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  11023. this._caps.textureFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float');
  11024. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear');
  11025. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer();
  11026. this._caps.textureHalfFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float');
  11027. this._caps.textureHalfFloatLinearFiltering = this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'));
  11028. if (this._webGLVersion > 1) {
  11029. this._gl.HALF_FLOAT_OES = 0x140B;
  11030. }
  11031. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  11032. this._caps.textureLOD = this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod');
  11033. // Draw buffers
  11034. if (this._webGLVersion > 1) {
  11035. this._caps.drawBuffersExtension = true;
  11036. }
  11037. else {
  11038. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  11039. if (drawBuffersExtension !== null) {
  11040. this._caps.drawBuffersExtension = true;
  11041. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  11042. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  11043. for (var i = 0; i < 16; i++) {
  11044. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  11045. }
  11046. }
  11047. else {
  11048. this._caps.drawBuffersExtension = false;
  11049. }
  11050. }
  11051. // Depth Texture
  11052. if (this._webGLVersion > 1) {
  11053. this._caps.depthTextureExtension = true;
  11054. }
  11055. else {
  11056. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  11057. if (depthTextureExtension != null) {
  11058. this._caps.depthTextureExtension = true;
  11059. }
  11060. }
  11061. // Vertex array object
  11062. if (this._webGLVersion > 1) {
  11063. this._caps.vertexArrayObject = true;
  11064. }
  11065. else {
  11066. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  11067. if (vertexArrayObjectExtension != null) {
  11068. this._caps.vertexArrayObject = true;
  11069. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  11070. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  11071. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  11072. }
  11073. else {
  11074. this._caps.vertexArrayObject = false;
  11075. }
  11076. }
  11077. // Instances count
  11078. if (this._webGLVersion > 1) {
  11079. this._caps.instancedArrays = true;
  11080. }
  11081. else {
  11082. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  11083. if (instanceExtension != null) {
  11084. this._caps.instancedArrays = true;
  11085. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  11086. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  11087. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  11088. }
  11089. else {
  11090. this._caps.instancedArrays = false;
  11091. }
  11092. }
  11093. // Intelligently add supported compressed formats in order to check for.
  11094. // Check for ASTC support first as it is most powerful and to be very cross platform.
  11095. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  11096. // Likely no hardware which supports both PVR & DXT, so order matters little.
  11097. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  11098. if (this._caps.astc)
  11099. this.texturesSupported.push('-astc.ktx');
  11100. if (this._caps.s3tc)
  11101. this.texturesSupported.push('-dxt.ktx');
  11102. if (this._caps.pvrtc)
  11103. this.texturesSupported.push('-pvrtc.ktx');
  11104. if (this._caps.etc2)
  11105. this.texturesSupported.push('-etc2.ktx');
  11106. if (this._caps.etc1)
  11107. this.texturesSupported.push('-etc1.ktx');
  11108. if (this._gl.getShaderPrecisionFormat) {
  11109. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  11110. if (highp) {
  11111. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  11112. }
  11113. }
  11114. // Depth buffer
  11115. this.setDepthBuffer(true);
  11116. this.setDepthFunctionToLessOrEqual();
  11117. this.setDepthWrite(true);
  11118. // Texture maps
  11119. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  11120. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  11121. this._nextFreeTextureSlots.push(slot);
  11122. }
  11123. };
  11124. Object.defineProperty(Engine.prototype, "webGLVersion", {
  11125. get: function () {
  11126. return this._webGLVersion;
  11127. },
  11128. enumerable: true,
  11129. configurable: true
  11130. });
  11131. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  11132. /**
  11133. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  11134. */
  11135. get: function () {
  11136. return this._isStencilEnable;
  11137. },
  11138. enumerable: true,
  11139. configurable: true
  11140. });
  11141. Engine.prototype._prepareWorkingCanvas = function () {
  11142. if (this._workingCanvas) {
  11143. return;
  11144. }
  11145. this._workingCanvas = document.createElement("canvas");
  11146. var context = this._workingCanvas.getContext("2d");
  11147. if (context) {
  11148. this._workingContext = context;
  11149. }
  11150. };
  11151. Engine.prototype.resetTextureCache = function () {
  11152. for (var key in this._boundTexturesCache) {
  11153. var boundTexture = this._boundTexturesCache[key];
  11154. if (boundTexture) {
  11155. this._removeDesignatedSlot(boundTexture);
  11156. }
  11157. this._boundTexturesCache[key] = null;
  11158. }
  11159. if (!this.disableTextureBindingOptimization) {
  11160. this._nextFreeTextureSlots = [];
  11161. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  11162. this._nextFreeTextureSlots.push(slot);
  11163. }
  11164. }
  11165. this._currentTextureChannel = -1;
  11166. };
  11167. Engine.prototype.isDeterministicLockStep = function () {
  11168. return this._deterministicLockstep;
  11169. };
  11170. Engine.prototype.getLockstepMaxSteps = function () {
  11171. return this._lockstepMaxSteps;
  11172. };
  11173. Engine.prototype.getGlInfo = function () {
  11174. return {
  11175. vendor: this._glVendor,
  11176. renderer: this._glRenderer,
  11177. version: this._glVersion
  11178. };
  11179. };
  11180. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  11181. if (useScreen === void 0) { useScreen = false; }
  11182. var viewport = camera.viewport;
  11183. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  11184. };
  11185. Engine.prototype.getRenderWidth = function (useScreen) {
  11186. if (useScreen === void 0) { useScreen = false; }
  11187. if (!useScreen && this._currentRenderTarget) {
  11188. return this._currentRenderTarget.width;
  11189. }
  11190. return this._gl.drawingBufferWidth;
  11191. };
  11192. Engine.prototype.getRenderHeight = function (useScreen) {
  11193. if (useScreen === void 0) { useScreen = false; }
  11194. if (!useScreen && this._currentRenderTarget) {
  11195. return this._currentRenderTarget.height;
  11196. }
  11197. return this._gl.drawingBufferHeight;
  11198. };
  11199. Engine.prototype.getRenderingCanvas = function () {
  11200. return this._renderingCanvas;
  11201. };
  11202. Engine.prototype.getRenderingCanvasClientRect = function () {
  11203. if (!this._renderingCanvas) {
  11204. return null;
  11205. }
  11206. return this._renderingCanvas.getBoundingClientRect();
  11207. };
  11208. Engine.prototype.setHardwareScalingLevel = function (level) {
  11209. this._hardwareScalingLevel = level;
  11210. this.resize();
  11211. };
  11212. Engine.prototype.getHardwareScalingLevel = function () {
  11213. return this._hardwareScalingLevel;
  11214. };
  11215. Engine.prototype.getLoadedTexturesCache = function () {
  11216. return this._internalTexturesCache;
  11217. };
  11218. Engine.prototype.getCaps = function () {
  11219. return this._caps;
  11220. };
  11221. Object.defineProperty(Engine.prototype, "drawCalls", {
  11222. /** The number of draw calls submitted last frame */
  11223. get: function () {
  11224. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  11225. return 0;
  11226. },
  11227. enumerable: true,
  11228. configurable: true
  11229. });
  11230. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  11231. get: function () {
  11232. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  11233. return null;
  11234. },
  11235. enumerable: true,
  11236. configurable: true
  11237. });
  11238. Engine.prototype.getDepthFunction = function () {
  11239. return this._depthCullingState.depthFunc;
  11240. };
  11241. Engine.prototype.setDepthFunction = function (depthFunc) {
  11242. this._depthCullingState.depthFunc = depthFunc;
  11243. };
  11244. Engine.prototype.setDepthFunctionToGreater = function () {
  11245. this._depthCullingState.depthFunc = this._gl.GREATER;
  11246. };
  11247. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  11248. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  11249. };
  11250. Engine.prototype.setDepthFunctionToLess = function () {
  11251. this._depthCullingState.depthFunc = this._gl.LESS;
  11252. };
  11253. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  11254. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  11255. };
  11256. Engine.prototype.getStencilBuffer = function () {
  11257. return this._stencilState.stencilTest;
  11258. };
  11259. Engine.prototype.setStencilBuffer = function (enable) {
  11260. this._stencilState.stencilTest = enable;
  11261. };
  11262. Engine.prototype.getStencilMask = function () {
  11263. return this._stencilState.stencilMask;
  11264. };
  11265. Engine.prototype.setStencilMask = function (mask) {
  11266. this._stencilState.stencilMask = mask;
  11267. };
  11268. Engine.prototype.getStencilFunction = function () {
  11269. return this._stencilState.stencilFunc;
  11270. };
  11271. Engine.prototype.getStencilFunctionReference = function () {
  11272. return this._stencilState.stencilFuncRef;
  11273. };
  11274. Engine.prototype.getStencilFunctionMask = function () {
  11275. return this._stencilState.stencilFuncMask;
  11276. };
  11277. Engine.prototype.setStencilFunction = function (stencilFunc) {
  11278. this._stencilState.stencilFunc = stencilFunc;
  11279. };
  11280. Engine.prototype.setStencilFunctionReference = function (reference) {
  11281. this._stencilState.stencilFuncRef = reference;
  11282. };
  11283. Engine.prototype.setStencilFunctionMask = function (mask) {
  11284. this._stencilState.stencilFuncMask = mask;
  11285. };
  11286. Engine.prototype.getStencilOperationFail = function () {
  11287. return this._stencilState.stencilOpStencilFail;
  11288. };
  11289. Engine.prototype.getStencilOperationDepthFail = function () {
  11290. return this._stencilState.stencilOpDepthFail;
  11291. };
  11292. Engine.prototype.getStencilOperationPass = function () {
  11293. return this._stencilState.stencilOpStencilDepthPass;
  11294. };
  11295. Engine.prototype.setStencilOperationFail = function (operation) {
  11296. this._stencilState.stencilOpStencilFail = operation;
  11297. };
  11298. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  11299. this._stencilState.stencilOpDepthFail = operation;
  11300. };
  11301. Engine.prototype.setStencilOperationPass = function (operation) {
  11302. this._stencilState.stencilOpStencilDepthPass = operation;
  11303. };
  11304. Engine.prototype.setDitheringState = function (value) {
  11305. if (value) {
  11306. this._gl.enable(this._gl.DITHER);
  11307. }
  11308. else {
  11309. this._gl.disable(this._gl.DITHER);
  11310. }
  11311. };
  11312. Engine.prototype.setRasterizerState = function (value) {
  11313. if (value) {
  11314. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  11315. }
  11316. else {
  11317. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  11318. }
  11319. };
  11320. /**
  11321. * stop executing a render loop function and remove it from the execution array
  11322. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  11323. */
  11324. Engine.prototype.stopRenderLoop = function (renderFunction) {
  11325. if (!renderFunction) {
  11326. this._activeRenderLoops = [];
  11327. return;
  11328. }
  11329. var index = this._activeRenderLoops.indexOf(renderFunction);
  11330. if (index >= 0) {
  11331. this._activeRenderLoops.splice(index, 1);
  11332. }
  11333. };
  11334. Engine.prototype._renderLoop = function () {
  11335. if (!this._contextWasLost) {
  11336. var shouldRender = true;
  11337. if (!this.renderEvenInBackground && this._windowIsBackground) {
  11338. shouldRender = false;
  11339. }
  11340. if (shouldRender) {
  11341. // Start new frame
  11342. this.beginFrame();
  11343. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  11344. var renderFunction = this._activeRenderLoops[index];
  11345. renderFunction();
  11346. }
  11347. // Present
  11348. this.endFrame();
  11349. }
  11350. }
  11351. if (this._activeRenderLoops.length > 0) {
  11352. // Register new frame
  11353. var requester = null;
  11354. if (this._vrDisplay && this._vrDisplay.isPresenting)
  11355. requester = this._vrDisplay;
  11356. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  11357. }
  11358. else {
  11359. this._renderingQueueLaunched = false;
  11360. }
  11361. };
  11362. /**
  11363. * Register and execute a render loop. The engine can have more than one render function.
  11364. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  11365. * @example
  11366. * engine.runRenderLoop(function () {
  11367. * scene.render()
  11368. * })
  11369. */
  11370. Engine.prototype.runRenderLoop = function (renderFunction) {
  11371. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  11372. return;
  11373. }
  11374. this._activeRenderLoops.push(renderFunction);
  11375. if (!this._renderingQueueLaunched) {
  11376. this._renderingQueueLaunched = true;
  11377. this._bindedRenderFunction = this._renderLoop.bind(this);
  11378. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  11379. }
  11380. };
  11381. /**
  11382. * Toggle full screen mode.
  11383. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  11384. * @param {any} options - an options object to be sent to the requestFullscreen function
  11385. */
  11386. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  11387. if (this.isFullscreen) {
  11388. BABYLON.Tools.ExitFullscreen();
  11389. }
  11390. else {
  11391. this._pointerLockRequested = requestPointerLock;
  11392. if (this._renderingCanvas) {
  11393. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  11394. }
  11395. }
  11396. };
  11397. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  11398. if (stencil === void 0) { stencil = false; }
  11399. this.applyStates();
  11400. var mode = 0;
  11401. if (backBuffer && color) {
  11402. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  11403. mode |= this._gl.COLOR_BUFFER_BIT;
  11404. }
  11405. if (depth) {
  11406. this._gl.clearDepth(1.0);
  11407. mode |= this._gl.DEPTH_BUFFER_BIT;
  11408. }
  11409. if (stencil) {
  11410. this._gl.clearStencil(0);
  11411. mode |= this._gl.STENCIL_BUFFER_BIT;
  11412. }
  11413. this._gl.clear(mode);
  11414. };
  11415. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  11416. var gl = this._gl;
  11417. // Save state
  11418. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  11419. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  11420. // Change state
  11421. gl.enable(gl.SCISSOR_TEST);
  11422. gl.scissor(x, y, width, height);
  11423. // Clear
  11424. this.clear(clearColor, true, true, true);
  11425. // Restore state
  11426. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  11427. if (curScissor === true) {
  11428. gl.enable(gl.SCISSOR_TEST);
  11429. }
  11430. else {
  11431. gl.disable(gl.SCISSOR_TEST);
  11432. }
  11433. };
  11434. /**
  11435. * Set the WebGL's viewport
  11436. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  11437. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  11438. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  11439. */
  11440. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  11441. var width = requiredWidth || this.getRenderWidth();
  11442. var height = requiredHeight || this.getRenderHeight();
  11443. var x = viewport.x || 0;
  11444. var y = viewport.y || 0;
  11445. this._cachedViewport = viewport;
  11446. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  11447. };
  11448. /**
  11449. * Directly set the WebGL Viewport
  11450. * The x, y, width & height are directly passed to the WebGL call
  11451. * @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.
  11452. */
  11453. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  11454. var currentViewport = this._cachedViewport;
  11455. this._cachedViewport = null;
  11456. this._gl.viewport(x, y, width, height);
  11457. return currentViewport;
  11458. };
  11459. Engine.prototype.beginFrame = function () {
  11460. this.onBeginFrameObservable.notifyObservers(this);
  11461. this._measureFps();
  11462. };
  11463. Engine.prototype.endFrame = function () {
  11464. //force a flush in case we are using a bad OS.
  11465. if (this._badOS) {
  11466. this.flushFramebuffer();
  11467. }
  11468. //submit frame to the vr device, if enabled
  11469. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  11470. // TODO: We should only submit the frame if we read frameData successfully.
  11471. this._vrDisplay.submitFrame();
  11472. }
  11473. this.onEndFrameObservable.notifyObservers(this);
  11474. };
  11475. /**
  11476. * resize the view according to the canvas' size.
  11477. * @example
  11478. * window.addEventListener("resize", function () {
  11479. * engine.resize();
  11480. * });
  11481. */
  11482. Engine.prototype.resize = function () {
  11483. // We're not resizing the size of the canvas while in VR mode & presenting
  11484. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  11485. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  11486. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  11487. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  11488. }
  11489. };
  11490. /**
  11491. * force a specific size of the canvas
  11492. * @param {number} width - the new canvas' width
  11493. * @param {number} height - the new canvas' height
  11494. */
  11495. Engine.prototype.setSize = function (width, height) {
  11496. if (!this._renderingCanvas) {
  11497. return;
  11498. }
  11499. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  11500. return;
  11501. }
  11502. this._renderingCanvas.width = width;
  11503. this._renderingCanvas.height = height;
  11504. for (var index = 0; index < this.scenes.length; index++) {
  11505. var scene = this.scenes[index];
  11506. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  11507. var cam = scene.cameras[camIndex];
  11508. cam._currentRenderId = 0;
  11509. }
  11510. }
  11511. if (this.onResizeObservable.hasObservers) {
  11512. this.onResizeObservable.notifyObservers(this);
  11513. }
  11514. };
  11515. // WebVR functions
  11516. Engine.prototype.isVRDevicePresent = function () {
  11517. return !!this._vrDisplay;
  11518. };
  11519. Engine.prototype.getVRDevice = function () {
  11520. return this._vrDisplay;
  11521. };
  11522. Engine.prototype.initWebVR = function () {
  11523. var _this = this;
  11524. var notifyObservers = function () {
  11525. var eventArgs = {
  11526. vrDisplay: _this._vrDisplay,
  11527. vrSupported: _this._vrSupported
  11528. };
  11529. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  11530. };
  11531. if (!this._onVrDisplayConnect) {
  11532. this._onVrDisplayConnect = function (event) {
  11533. _this._vrDisplay = event.display;
  11534. notifyObservers();
  11535. };
  11536. this._onVrDisplayDisconnect = function () {
  11537. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  11538. _this._vrDisplay = undefined;
  11539. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  11540. notifyObservers();
  11541. };
  11542. this._onVrDisplayPresentChange = function () {
  11543. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  11544. };
  11545. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  11546. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  11547. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  11548. }
  11549. this._getVRDisplays(notifyObservers);
  11550. return this.onVRDisplayChangedObservable;
  11551. };
  11552. Engine.prototype.enableVR = function () {
  11553. var _this = this;
  11554. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  11555. var onResolved = function () {
  11556. _this.onVRRequestPresentComplete.notifyObservers(true);
  11557. _this._onVRFullScreenTriggered();
  11558. };
  11559. var onRejected = function () {
  11560. _this.onVRRequestPresentComplete.notifyObservers(false);
  11561. };
  11562. this.onVRRequestPresentStart.notifyObservers(this);
  11563. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  11564. }
  11565. };
  11566. Engine.prototype.disableVR = function () {
  11567. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  11568. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  11569. }
  11570. };
  11571. Engine.prototype._getVRDisplays = function (callback) {
  11572. var _this = this;
  11573. var getWebVRDevices = function (devices) {
  11574. _this._vrSupported = true;
  11575. // note that devices may actually be an empty array. This is fine;
  11576. // we expect this._vrDisplay to be undefined in this case.
  11577. return _this._vrDisplay = devices[0];
  11578. };
  11579. if (navigator.getVRDisplays) {
  11580. navigator.getVRDisplays().then(getWebVRDevices).then(callback).catch(function (error) {
  11581. // TODO: System CANNOT support WebVR, despite API presence.
  11582. _this._vrSupported = false;
  11583. callback();
  11584. });
  11585. }
  11586. else {
  11587. // TODO: Browser does not support WebVR
  11588. this._vrDisplay = undefined;
  11589. this._vrSupported = false;
  11590. callback();
  11591. }
  11592. };
  11593. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  11594. if (this._currentRenderTarget) {
  11595. this.unBindFramebuffer(this._currentRenderTarget);
  11596. }
  11597. this._currentRenderTarget = texture;
  11598. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  11599. var gl = this._gl;
  11600. if (texture.isCube) {
  11601. if (faceIndex === undefined) {
  11602. faceIndex = 0;
  11603. }
  11604. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  11605. }
  11606. if (this._cachedViewport && !forceFullscreenViewport) {
  11607. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  11608. }
  11609. else {
  11610. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  11611. }
  11612. this.wipeCaches();
  11613. };
  11614. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  11615. if (this._currentFramebuffer !== framebuffer) {
  11616. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  11617. this._currentFramebuffer = framebuffer;
  11618. }
  11619. };
  11620. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  11621. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  11622. this._currentRenderTarget = null;
  11623. // If MSAA, we need to bitblt back to main texture
  11624. var gl = this._gl;
  11625. if (texture._MSAAFramebuffer) {
  11626. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  11627. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  11628. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  11629. }
  11630. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  11631. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  11632. gl.generateMipmap(gl.TEXTURE_2D);
  11633. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  11634. }
  11635. if (onBeforeUnbind) {
  11636. if (texture._MSAAFramebuffer) {
  11637. // Bind the correct framebuffer
  11638. this.bindUnboundFramebuffer(texture._framebuffer);
  11639. }
  11640. onBeforeUnbind();
  11641. }
  11642. this.bindUnboundFramebuffer(null);
  11643. };
  11644. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  11645. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  11646. this._currentRenderTarget = null;
  11647. // If MSAA, we need to bitblt back to main texture
  11648. var gl = this._gl;
  11649. if (textures[0]._MSAAFramebuffer) {
  11650. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  11651. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  11652. var attachments = textures[0]._attachments;
  11653. if (!attachments) {
  11654. attachments = new Array(textures.length);
  11655. textures[0]._attachments = attachments;
  11656. }
  11657. for (var i = 0; i < textures.length; i++) {
  11658. var texture = textures[i];
  11659. for (var j = 0; j < attachments.length; j++) {
  11660. attachments[j] = gl.NONE;
  11661. }
  11662. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  11663. gl.readBuffer(attachments[i]);
  11664. gl.drawBuffers(attachments);
  11665. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  11666. }
  11667. for (var i = 0; i < attachments.length; i++) {
  11668. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  11669. }
  11670. gl.drawBuffers(attachments);
  11671. }
  11672. for (var i = 0; i < textures.length; i++) {
  11673. var texture = textures[i];
  11674. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  11675. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  11676. gl.generateMipmap(gl.TEXTURE_2D);
  11677. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  11678. }
  11679. }
  11680. if (onBeforeUnbind) {
  11681. if (textures[0]._MSAAFramebuffer) {
  11682. // Bind the correct framebuffer
  11683. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  11684. }
  11685. onBeforeUnbind();
  11686. }
  11687. this.bindUnboundFramebuffer(null);
  11688. };
  11689. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  11690. if (texture.generateMipMaps) {
  11691. var gl = this._gl;
  11692. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  11693. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  11694. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  11695. }
  11696. };
  11697. Engine.prototype.flushFramebuffer = function () {
  11698. this._gl.flush();
  11699. };
  11700. Engine.prototype.restoreDefaultFramebuffer = function () {
  11701. if (this._currentRenderTarget) {
  11702. this.unBindFramebuffer(this._currentRenderTarget);
  11703. }
  11704. else {
  11705. this.bindUnboundFramebuffer(null);
  11706. }
  11707. if (this._cachedViewport) {
  11708. this.setViewport(this._cachedViewport);
  11709. }
  11710. this.wipeCaches();
  11711. };
  11712. // UBOs
  11713. Engine.prototype.createUniformBuffer = function (elements) {
  11714. var ubo = this._gl.createBuffer();
  11715. if (!ubo) {
  11716. throw new Error("Unable to create uniform buffer");
  11717. }
  11718. this.bindUniformBuffer(ubo);
  11719. if (elements instanceof Float32Array) {
  11720. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  11721. }
  11722. else {
  11723. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  11724. }
  11725. this.bindUniformBuffer(null);
  11726. ubo.references = 1;
  11727. return ubo;
  11728. };
  11729. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  11730. var ubo = this._gl.createBuffer();
  11731. if (!ubo) {
  11732. throw new Error("Unable to create dynamic uniform buffer");
  11733. }
  11734. this.bindUniformBuffer(ubo);
  11735. if (elements instanceof Float32Array) {
  11736. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  11737. }
  11738. else {
  11739. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  11740. }
  11741. this.bindUniformBuffer(null);
  11742. ubo.references = 1;
  11743. return ubo;
  11744. };
  11745. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  11746. this.bindUniformBuffer(uniformBuffer);
  11747. if (offset === undefined) {
  11748. offset = 0;
  11749. }
  11750. if (count === undefined) {
  11751. if (elements instanceof Float32Array) {
  11752. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  11753. }
  11754. else {
  11755. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  11756. }
  11757. }
  11758. else {
  11759. if (elements instanceof Float32Array) {
  11760. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  11761. }
  11762. else {
  11763. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  11764. }
  11765. }
  11766. this.bindUniformBuffer(null);
  11767. };
  11768. // VBOs
  11769. Engine.prototype._resetVertexBufferBinding = function () {
  11770. this.bindArrayBuffer(null);
  11771. this._cachedVertexBuffers = null;
  11772. };
  11773. Engine.prototype.createVertexBuffer = function (vertices) {
  11774. var vbo = this._gl.createBuffer();
  11775. if (!vbo) {
  11776. throw new Error("Unable to create vertex buffer");
  11777. }
  11778. this.bindArrayBuffer(vbo);
  11779. if (vertices instanceof Float32Array) {
  11780. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  11781. }
  11782. else {
  11783. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  11784. }
  11785. this._resetVertexBufferBinding();
  11786. vbo.references = 1;
  11787. return vbo;
  11788. };
  11789. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  11790. var vbo = this._gl.createBuffer();
  11791. if (!vbo) {
  11792. throw new Error("Unable to create dynamic vertex buffer");
  11793. }
  11794. this.bindArrayBuffer(vbo);
  11795. if (vertices instanceof Float32Array) {
  11796. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  11797. }
  11798. else {
  11799. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  11800. }
  11801. this._resetVertexBufferBinding();
  11802. vbo.references = 1;
  11803. return vbo;
  11804. };
  11805. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  11806. if (offset === void 0) { offset = 0; }
  11807. // Force cache update
  11808. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  11809. this.bindIndexBuffer(indexBuffer);
  11810. var arrayBuffer;
  11811. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  11812. arrayBuffer = indices;
  11813. }
  11814. else {
  11815. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  11816. }
  11817. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  11818. this._resetIndexBufferBinding();
  11819. };
  11820. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  11821. this.bindArrayBuffer(vertexBuffer);
  11822. if (offset === undefined) {
  11823. offset = 0;
  11824. }
  11825. if (count === undefined) {
  11826. if (vertices instanceof Float32Array) {
  11827. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  11828. }
  11829. else {
  11830. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  11831. }
  11832. }
  11833. else {
  11834. if (vertices instanceof Float32Array) {
  11835. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  11836. }
  11837. else {
  11838. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  11839. }
  11840. }
  11841. this._resetVertexBufferBinding();
  11842. };
  11843. Engine.prototype._resetIndexBufferBinding = function () {
  11844. this.bindIndexBuffer(null);
  11845. this._cachedIndexBuffer = null;
  11846. };
  11847. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  11848. var vbo = this._gl.createBuffer();
  11849. if (!vbo) {
  11850. throw new Error("Unable to create index buffer");
  11851. }
  11852. this.bindIndexBuffer(vbo);
  11853. // Check for 32 bits indices
  11854. var arrayBuffer;
  11855. var need32Bits = false;
  11856. if (indices instanceof Uint16Array) {
  11857. arrayBuffer = indices;
  11858. }
  11859. else {
  11860. //check 32 bit support
  11861. if (this._caps.uintIndices) {
  11862. if (indices instanceof Uint32Array) {
  11863. arrayBuffer = indices;
  11864. need32Bits = true;
  11865. }
  11866. else {
  11867. //number[] or Int32Array, check if 32 bit is necessary
  11868. for (var index = 0; index < indices.length; index++) {
  11869. if (indices[index] > 65535) {
  11870. need32Bits = true;
  11871. break;
  11872. }
  11873. }
  11874. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  11875. }
  11876. }
  11877. else {
  11878. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  11879. arrayBuffer = new Uint16Array(indices);
  11880. }
  11881. }
  11882. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  11883. this._resetIndexBufferBinding();
  11884. vbo.references = 1;
  11885. vbo.is32Bits = need32Bits;
  11886. return vbo;
  11887. };
  11888. Engine.prototype.bindArrayBuffer = function (buffer) {
  11889. if (!this._vaoRecordInProgress) {
  11890. this._unbindVertexArrayObject();
  11891. }
  11892. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  11893. };
  11894. Engine.prototype.bindUniformBuffer = function (buffer) {
  11895. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  11896. };
  11897. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  11898. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  11899. };
  11900. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  11901. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  11902. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  11903. };
  11904. ;
  11905. Engine.prototype.bindIndexBuffer = function (buffer) {
  11906. if (!this._vaoRecordInProgress) {
  11907. this._unbindVertexArrayObject();
  11908. }
  11909. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  11910. };
  11911. Engine.prototype.bindBuffer = function (buffer, target) {
  11912. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  11913. this._gl.bindBuffer(target, buffer);
  11914. this._currentBoundBuffer[target] = buffer;
  11915. }
  11916. };
  11917. Engine.prototype.updateArrayBuffer = function (data) {
  11918. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  11919. };
  11920. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  11921. var pointer = this._currentBufferPointers[indx];
  11922. var changed = false;
  11923. if (!pointer.active) {
  11924. changed = true;
  11925. pointer.active = true;
  11926. pointer.index = indx;
  11927. pointer.size = size;
  11928. pointer.type = type;
  11929. pointer.normalized = normalized;
  11930. pointer.stride = stride;
  11931. pointer.offset = offset;
  11932. pointer.buffer = buffer;
  11933. }
  11934. else {
  11935. if (pointer.buffer !== buffer) {
  11936. pointer.buffer = buffer;
  11937. changed = true;
  11938. }
  11939. if (pointer.size !== size) {
  11940. pointer.size = size;
  11941. changed = true;
  11942. }
  11943. if (pointer.type !== type) {
  11944. pointer.type = type;
  11945. changed = true;
  11946. }
  11947. if (pointer.normalized !== normalized) {
  11948. pointer.normalized = normalized;
  11949. changed = true;
  11950. }
  11951. if (pointer.stride !== stride) {
  11952. pointer.stride = stride;
  11953. changed = true;
  11954. }
  11955. if (pointer.offset !== offset) {
  11956. pointer.offset = offset;
  11957. changed = true;
  11958. }
  11959. }
  11960. if (changed || this._vaoRecordInProgress) {
  11961. this.bindArrayBuffer(buffer);
  11962. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  11963. }
  11964. };
  11965. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  11966. if (indexBuffer == null) {
  11967. return;
  11968. }
  11969. if (this._cachedIndexBuffer !== indexBuffer) {
  11970. this._cachedIndexBuffer = indexBuffer;
  11971. this.bindIndexBuffer(indexBuffer);
  11972. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  11973. }
  11974. };
  11975. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  11976. var attributes = effect.getAttributesNames();
  11977. if (!this._vaoRecordInProgress) {
  11978. this._unbindVertexArrayObject();
  11979. }
  11980. this.unbindAllAttributes();
  11981. for (var index = 0; index < attributes.length; index++) {
  11982. var order = effect.getAttributeLocation(index);
  11983. if (order >= 0) {
  11984. var vertexBuffer = vertexBuffers[attributes[index]];
  11985. if (!vertexBuffer) {
  11986. continue;
  11987. }
  11988. this._gl.enableVertexAttribArray(order);
  11989. if (!this._vaoRecordInProgress) {
  11990. this._vertexAttribArraysEnabled[order] = true;
  11991. }
  11992. var buffer = vertexBuffer.getBuffer();
  11993. if (buffer) {
  11994. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  11995. if (vertexBuffer.getIsInstanced()) {
  11996. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  11997. if (!this._vaoRecordInProgress) {
  11998. this._currentInstanceLocations.push(order);
  11999. this._currentInstanceBuffers.push(buffer);
  12000. }
  12001. }
  12002. }
  12003. }
  12004. }
  12005. };
  12006. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  12007. var vao = this._gl.createVertexArray();
  12008. this._vaoRecordInProgress = true;
  12009. this._gl.bindVertexArray(vao);
  12010. this._mustWipeVertexAttributes = true;
  12011. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  12012. this.bindIndexBuffer(indexBuffer);
  12013. this._vaoRecordInProgress = false;
  12014. this._gl.bindVertexArray(null);
  12015. return vao;
  12016. };
  12017. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  12018. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  12019. this._cachedVertexArrayObject = vertexArrayObject;
  12020. this._gl.bindVertexArray(vertexArrayObject);
  12021. this._cachedVertexBuffers = null;
  12022. this._cachedIndexBuffer = null;
  12023. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  12024. this._mustWipeVertexAttributes = true;
  12025. }
  12026. };
  12027. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  12028. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  12029. this._cachedVertexBuffers = vertexBuffer;
  12030. this._cachedEffectForVertexBuffers = effect;
  12031. var attributesCount = effect.getAttributesCount();
  12032. this._unbindVertexArrayObject();
  12033. this.unbindAllAttributes();
  12034. var offset = 0;
  12035. for (var index = 0; index < attributesCount; index++) {
  12036. if (index < vertexDeclaration.length) {
  12037. var order = effect.getAttributeLocation(index);
  12038. if (order >= 0) {
  12039. this._gl.enableVertexAttribArray(order);
  12040. this._vertexAttribArraysEnabled[order] = true;
  12041. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  12042. }
  12043. offset += vertexDeclaration[index] * 4;
  12044. }
  12045. }
  12046. }
  12047. this._bindIndexBufferWithCache(indexBuffer);
  12048. };
  12049. Engine.prototype._unbindVertexArrayObject = function () {
  12050. if (!this._cachedVertexArrayObject) {
  12051. return;
  12052. }
  12053. this._cachedVertexArrayObject = null;
  12054. this._gl.bindVertexArray(null);
  12055. };
  12056. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  12057. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  12058. this._cachedVertexBuffers = vertexBuffers;
  12059. this._cachedEffectForVertexBuffers = effect;
  12060. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  12061. }
  12062. this._bindIndexBufferWithCache(indexBuffer);
  12063. };
  12064. Engine.prototype.unbindInstanceAttributes = function () {
  12065. var boundBuffer;
  12066. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  12067. var instancesBuffer = this._currentInstanceBuffers[i];
  12068. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  12069. boundBuffer = instancesBuffer;
  12070. this.bindArrayBuffer(instancesBuffer);
  12071. }
  12072. var offsetLocation = this._currentInstanceLocations[i];
  12073. this._gl.vertexAttribDivisor(offsetLocation, 0);
  12074. }
  12075. this._currentInstanceBuffers.length = 0;
  12076. this._currentInstanceLocations.length = 0;
  12077. };
  12078. Engine.prototype.releaseVertexArrayObject = function (vao) {
  12079. this._gl.deleteVertexArray(vao);
  12080. };
  12081. Engine.prototype._releaseBuffer = function (buffer) {
  12082. buffer.references--;
  12083. if (buffer.references === 0) {
  12084. this._gl.deleteBuffer(buffer);
  12085. return true;
  12086. }
  12087. return false;
  12088. };
  12089. Engine.prototype.createInstancesBuffer = function (capacity) {
  12090. var buffer = this._gl.createBuffer();
  12091. if (!buffer) {
  12092. throw new Error("Unable to create instance buffer");
  12093. }
  12094. buffer.capacity = capacity;
  12095. this.bindArrayBuffer(buffer);
  12096. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  12097. return buffer;
  12098. };
  12099. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  12100. this._gl.deleteBuffer(buffer);
  12101. };
  12102. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  12103. this.bindArrayBuffer(instancesBuffer);
  12104. if (data) {
  12105. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  12106. }
  12107. if (offsetLocations[0].index !== undefined) {
  12108. var stride = 0;
  12109. for (var i = 0; i < offsetLocations.length; i++) {
  12110. var ai = offsetLocations[i];
  12111. stride += ai.attributeSize * 4;
  12112. }
  12113. for (var i = 0; i < offsetLocations.length; i++) {
  12114. var ai = offsetLocations[i];
  12115. if (!this._vertexAttribArraysEnabled[ai.index]) {
  12116. this._gl.enableVertexAttribArray(ai.index);
  12117. this._vertexAttribArraysEnabled[ai.index] = true;
  12118. }
  12119. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  12120. this._gl.vertexAttribDivisor(ai.index, 1);
  12121. this._currentInstanceLocations.push(ai.index);
  12122. this._currentInstanceBuffers.push(instancesBuffer);
  12123. }
  12124. }
  12125. else {
  12126. for (var index = 0; index < 4; index++) {
  12127. var offsetLocation = offsetLocations[index];
  12128. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  12129. this._gl.enableVertexAttribArray(offsetLocation);
  12130. this._vertexAttribArraysEnabled[offsetLocation] = true;
  12131. }
  12132. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  12133. this._gl.vertexAttribDivisor(offsetLocation, 1);
  12134. this._currentInstanceLocations.push(offsetLocation);
  12135. this._currentInstanceBuffers.push(instancesBuffer);
  12136. }
  12137. }
  12138. };
  12139. Engine.prototype.applyStates = function () {
  12140. this._depthCullingState.apply(this._gl);
  12141. this._stencilState.apply(this._gl);
  12142. this._alphaState.apply(this._gl);
  12143. };
  12144. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  12145. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  12146. };
  12147. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  12148. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  12149. };
  12150. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  12151. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  12152. };
  12153. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  12154. // Apply states
  12155. this.applyStates();
  12156. this._drawCalls.addCount(1, false);
  12157. // Render
  12158. var drawMode = this.DrawMode(fillMode);
  12159. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  12160. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  12161. if (instancesCount) {
  12162. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  12163. }
  12164. else {
  12165. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  12166. }
  12167. };
  12168. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  12169. // Apply states
  12170. this.applyStates();
  12171. this._drawCalls.addCount(1, false);
  12172. var drawMode = this.DrawMode(fillMode);
  12173. if (instancesCount) {
  12174. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  12175. }
  12176. else {
  12177. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  12178. }
  12179. };
  12180. Engine.prototype.DrawMode = function (fillMode) {
  12181. switch (fillMode) {
  12182. // Triangle views
  12183. case BABYLON.Material.TriangleFillMode:
  12184. return this._gl.TRIANGLES;
  12185. case BABYLON.Material.PointFillMode:
  12186. return this._gl.POINTS;
  12187. case BABYLON.Material.WireFrameFillMode:
  12188. return this._gl.LINES;
  12189. // Draw modes
  12190. case BABYLON.Material.PointListDrawMode:
  12191. return this._gl.POINTS;
  12192. case BABYLON.Material.LineListDrawMode:
  12193. return this._gl.LINES;
  12194. case BABYLON.Material.LineLoopDrawMode:
  12195. return this._gl.LINE_LOOP;
  12196. case BABYLON.Material.LineStripDrawMode:
  12197. return this._gl.LINE_STRIP;
  12198. case BABYLON.Material.TriangleStripDrawMode:
  12199. return this._gl.TRIANGLE_STRIP;
  12200. case BABYLON.Material.TriangleFanDrawMode:
  12201. return this._gl.TRIANGLE_FAN;
  12202. default:
  12203. return this._gl.TRIANGLES;
  12204. }
  12205. };
  12206. // Shaders
  12207. Engine.prototype._releaseEffect = function (effect) {
  12208. if (this._compiledEffects[effect._key]) {
  12209. delete this._compiledEffects[effect._key];
  12210. this._deleteProgram(effect.getProgram());
  12211. }
  12212. };
  12213. Engine.prototype._deleteProgram = function (program) {
  12214. if (program) {
  12215. program.__SPECTOR_rebuildProgram = null;
  12216. if (program.transformFeedback) {
  12217. this.deleteTransformFeedback(program.transformFeedback);
  12218. program.transformFeedback = null;
  12219. }
  12220. this._gl.deleteProgram(program);
  12221. }
  12222. };
  12223. /**
  12224. * @param baseName The base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  12225. * @param samplers An array of string used to represent textures
  12226. */
  12227. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  12228. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  12229. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  12230. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  12231. if (this._compiledEffects[name]) {
  12232. var compiledEffect = this._compiledEffects[name];
  12233. if (onCompiled && compiledEffect.isReady()) {
  12234. onCompiled(compiledEffect);
  12235. }
  12236. return compiledEffect;
  12237. }
  12238. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  12239. effect._key = name;
  12240. this._compiledEffects[name] = effect;
  12241. return effect;
  12242. };
  12243. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  12244. if (uniformsNames === void 0) { uniformsNames = []; }
  12245. if (samplers === void 0) { samplers = []; }
  12246. if (defines === void 0) { defines = ""; }
  12247. return this.createEffect({
  12248. vertex: "particles",
  12249. fragmentElement: fragmentName
  12250. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  12251. };
  12252. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  12253. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12254. context = context || this._gl;
  12255. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  12256. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  12257. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  12258. };
  12259. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  12260. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12261. context = context || this._gl;
  12262. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  12263. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n" : "";
  12264. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  12265. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  12266. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  12267. this.onAfterShaderCompilationObservable.notifyObservers(this);
  12268. return program;
  12269. };
  12270. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  12271. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12272. var shaderProgram = context.createProgram();
  12273. if (!shaderProgram) {
  12274. throw new Error("Unable to create program");
  12275. }
  12276. context.attachShader(shaderProgram, vertexShader);
  12277. context.attachShader(shaderProgram, fragmentShader);
  12278. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  12279. var transformFeedback = this.createTransformFeedback();
  12280. this.bindTransformFeedback(transformFeedback);
  12281. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  12282. shaderProgram.transformFeedback = transformFeedback;
  12283. }
  12284. context.linkProgram(shaderProgram);
  12285. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  12286. this.bindTransformFeedback(null);
  12287. }
  12288. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  12289. if (!linked) {
  12290. context.validateProgram(shaderProgram);
  12291. var error = context.getProgramInfoLog(shaderProgram);
  12292. if (error) {
  12293. throw new Error(error);
  12294. }
  12295. }
  12296. context.deleteShader(vertexShader);
  12297. context.deleteShader(fragmentShader);
  12298. return shaderProgram;
  12299. };
  12300. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  12301. var results = new Array();
  12302. for (var index = 0; index < uniformsNames.length; index++) {
  12303. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  12304. }
  12305. return results;
  12306. };
  12307. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  12308. var results = [];
  12309. for (var index = 0; index < attributesNames.length; index++) {
  12310. try {
  12311. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  12312. }
  12313. catch (e) {
  12314. results.push(-1);
  12315. }
  12316. }
  12317. return results;
  12318. };
  12319. Engine.prototype.enableEffect = function (effect) {
  12320. if (!effect) {
  12321. return;
  12322. }
  12323. // Use program
  12324. this.bindSamplers(effect);
  12325. this._currentEffect = effect;
  12326. if (effect.onBind) {
  12327. effect.onBind(effect);
  12328. }
  12329. effect.onBindObservable.notifyObservers(effect);
  12330. };
  12331. Engine.prototype.setIntArray = function (uniform, array) {
  12332. if (!uniform)
  12333. return;
  12334. this._gl.uniform1iv(uniform, array);
  12335. };
  12336. Engine.prototype.setIntArray2 = function (uniform, array) {
  12337. if (!uniform || array.length % 2 !== 0)
  12338. return;
  12339. this._gl.uniform2iv(uniform, array);
  12340. };
  12341. Engine.prototype.setIntArray3 = function (uniform, array) {
  12342. if (!uniform || array.length % 3 !== 0)
  12343. return;
  12344. this._gl.uniform3iv(uniform, array);
  12345. };
  12346. Engine.prototype.setIntArray4 = function (uniform, array) {
  12347. if (!uniform || array.length % 4 !== 0)
  12348. return;
  12349. this._gl.uniform4iv(uniform, array);
  12350. };
  12351. Engine.prototype.setFloatArray = function (uniform, array) {
  12352. if (!uniform)
  12353. return;
  12354. this._gl.uniform1fv(uniform, array);
  12355. };
  12356. Engine.prototype.setFloatArray2 = function (uniform, array) {
  12357. if (!uniform || array.length % 2 !== 0)
  12358. return;
  12359. this._gl.uniform2fv(uniform, array);
  12360. };
  12361. Engine.prototype.setFloatArray3 = function (uniform, array) {
  12362. if (!uniform || array.length % 3 !== 0)
  12363. return;
  12364. this._gl.uniform3fv(uniform, array);
  12365. };
  12366. Engine.prototype.setFloatArray4 = function (uniform, array) {
  12367. if (!uniform || array.length % 4 !== 0)
  12368. return;
  12369. this._gl.uniform4fv(uniform, array);
  12370. };
  12371. Engine.prototype.setArray = function (uniform, array) {
  12372. if (!uniform)
  12373. return;
  12374. this._gl.uniform1fv(uniform, array);
  12375. };
  12376. Engine.prototype.setArray2 = function (uniform, array) {
  12377. if (!uniform || array.length % 2 !== 0)
  12378. return;
  12379. this._gl.uniform2fv(uniform, array);
  12380. };
  12381. Engine.prototype.setArray3 = function (uniform, array) {
  12382. if (!uniform || array.length % 3 !== 0)
  12383. return;
  12384. this._gl.uniform3fv(uniform, array);
  12385. };
  12386. Engine.prototype.setArray4 = function (uniform, array) {
  12387. if (!uniform || array.length % 4 !== 0)
  12388. return;
  12389. this._gl.uniform4fv(uniform, array);
  12390. };
  12391. Engine.prototype.setMatrices = function (uniform, matrices) {
  12392. if (!uniform)
  12393. return;
  12394. this._gl.uniformMatrix4fv(uniform, false, matrices);
  12395. };
  12396. Engine.prototype.setMatrix = function (uniform, matrix) {
  12397. if (!uniform)
  12398. return;
  12399. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  12400. };
  12401. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  12402. if (!uniform)
  12403. return;
  12404. this._gl.uniformMatrix3fv(uniform, false, matrix);
  12405. };
  12406. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  12407. if (!uniform)
  12408. return;
  12409. this._gl.uniformMatrix2fv(uniform, false, matrix);
  12410. };
  12411. Engine.prototype.setInt = function (uniform, value) {
  12412. if (!uniform)
  12413. return;
  12414. this._gl.uniform1i(uniform, value);
  12415. };
  12416. Engine.prototype.setFloat = function (uniform, value) {
  12417. if (!uniform)
  12418. return;
  12419. this._gl.uniform1f(uniform, value);
  12420. };
  12421. Engine.prototype.setFloat2 = function (uniform, x, y) {
  12422. if (!uniform)
  12423. return;
  12424. this._gl.uniform2f(uniform, x, y);
  12425. };
  12426. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  12427. if (!uniform)
  12428. return;
  12429. this._gl.uniform3f(uniform, x, y, z);
  12430. };
  12431. Engine.prototype.setBool = function (uniform, bool) {
  12432. if (!uniform)
  12433. return;
  12434. this._gl.uniform1i(uniform, bool);
  12435. };
  12436. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  12437. if (!uniform)
  12438. return;
  12439. this._gl.uniform4f(uniform, x, y, z, w);
  12440. };
  12441. Engine.prototype.setColor3 = function (uniform, color3) {
  12442. if (!uniform)
  12443. return;
  12444. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  12445. };
  12446. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  12447. if (!uniform)
  12448. return;
  12449. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  12450. };
  12451. // States
  12452. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  12453. if (zOffset === void 0) { zOffset = 0; }
  12454. if (reverseSide === void 0) { reverseSide = false; }
  12455. // Culling
  12456. if (this._depthCullingState.cull !== culling || force) {
  12457. this._depthCullingState.cull = culling;
  12458. }
  12459. // Cull face
  12460. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  12461. if (this._depthCullingState.cullFace !== cullFace || force) {
  12462. this._depthCullingState.cullFace = cullFace;
  12463. }
  12464. // Z offset
  12465. this.setZOffset(zOffset);
  12466. // Front face
  12467. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  12468. if (this._depthCullingState.frontFace !== frontFace || force) {
  12469. this._depthCullingState.frontFace = frontFace;
  12470. }
  12471. };
  12472. Engine.prototype.setZOffset = function (value) {
  12473. this._depthCullingState.zOffset = value;
  12474. };
  12475. Engine.prototype.getZOffset = function () {
  12476. return this._depthCullingState.zOffset;
  12477. };
  12478. Engine.prototype.setDepthBuffer = function (enable) {
  12479. this._depthCullingState.depthTest = enable;
  12480. };
  12481. Engine.prototype.getDepthWrite = function () {
  12482. return this._depthCullingState.depthMask;
  12483. };
  12484. Engine.prototype.setDepthWrite = function (enable) {
  12485. this._depthCullingState.depthMask = enable;
  12486. };
  12487. Engine.prototype.setColorWrite = function (enable) {
  12488. this._gl.colorMask(enable, enable, enable, enable);
  12489. this._colorWrite = enable;
  12490. };
  12491. Engine.prototype.getColorWrite = function () {
  12492. return this._colorWrite;
  12493. };
  12494. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  12495. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  12496. };
  12497. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  12498. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  12499. if (this._alphaMode === mode) {
  12500. return;
  12501. }
  12502. switch (mode) {
  12503. case Engine.ALPHA_DISABLE:
  12504. this._alphaState.alphaBlend = false;
  12505. break;
  12506. case Engine.ALPHA_PREMULTIPLIED:
  12507. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  12508. this._alphaState.alphaBlend = true;
  12509. break;
  12510. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  12511. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  12512. this._alphaState.alphaBlend = true;
  12513. break;
  12514. case Engine.ALPHA_COMBINE:
  12515. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  12516. this._alphaState.alphaBlend = true;
  12517. break;
  12518. case Engine.ALPHA_ONEONE:
  12519. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  12520. this._alphaState.alphaBlend = true;
  12521. break;
  12522. case Engine.ALPHA_ADD:
  12523. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  12524. this._alphaState.alphaBlend = true;
  12525. break;
  12526. case Engine.ALPHA_SUBTRACT:
  12527. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  12528. this._alphaState.alphaBlend = true;
  12529. break;
  12530. case Engine.ALPHA_MULTIPLY:
  12531. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  12532. this._alphaState.alphaBlend = true;
  12533. break;
  12534. case Engine.ALPHA_MAXIMIZED:
  12535. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  12536. this._alphaState.alphaBlend = true;
  12537. break;
  12538. case Engine.ALPHA_INTERPOLATE:
  12539. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  12540. this._alphaState.alphaBlend = true;
  12541. break;
  12542. case Engine.ALPHA_SCREENMODE:
  12543. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  12544. this._alphaState.alphaBlend = true;
  12545. break;
  12546. }
  12547. if (!noDepthWriteChange) {
  12548. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  12549. }
  12550. this._alphaMode = mode;
  12551. };
  12552. Engine.prototype.getAlphaMode = function () {
  12553. return this._alphaMode;
  12554. };
  12555. // Textures
  12556. Engine.prototype.wipeCaches = function (bruteForce) {
  12557. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  12558. return;
  12559. }
  12560. this._currentEffect = null;
  12561. // 6/8/2017: deltakosh: Should not be required anymore.
  12562. // This message is then mostly for the future myself who will scream out loud when seeing that it was actually required :)
  12563. if (bruteForce) {
  12564. this.resetTextureCache();
  12565. this._currentProgram = null;
  12566. this._stencilState.reset();
  12567. this._depthCullingState.reset();
  12568. this.setDepthFunctionToLessOrEqual();
  12569. this._alphaState.reset();
  12570. }
  12571. this._resetVertexBufferBinding();
  12572. this._cachedIndexBuffer = null;
  12573. this._cachedEffectForVertexBuffers = null;
  12574. this._unbindVertexArrayObject();
  12575. this.bindIndexBuffer(null);
  12576. };
  12577. /**
  12578. * Set the compressed texture format to use, based on the formats you have, and the formats
  12579. * supported by the hardware / browser.
  12580. *
  12581. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  12582. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  12583. * to API arguments needed to compressed textures. This puts the burden on the container
  12584. * generator to house the arcane code for determining these for current & future formats.
  12585. *
  12586. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  12587. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  12588. *
  12589. * Note: The result of this call is not taken into account when a texture is base64.
  12590. *
  12591. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  12592. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  12593. *
  12594. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  12595. * @returns The extension selected.
  12596. */
  12597. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  12598. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  12599. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  12600. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  12601. return this._textureFormatInUse = this._texturesSupported[i];
  12602. }
  12603. }
  12604. }
  12605. // actively set format to nothing, to allow this to be called more than once
  12606. // and possibly fail the 2nd time
  12607. this._textureFormatInUse = null;
  12608. return null;
  12609. };
  12610. Engine.prototype._createTexture = function () {
  12611. var texture = this._gl.createTexture();
  12612. if (!texture) {
  12613. throw new Error("Unable to create texture");
  12614. }
  12615. return texture;
  12616. };
  12617. /**
  12618. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  12619. * @param {string} urlArg- This contains one of the following:
  12620. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  12621. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  12622. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  12623. *
  12624. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  12625. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  12626. * @param {Scene} scene- Needed for loading to the correct scene.
  12627. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  12628. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  12629. * @param {callback} onError- Optional callback to be called upon failure.
  12630. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  12631. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  12632. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  12633. *
  12634. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  12635. */
  12636. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  12637. var _this = this;
  12638. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  12639. if (onLoad === void 0) { onLoad = null; }
  12640. if (onError === void 0) { onError = null; }
  12641. if (buffer === void 0) { buffer = null; }
  12642. if (fallBack === void 0) { fallBack = null; }
  12643. if (format === void 0) { format = null; }
  12644. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  12645. var fromData = url.substr(0, 5) === "data:";
  12646. var fromBlob = url.substr(0, 5) === "blob:";
  12647. var isBase64 = fromData && url.indexOf("base64") !== -1;
  12648. var texture = fallBack ? fallBack : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  12649. // establish the file extension, if possible
  12650. var lastDot = url.lastIndexOf('.');
  12651. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  12652. var isDDS = this.getCaps().s3tc && (extension.indexOf(".dds") === 0);
  12653. var isTGA = (extension.indexOf(".tga") === 0);
  12654. // determine if a ktx file should be substituted
  12655. var isKTX = false;
  12656. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  12657. url = url.substring(0, lastDot) + this._textureFormatInUse;
  12658. isKTX = true;
  12659. }
  12660. if (scene) {
  12661. scene._addPendingData(texture);
  12662. }
  12663. texture.url = url;
  12664. texture.generateMipMaps = !noMipmap;
  12665. texture.samplingMode = samplingMode;
  12666. texture.invertY = invertY;
  12667. if (!this._doNotHandleContextLost) {
  12668. // Keep a link to the buffer only if we plan to handle context lost
  12669. texture._buffer = buffer;
  12670. }
  12671. var onLoadObserver = null;
  12672. if (onLoad && !fallBack) {
  12673. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  12674. }
  12675. if (!fallBack)
  12676. this._internalTexturesCache.push(texture);
  12677. var onerror = function (message, exception) {
  12678. if (scene) {
  12679. scene._removePendingData(texture);
  12680. }
  12681. if (onLoadObserver) {
  12682. texture.onLoadedObservable.remove(onLoadObserver);
  12683. }
  12684. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  12685. if (isKTX) {
  12686. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  12687. }
  12688. else if (BABYLON.Tools.UseFallbackTexture) {
  12689. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  12690. }
  12691. if (onError) {
  12692. onError(message || "Unknown error", exception);
  12693. }
  12694. };
  12695. var callback = null;
  12696. // processing for non-image formats
  12697. if (isKTX || isTGA || isDDS) {
  12698. if (isKTX) {
  12699. callback = function (data) {
  12700. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  12701. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  12702. ktx.uploadLevels(_this._gl, !noMipmap);
  12703. return false;
  12704. }, samplingMode);
  12705. };
  12706. }
  12707. else if (isTGA) {
  12708. callback = function (arrayBuffer) {
  12709. var data = new Uint8Array(arrayBuffer);
  12710. var header = BABYLON.TGATools.GetTGAHeader(data);
  12711. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  12712. BABYLON.TGATools.UploadContent(_this._gl, data);
  12713. return false;
  12714. }, samplingMode);
  12715. };
  12716. }
  12717. else if (isDDS) {
  12718. callback = function (data) {
  12719. var info = BABYLON.DDSTools.GetDDSInfo(data);
  12720. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  12721. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  12722. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  12723. return false;
  12724. }, samplingMode);
  12725. };
  12726. }
  12727. if (!buffer) {
  12728. this._loadFile(url, function (data) {
  12729. if (callback) {
  12730. callback(data);
  12731. }
  12732. }, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  12733. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  12734. });
  12735. }
  12736. else {
  12737. if (callback) {
  12738. callback(buffer);
  12739. }
  12740. }
  12741. // image format processing
  12742. }
  12743. else {
  12744. var onload = function (img) {
  12745. if (fromBlob && !_this._doNotHandleContextLost) {
  12746. // We need to store the image if we need to rebuild the texture
  12747. // in case of a webgl context lost
  12748. texture._buffer = img;
  12749. }
  12750. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  12751. var gl = _this._gl;
  12752. var isPot = (img.width === potWidth && img.height === potHeight);
  12753. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  12754. if (isPot) {
  12755. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  12756. return false;
  12757. }
  12758. // Using shaders to rescale because canvas.drawImage is lossy
  12759. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  12760. _this._bindTextureDirectly(gl.TEXTURE_2D, source, true);
  12761. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  12762. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  12763. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  12764. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  12765. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  12766. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  12767. _this._releaseTexture(source);
  12768. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  12769. continuationCallback();
  12770. });
  12771. return true;
  12772. }, samplingMode);
  12773. };
  12774. if (!fromData || isBase64)
  12775. if (buffer instanceof HTMLImageElement) {
  12776. onload(buffer);
  12777. }
  12778. else {
  12779. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  12780. }
  12781. else if (buffer instanceof Array || typeof buffer === "string" || buffer instanceof ArrayBuffer)
  12782. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  12783. else
  12784. onload(buffer);
  12785. }
  12786. return texture;
  12787. };
  12788. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  12789. var _this = this;
  12790. var rtt = this.createRenderTargetTexture({
  12791. width: destination.width,
  12792. height: destination.height,
  12793. }, {
  12794. generateMipMaps: false,
  12795. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  12796. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  12797. generateDepthBuffer: false,
  12798. generateStencilBuffer: false
  12799. });
  12800. if (!this._rescalePostProcess) {
  12801. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  12802. }
  12803. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  12804. _this._rescalePostProcess.onApply = function (effect) {
  12805. effect._bindTexture("textureSampler", source);
  12806. };
  12807. var hostingScene = scene;
  12808. if (!hostingScene) {
  12809. hostingScene = _this.scenes[_this.scenes.length - 1];
  12810. }
  12811. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  12812. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  12813. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  12814. _this.unBindFramebuffer(rtt);
  12815. _this._releaseTexture(rtt);
  12816. if (onComplete) {
  12817. onComplete();
  12818. }
  12819. });
  12820. };
  12821. Engine.prototype._getInternalFormat = function (format) {
  12822. var internalFormat = this._gl.RGBA;
  12823. switch (format) {
  12824. case Engine.TEXTUREFORMAT_ALPHA:
  12825. internalFormat = this._gl.ALPHA;
  12826. break;
  12827. case Engine.TEXTUREFORMAT_LUMINANCE:
  12828. internalFormat = this._gl.LUMINANCE;
  12829. break;
  12830. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  12831. internalFormat = this._gl.LUMINANCE_ALPHA;
  12832. break;
  12833. case Engine.TEXTUREFORMAT_RGB:
  12834. internalFormat = this._gl.RGB;
  12835. break;
  12836. case Engine.TEXTUREFORMAT_RGBA:
  12837. internalFormat = this._gl.RGBA;
  12838. break;
  12839. }
  12840. return internalFormat;
  12841. };
  12842. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  12843. if (compression === void 0) { compression = null; }
  12844. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  12845. if (!texture) {
  12846. return;
  12847. }
  12848. var internalFormat = this._getInternalFormat(format);
  12849. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  12850. var textureType = this._getWebGLTextureType(type);
  12851. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  12852. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  12853. if (!this._doNotHandleContextLost) {
  12854. texture._bufferView = data;
  12855. texture.format = format;
  12856. texture.type = type;
  12857. texture.invertY = invertY;
  12858. texture._compression = compression;
  12859. }
  12860. if (texture.width % 4 !== 0) {
  12861. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  12862. }
  12863. if (compression && data) {
  12864. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  12865. }
  12866. else {
  12867. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  12868. }
  12869. if (texture.generateMipMaps) {
  12870. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  12871. }
  12872. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  12873. // this.resetTextureCache();
  12874. texture.isReady = true;
  12875. };
  12876. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  12877. if (compression === void 0) { compression = null; }
  12878. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  12879. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  12880. texture.baseWidth = width;
  12881. texture.baseHeight = height;
  12882. texture.width = width;
  12883. texture.height = height;
  12884. texture.format = format;
  12885. texture.generateMipMaps = generateMipMaps;
  12886. texture.samplingMode = samplingMode;
  12887. texture.invertY = invertY;
  12888. texture._compression = compression;
  12889. texture.type = type;
  12890. if (!this._doNotHandleContextLost) {
  12891. texture._bufferView = data;
  12892. }
  12893. this.updateRawTexture(texture, data, format, invertY, compression, type);
  12894. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  12895. // Filters
  12896. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  12897. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  12898. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  12899. if (generateMipMaps) {
  12900. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  12901. }
  12902. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  12903. this._internalTexturesCache.push(texture);
  12904. return texture;
  12905. };
  12906. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  12907. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  12908. texture.baseWidth = width;
  12909. texture.baseHeight = height;
  12910. if (generateMipMaps) {
  12911. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  12912. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  12913. }
  12914. // this.resetTextureCache();
  12915. texture.width = width;
  12916. texture.height = height;
  12917. texture.isReady = false;
  12918. texture.generateMipMaps = generateMipMaps;
  12919. texture.samplingMode = samplingMode;
  12920. this.updateTextureSamplingMode(samplingMode, texture);
  12921. this._internalTexturesCache.push(texture);
  12922. return texture;
  12923. };
  12924. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  12925. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  12926. if (texture.isCube) {
  12927. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  12928. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  12929. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  12930. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  12931. }
  12932. else if (texture.is3D) {
  12933. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  12934. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  12935. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  12936. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  12937. }
  12938. else {
  12939. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  12940. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  12941. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  12942. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  12943. }
  12944. texture.samplingMode = samplingMode;
  12945. };
  12946. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  12947. if (premulAlpha === void 0) { premulAlpha = false; }
  12948. if (!texture) {
  12949. return;
  12950. }
  12951. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  12952. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  12953. if (premulAlpha) {
  12954. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  12955. }
  12956. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  12957. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  12958. if (texture.generateMipMaps) {
  12959. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  12960. }
  12961. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  12962. if (premulAlpha) {
  12963. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  12964. }
  12965. texture.isReady = true;
  12966. };
  12967. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  12968. if (!texture || texture._isDisabled) {
  12969. return;
  12970. }
  12971. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  12972. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  12973. try {
  12974. // Testing video texture support
  12975. if (this._videoTextureSupported === undefined) {
  12976. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  12977. if (this._gl.getError() !== 0) {
  12978. this._videoTextureSupported = false;
  12979. }
  12980. else {
  12981. this._videoTextureSupported = true;
  12982. }
  12983. }
  12984. // Copy video through the current working canvas if video texture is not supported
  12985. if (!this._videoTextureSupported) {
  12986. if (!texture._workingCanvas) {
  12987. texture._workingCanvas = document.createElement("canvas");
  12988. var context = texture._workingCanvas.getContext("2d");
  12989. if (!context) {
  12990. throw new Error("Unable to get 2d context");
  12991. }
  12992. texture._workingContext = context;
  12993. texture._workingCanvas.width = texture.width;
  12994. texture._workingCanvas.height = texture.height;
  12995. }
  12996. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  12997. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  12998. }
  12999. else {
  13000. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  13001. }
  13002. if (texture.generateMipMaps) {
  13003. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13004. }
  13005. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13006. // this.resetTextureCache();
  13007. texture.isReady = true;
  13008. }
  13009. catch (ex) {
  13010. // Something unexpected
  13011. // Let's disable the texture
  13012. texture._isDisabled = true;
  13013. }
  13014. };
  13015. Engine.prototype.createRenderTargetTexture = function (size, options) {
  13016. var fullOptions = new RenderTargetCreationOptions();
  13017. if (options !== undefined && typeof options === "object") {
  13018. fullOptions.generateMipMaps = options.generateMipMaps;
  13019. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  13020. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  13021. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  13022. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  13023. }
  13024. else {
  13025. fullOptions.generateMipMaps = options;
  13026. fullOptions.generateDepthBuffer = true;
  13027. fullOptions.generateStencilBuffer = false;
  13028. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13029. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  13030. }
  13031. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  13032. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  13033. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13034. }
  13035. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  13036. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  13037. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13038. }
  13039. var gl = this._gl;
  13040. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  13041. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13042. var width = size.width || size;
  13043. var height = size.height || size;
  13044. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  13045. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  13046. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13047. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  13048. }
  13049. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  13050. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  13051. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13052. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13053. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type), width, height, 0, gl.RGBA, this._getWebGLTextureType(fullOptions.type), null);
  13054. // Create the framebuffer
  13055. var framebuffer = gl.createFramebuffer();
  13056. this.bindUnboundFramebuffer(framebuffer);
  13057. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  13058. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  13059. if (fullOptions.generateMipMaps) {
  13060. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13061. }
  13062. // Unbind
  13063. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13064. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13065. this.bindUnboundFramebuffer(null);
  13066. texture._framebuffer = framebuffer;
  13067. texture.baseWidth = width;
  13068. texture.baseHeight = height;
  13069. texture.width = width;
  13070. texture.height = height;
  13071. texture.isReady = true;
  13072. texture.samples = 1;
  13073. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  13074. texture.samplingMode = fullOptions.samplingMode;
  13075. texture.type = fullOptions.type;
  13076. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  13077. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  13078. // this.resetTextureCache();
  13079. this._internalTexturesCache.push(texture);
  13080. return texture;
  13081. };
  13082. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  13083. var generateMipMaps = false;
  13084. var generateDepthBuffer = true;
  13085. var generateStencilBuffer = false;
  13086. var generateDepthTexture = false;
  13087. var textureCount = 1;
  13088. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  13089. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  13090. var types = [], samplingModes = [];
  13091. if (options !== undefined) {
  13092. generateMipMaps = options.generateMipMaps;
  13093. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  13094. generateStencilBuffer = options.generateStencilBuffer;
  13095. generateDepthTexture = options.generateDepthTexture;
  13096. textureCount = options.textureCount || 1;
  13097. if (options.types) {
  13098. types = options.types;
  13099. }
  13100. if (options.samplingModes) {
  13101. samplingModes = options.samplingModes;
  13102. }
  13103. }
  13104. var gl = this._gl;
  13105. // Create the framebuffer
  13106. var framebuffer = gl.createFramebuffer();
  13107. this.bindUnboundFramebuffer(framebuffer);
  13108. var width = size.width || size;
  13109. var height = size.height || size;
  13110. var textures = [];
  13111. var attachments = [];
  13112. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  13113. for (var i = 0; i < textureCount; i++) {
  13114. var samplingMode = samplingModes[i] || defaultSamplingMode;
  13115. var type = types[i] || defaultType;
  13116. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  13117. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  13118. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13119. }
  13120. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  13121. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  13122. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13123. }
  13124. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  13125. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  13126. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13127. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  13128. }
  13129. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  13130. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13131. textures.push(texture);
  13132. attachments.push(attachment);
  13133. gl.activeTexture(gl["TEXTURE" + i]);
  13134. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  13135. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  13136. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  13137. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13138. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13139. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  13140. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  13141. if (generateMipMaps) {
  13142. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13143. }
  13144. // Unbind
  13145. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13146. texture._framebuffer = framebuffer;
  13147. texture._depthStencilBuffer = depthStencilBuffer;
  13148. texture.baseWidth = width;
  13149. texture.baseHeight = height;
  13150. texture.width = width;
  13151. texture.height = height;
  13152. texture.isReady = true;
  13153. texture.samples = 1;
  13154. texture.generateMipMaps = generateMipMaps;
  13155. texture.samplingMode = samplingMode;
  13156. texture.type = type;
  13157. texture._generateDepthBuffer = generateDepthBuffer;
  13158. texture._generateStencilBuffer = generateStencilBuffer;
  13159. texture._attachments = attachments;
  13160. this._internalTexturesCache.push(texture);
  13161. }
  13162. if (generateDepthTexture && this._caps.depthTextureExtension) {
  13163. // Depth texture
  13164. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  13165. gl.activeTexture(gl.TEXTURE0);
  13166. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  13167. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  13168. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  13169. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13170. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13171. 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);
  13172. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  13173. depthTexture._framebuffer = framebuffer;
  13174. depthTexture.baseWidth = width;
  13175. depthTexture.baseHeight = height;
  13176. depthTexture.width = width;
  13177. depthTexture.height = height;
  13178. depthTexture.isReady = true;
  13179. depthTexture.samples = 1;
  13180. depthTexture.generateMipMaps = generateMipMaps;
  13181. depthTexture.samplingMode = gl.NEAREST;
  13182. depthTexture._generateDepthBuffer = generateDepthBuffer;
  13183. depthTexture._generateStencilBuffer = generateStencilBuffer;
  13184. textures.push(depthTexture);
  13185. this._internalTexturesCache.push(depthTexture);
  13186. }
  13187. gl.drawBuffers(attachments);
  13188. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13189. this.bindUnboundFramebuffer(null);
  13190. this.resetTextureCache();
  13191. return textures;
  13192. };
  13193. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  13194. if (samples === void 0) { samples = 1; }
  13195. var depthStencilBuffer = null;
  13196. var gl = this._gl;
  13197. // Create the depth/stencil buffer
  13198. if (generateStencilBuffer) {
  13199. depthStencilBuffer = gl.createRenderbuffer();
  13200. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  13201. if (samples > 1) {
  13202. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  13203. }
  13204. else {
  13205. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  13206. }
  13207. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  13208. }
  13209. else if (generateDepthBuffer) {
  13210. depthStencilBuffer = gl.createRenderbuffer();
  13211. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  13212. if (samples > 1) {
  13213. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  13214. }
  13215. else {
  13216. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  13217. }
  13218. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  13219. }
  13220. return depthStencilBuffer;
  13221. };
  13222. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  13223. if (this.webGLVersion < 2 || !texture) {
  13224. return 1;
  13225. }
  13226. if (texture.samples === samples) {
  13227. return samples;
  13228. }
  13229. var gl = this._gl;
  13230. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  13231. // Dispose previous render buffers
  13232. if (texture._depthStencilBuffer) {
  13233. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  13234. texture._depthStencilBuffer = null;
  13235. }
  13236. if (texture._MSAAFramebuffer) {
  13237. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  13238. texture._MSAAFramebuffer = null;
  13239. }
  13240. if (texture._MSAARenderBuffer) {
  13241. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  13242. texture._MSAARenderBuffer = null;
  13243. }
  13244. if (samples > 1) {
  13245. var framebuffer = gl.createFramebuffer();
  13246. if (!framebuffer) {
  13247. throw new Error("Unable to create multi sampled framebuffer");
  13248. }
  13249. texture._MSAAFramebuffer = framebuffer;
  13250. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  13251. var colorRenderbuffer = gl.createRenderbuffer();
  13252. if (!colorRenderbuffer) {
  13253. throw new Error("Unable to create multi sampled framebuffer");
  13254. }
  13255. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  13256. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  13257. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  13258. texture._MSAARenderBuffer = colorRenderbuffer;
  13259. }
  13260. else {
  13261. this.bindUnboundFramebuffer(texture._framebuffer);
  13262. }
  13263. texture.samples = samples;
  13264. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  13265. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13266. this.bindUnboundFramebuffer(null);
  13267. return samples;
  13268. };
  13269. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  13270. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  13271. return 1;
  13272. }
  13273. if (textures[0].samples === samples) {
  13274. return samples;
  13275. }
  13276. var gl = this._gl;
  13277. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  13278. // Dispose previous render buffers
  13279. if (textures[0]._depthStencilBuffer) {
  13280. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  13281. textures[0]._depthStencilBuffer = null;
  13282. }
  13283. if (textures[0]._MSAAFramebuffer) {
  13284. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  13285. textures[0]._MSAAFramebuffer = null;
  13286. }
  13287. for (var i = 0; i < textures.length; i++) {
  13288. if (textures[i]._MSAARenderBuffer) {
  13289. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  13290. textures[i]._MSAARenderBuffer = null;
  13291. }
  13292. }
  13293. if (samples > 1) {
  13294. var framebuffer = gl.createFramebuffer();
  13295. if (!framebuffer) {
  13296. throw new Error("Unable to create multi sampled framebuffer");
  13297. }
  13298. this.bindUnboundFramebuffer(framebuffer);
  13299. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  13300. var attachments = [];
  13301. for (var i = 0; i < textures.length; i++) {
  13302. var texture = textures[i];
  13303. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13304. var colorRenderbuffer = gl.createRenderbuffer();
  13305. if (!colorRenderbuffer) {
  13306. throw new Error("Unable to create multi sampled framebuffer");
  13307. }
  13308. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  13309. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  13310. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  13311. texture._MSAAFramebuffer = framebuffer;
  13312. texture._MSAARenderBuffer = colorRenderbuffer;
  13313. texture.samples = samples;
  13314. texture._depthStencilBuffer = depthStencilBuffer;
  13315. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13316. attachments.push(attachment);
  13317. }
  13318. gl.drawBuffers(attachments);
  13319. }
  13320. else {
  13321. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  13322. }
  13323. this.bindUnboundFramebuffer(null);
  13324. return samples;
  13325. };
  13326. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  13327. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  13328. };
  13329. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  13330. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  13331. };
  13332. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  13333. var gl = this._gl;
  13334. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  13335. var generateMipMaps = true;
  13336. var generateDepthBuffer = true;
  13337. var generateStencilBuffer = false;
  13338. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  13339. if (options !== undefined) {
  13340. generateMipMaps = options.generateMipMaps === undefined ? true : options.generateMipMaps;
  13341. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  13342. generateStencilBuffer = (generateDepthBuffer && options.generateStencilBuffer) ? true : false;
  13343. if (options.samplingMode !== undefined) {
  13344. samplingMode = options.samplingMode;
  13345. }
  13346. }
  13347. texture.isCube = true;
  13348. texture.generateMipMaps = generateMipMaps;
  13349. texture.samples = 1;
  13350. texture.samplingMode = samplingMode;
  13351. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  13352. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13353. for (var face = 0; face < 6; face++) {
  13354. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  13355. }
  13356. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  13357. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  13358. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13359. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13360. // Create the framebuffer
  13361. var framebuffer = gl.createFramebuffer();
  13362. this.bindUnboundFramebuffer(framebuffer);
  13363. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, size, size);
  13364. // Mipmaps
  13365. if (texture.generateMipMaps) {
  13366. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13367. }
  13368. // Unbind
  13369. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13370. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13371. this.bindUnboundFramebuffer(null);
  13372. texture._framebuffer = framebuffer;
  13373. texture.width = size;
  13374. texture.height = size;
  13375. texture.isReady = true;
  13376. //this.resetTextureCache();
  13377. this._internalTexturesCache.push(texture);
  13378. return texture;
  13379. };
  13380. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension) {
  13381. var _this = this;
  13382. if (onLoad === void 0) { onLoad = null; }
  13383. if (onError === void 0) { onError = null; }
  13384. if (forcedExtension === void 0) { forcedExtension = null; }
  13385. var callback = function (loadData) {
  13386. if (!loadData) {
  13387. if (onLoad) {
  13388. onLoad(null);
  13389. }
  13390. return;
  13391. }
  13392. var texture = loadData.texture;
  13393. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  13394. texture._lodGenerationScale = scale;
  13395. texture._lodGenerationOffset = offset;
  13396. if (_this._caps.textureLOD) {
  13397. // Do not add extra process if texture lod is supported.
  13398. if (onLoad) {
  13399. onLoad(texture);
  13400. }
  13401. return;
  13402. }
  13403. var mipSlices = 3;
  13404. var gl = _this._gl;
  13405. var width = loadData.width;
  13406. if (!width) {
  13407. return;
  13408. }
  13409. var textures = [];
  13410. for (var i = 0; i < mipSlices; i++) {
  13411. //compute LOD from even spacing in smoothness (matching shader calculation)
  13412. var smoothness = i / (mipSlices - 1);
  13413. var roughness = 1 - smoothness;
  13414. var minLODIndex = offset; // roughness = 0
  13415. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  13416. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  13417. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  13418. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  13419. glTextureFromLod.isCube = true;
  13420. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  13421. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  13422. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  13423. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13424. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13425. if (loadData.isDDS) {
  13426. var info = loadData.info;
  13427. var data = loadData.data;
  13428. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  13429. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  13430. }
  13431. else {
  13432. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  13433. }
  13434. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13435. // Wrap in a base texture for easy binding.
  13436. var lodTexture = new BABYLON.BaseTexture(scene);
  13437. lodTexture.isCube = true;
  13438. lodTexture._texture = glTextureFromLod;
  13439. glTextureFromLod.isReady = true;
  13440. textures.push(lodTexture);
  13441. }
  13442. texture._lodTextureHigh = textures[2];
  13443. texture._lodTextureMid = textures[1];
  13444. texture._lodTextureLow = textures[0];
  13445. if (onLoad) {
  13446. onLoad(texture);
  13447. }
  13448. };
  13449. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension);
  13450. };
  13451. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension) {
  13452. var _this = this;
  13453. if (onLoad === void 0) { onLoad = null; }
  13454. if (onError === void 0) { onError = null; }
  13455. if (forcedExtension === void 0) { forcedExtension = null; }
  13456. var gl = this._gl;
  13457. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  13458. texture.isCube = true;
  13459. texture.url = rootUrl;
  13460. texture.generateMipMaps = !noMipmap;
  13461. if (!this._doNotHandleContextLost) {
  13462. texture._extension = forcedExtension;
  13463. texture._files = files;
  13464. }
  13465. var isKTX = false;
  13466. var isDDS = false;
  13467. var lastDot = rootUrl.lastIndexOf('.');
  13468. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  13469. if (this._textureFormatInUse) {
  13470. extension = this._textureFormatInUse;
  13471. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  13472. isKTX = true;
  13473. }
  13474. else {
  13475. isDDS = (extension === ".dds");
  13476. }
  13477. var onerror = function (request, exception) {
  13478. if (onError && request) {
  13479. onError(request.status + " " + request.statusText, exception);
  13480. }
  13481. };
  13482. if (isKTX) {
  13483. this._loadFile(rootUrl, function (data) {
  13484. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  13485. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  13486. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13487. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  13488. ktx.uploadLevels(_this._gl, !noMipmap);
  13489. _this.setCubeMapTextureParams(gl, loadMipmap);
  13490. texture.width = ktx.pixelWidth;
  13491. texture.height = ktx.pixelHeight;
  13492. texture.isReady = true;
  13493. }, undefined, undefined, true, onerror);
  13494. }
  13495. else if (isDDS) {
  13496. if (files && files.length === 6) {
  13497. this._cascadeLoadFiles(rootUrl, scene, function (imgs) {
  13498. var info;
  13499. var loadMipmap = false;
  13500. var width = 0;
  13501. for (var index = 0; index < imgs.length; index++) {
  13502. var data = imgs[index];
  13503. info = BABYLON.DDSTools.GetDDSInfo(data);
  13504. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  13505. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13506. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  13507. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6, -1, index);
  13508. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  13509. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13510. }
  13511. texture.width = info.width;
  13512. texture.height = info.height;
  13513. texture.type = info.textureType;
  13514. width = info.width;
  13515. }
  13516. _this.setCubeMapTextureParams(gl, loadMipmap);
  13517. texture.isReady = true;
  13518. if (onLoad) {
  13519. onLoad({ isDDS: true, width: width, info: info, imgs: imgs, texture: texture });
  13520. }
  13521. }, files, onError);
  13522. }
  13523. else {
  13524. this._loadFile(rootUrl, function (data) {
  13525. var info = BABYLON.DDSTools.GetDDSInfo(data);
  13526. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  13527. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13528. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  13529. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  13530. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  13531. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13532. }
  13533. _this.setCubeMapTextureParams(gl, loadMipmap);
  13534. texture.width = info.width;
  13535. texture.height = info.height;
  13536. texture.isReady = true;
  13537. texture.type = info.textureType;
  13538. if (onLoad) {
  13539. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  13540. }
  13541. }, undefined, undefined, true, onerror);
  13542. }
  13543. }
  13544. else {
  13545. if (!files) {
  13546. throw new Error("Cannot load cubemap because files were not defined");
  13547. }
  13548. cascadeLoadImgs(rootUrl, scene, function (imgs) {
  13549. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  13550. var height = width;
  13551. _this._prepareWorkingCanvas();
  13552. if (!_this._workingCanvas || !_this._workingContext) {
  13553. return;
  13554. }
  13555. _this._workingCanvas.width = width;
  13556. _this._workingCanvas.height = height;
  13557. var faces = [
  13558. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  13559. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  13560. ];
  13561. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13562. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  13563. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  13564. for (var index = 0; index < faces.length; index++) {
  13565. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  13566. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  13567. }
  13568. if (!noMipmap) {
  13569. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13570. }
  13571. _this.setCubeMapTextureParams(gl, !noMipmap);
  13572. texture.width = width;
  13573. texture.height = height;
  13574. texture.isReady = true;
  13575. if (format) {
  13576. texture.format = format;
  13577. }
  13578. texture.onLoadedObservable.notifyObservers(texture);
  13579. texture.onLoadedObservable.clear();
  13580. if (onLoad) {
  13581. onLoad();
  13582. }
  13583. }, files, onError);
  13584. }
  13585. this._internalTexturesCache.push(texture);
  13586. return texture;
  13587. };
  13588. Engine.prototype.setCubeMapTextureParams = function (gl, loadMipmap) {
  13589. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  13590. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  13591. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13592. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13593. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13594. // this.resetTextureCache();
  13595. };
  13596. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  13597. if (compression === void 0) { compression = null; }
  13598. if (level === void 0) { level = 0; }
  13599. texture._bufferViewArray = data;
  13600. texture.format = format;
  13601. texture.type = type;
  13602. texture.invertY = invertY;
  13603. texture._compression = compression;
  13604. var gl = this._gl;
  13605. var textureType = this._getWebGLTextureType(type);
  13606. var internalFormat = this._getInternalFormat(format);
  13607. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  13608. var needConversion = false;
  13609. if (internalFormat === gl.RGB) {
  13610. internalFormat = gl.RGBA;
  13611. needConversion = true;
  13612. }
  13613. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13614. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  13615. if (texture.width % 4 !== 0) {
  13616. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  13617. }
  13618. // Data are known to be in +X +Y +Z -X -Y -Z
  13619. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  13620. var faceData = data[faceIndex];
  13621. if (compression) {
  13622. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  13623. }
  13624. else {
  13625. if (needConversion) {
  13626. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  13627. }
  13628. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  13629. }
  13630. }
  13631. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  13632. if (isPot && texture.generateMipMaps && level === 0) {
  13633. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  13634. }
  13635. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  13636. // this.resetTextureCache();
  13637. texture.isReady = true;
  13638. };
  13639. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  13640. if (compression === void 0) { compression = null; }
  13641. var gl = this._gl;
  13642. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  13643. texture.isCube = true;
  13644. texture.generateMipMaps = generateMipMaps;
  13645. texture.format = format;
  13646. texture.type = type;
  13647. if (!this._doNotHandleContextLost) {
  13648. texture._bufferViewArray = data;
  13649. }
  13650. var textureType = this._getWebGLTextureType(type);
  13651. var internalFormat = this._getInternalFormat(format);
  13652. if (internalFormat === gl.RGB) {
  13653. internalFormat = gl.RGBA;
  13654. }
  13655. var width = size;
  13656. var height = width;
  13657. texture.width = width;
  13658. texture.height = height;
  13659. // Double check on POT to generate Mips.
  13660. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  13661. if (!isPot) {
  13662. generateMipMaps = false;
  13663. }
  13664. // Upload data if needed. The texture won't be ready until then.
  13665. if (data) {
  13666. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  13667. }
  13668. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  13669. // Filters
  13670. if (data && generateMipMaps) {
  13671. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  13672. }
  13673. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  13674. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  13675. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  13676. }
  13677. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  13678. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  13679. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  13680. }
  13681. else {
  13682. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  13683. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  13684. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  13685. }
  13686. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13687. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13688. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13689. return texture;
  13690. };
  13691. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError, samplingMode, invertY) {
  13692. var _this = this;
  13693. if (onLoad === void 0) { onLoad = null; }
  13694. if (onError === void 0) { onError = null; }
  13695. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  13696. if (invertY === void 0) { invertY = false; }
  13697. var gl = this._gl;
  13698. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  13699. scene._addPendingData(texture);
  13700. texture.url = url;
  13701. this._internalTexturesCache.push(texture);
  13702. var onerror = function (request, exception) {
  13703. scene._removePendingData(texture);
  13704. if (onError && request) {
  13705. onError(request.status + " " + request.statusText, exception);
  13706. }
  13707. };
  13708. var internalCallback = function (data) {
  13709. var width = texture.width;
  13710. var faceDataArrays = callback(data);
  13711. if (!faceDataArrays) {
  13712. return;
  13713. }
  13714. if (mipmmapGenerator) {
  13715. var textureType = _this._getWebGLTextureType(type);
  13716. var internalFormat = _this._getInternalFormat(format);
  13717. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  13718. var needConversion = false;
  13719. if (internalFormat === gl.RGB) {
  13720. internalFormat = gl.RGBA;
  13721. needConversion = true;
  13722. }
  13723. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13724. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  13725. var mipData = mipmmapGenerator(faceDataArrays);
  13726. for (var level = 0; level < mipData.length; level++) {
  13727. var mipSize = width >> level;
  13728. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  13729. var mipFaceData = mipData[level][faceIndex];
  13730. if (needConversion) {
  13731. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  13732. }
  13733. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  13734. }
  13735. }
  13736. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13737. }
  13738. else {
  13739. texture.generateMipMaps = !noMipmap;
  13740. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  13741. }
  13742. texture.isReady = true;
  13743. // this.resetTextureCache();
  13744. scene._removePendingData(texture);
  13745. if (onLoad) {
  13746. onLoad();
  13747. }
  13748. };
  13749. this._loadFile(url, function (data) {
  13750. internalCallback(data);
  13751. }, undefined, scene.database, true, onerror);
  13752. return texture;
  13753. };
  13754. ;
  13755. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression) {
  13756. if (compression === void 0) { compression = null; }
  13757. var internalFormat = this._getInternalFormat(format);
  13758. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  13759. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  13760. if (!this._doNotHandleContextLost) {
  13761. texture._bufferView = data;
  13762. texture.format = format;
  13763. texture.invertY = invertY;
  13764. texture._compression = compression;
  13765. }
  13766. if (texture.width % 4 !== 0) {
  13767. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  13768. }
  13769. if (compression && data) {
  13770. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  13771. }
  13772. else {
  13773. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalFormat, texture.width, texture.height, texture.depth, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  13774. }
  13775. if (texture.generateMipMaps) {
  13776. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  13777. }
  13778. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  13779. // this.resetTextureCache();
  13780. texture.isReady = true;
  13781. };
  13782. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression) {
  13783. if (compression === void 0) { compression = null; }
  13784. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  13785. texture.baseWidth = width;
  13786. texture.baseHeight = height;
  13787. texture.baseDepth = depth;
  13788. texture.width = width;
  13789. texture.height = height;
  13790. texture.depth = depth;
  13791. texture.format = format;
  13792. texture.generateMipMaps = generateMipMaps;
  13793. texture.samplingMode = samplingMode;
  13794. texture.is3D = true;
  13795. if (!this._doNotHandleContextLost) {
  13796. texture._bufferView = data;
  13797. }
  13798. this.updateRawTexture3D(texture, data, format, invertY, compression);
  13799. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  13800. // Filters
  13801. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  13802. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13803. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13804. if (generateMipMaps) {
  13805. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  13806. }
  13807. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  13808. this._internalTexturesCache.push(texture);
  13809. return texture;
  13810. };
  13811. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  13812. var gl = this._gl;
  13813. if (!gl) {
  13814. return;
  13815. }
  13816. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  13817. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  13818. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  13819. if (!noMipmap && !isCompressed) {
  13820. gl.generateMipmap(gl.TEXTURE_2D);
  13821. }
  13822. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13823. // this.resetTextureCache();
  13824. if (scene) {
  13825. scene._removePendingData(texture);
  13826. }
  13827. texture.onLoadedObservable.notifyObservers(texture);
  13828. texture.onLoadedObservable.clear();
  13829. };
  13830. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  13831. var _this = this;
  13832. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  13833. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  13834. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  13835. var gl = this._gl;
  13836. if (!gl) {
  13837. return;
  13838. }
  13839. if (!texture._webGLTexture) {
  13840. // this.resetTextureCache();
  13841. if (scene) {
  13842. scene._removePendingData(texture);
  13843. }
  13844. return;
  13845. }
  13846. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13847. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  13848. texture.baseWidth = width;
  13849. texture.baseHeight = height;
  13850. texture.width = potWidth;
  13851. texture.height = potHeight;
  13852. texture.isReady = true;
  13853. if (processFunction(potWidth, potHeight, function () {
  13854. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  13855. })) {
  13856. // Returning as texture needs extra async steps
  13857. return;
  13858. }
  13859. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  13860. };
  13861. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  13862. // Create new RGBA data container.
  13863. var rgbaData;
  13864. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  13865. rgbaData = new Float32Array(width * height * 4);
  13866. }
  13867. else {
  13868. rgbaData = new Uint32Array(width * height * 4);
  13869. }
  13870. // Convert each pixel.
  13871. for (var x = 0; x < width; x++) {
  13872. for (var y = 0; y < height; y++) {
  13873. var index = (y * width + x) * 3;
  13874. var newIndex = (y * width + x) * 4;
  13875. // Map Old Value to new value.
  13876. rgbaData[newIndex + 0] = rgbData[index + 0];
  13877. rgbaData[newIndex + 1] = rgbData[index + 1];
  13878. rgbaData[newIndex + 2] = rgbData[index + 2];
  13879. // Add fully opaque alpha channel.
  13880. rgbaData[newIndex + 3] = 1;
  13881. }
  13882. }
  13883. return rgbaData;
  13884. };
  13885. Engine.prototype._releaseFramebufferObjects = function (texture) {
  13886. var gl = this._gl;
  13887. if (texture._framebuffer) {
  13888. gl.deleteFramebuffer(texture._framebuffer);
  13889. texture._framebuffer = null;
  13890. }
  13891. if (texture._depthStencilBuffer) {
  13892. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  13893. texture._depthStencilBuffer = null;
  13894. }
  13895. if (texture._MSAAFramebuffer) {
  13896. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  13897. texture._MSAAFramebuffer = null;
  13898. }
  13899. if (texture._MSAARenderBuffer) {
  13900. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  13901. texture._MSAARenderBuffer = null;
  13902. }
  13903. };
  13904. Engine.prototype._releaseTexture = function (texture) {
  13905. var gl = this._gl;
  13906. this._releaseFramebufferObjects(texture);
  13907. gl.deleteTexture(texture._webGLTexture);
  13908. // Unbind channels
  13909. this.unbindAllTextures();
  13910. var index = this._internalTexturesCache.indexOf(texture);
  13911. if (index !== -1) {
  13912. this._internalTexturesCache.splice(index, 1);
  13913. }
  13914. // Integrated fixed lod samplers.
  13915. if (texture._lodTextureHigh) {
  13916. texture._lodTextureHigh.dispose();
  13917. }
  13918. if (texture._lodTextureMid) {
  13919. texture._lodTextureMid.dispose();
  13920. }
  13921. if (texture._lodTextureLow) {
  13922. texture._lodTextureLow.dispose();
  13923. }
  13924. };
  13925. Engine.prototype.setProgram = function (program) {
  13926. if (this._currentProgram !== program) {
  13927. this._gl.useProgram(program);
  13928. this._currentProgram = program;
  13929. }
  13930. };
  13931. Engine.prototype.bindSamplers = function (effect) {
  13932. this.setProgram(effect.getProgram());
  13933. var samplers = effect.getSamplers();
  13934. for (var index = 0; index < samplers.length; index++) {
  13935. var uniform = effect.getUniform(samplers[index]);
  13936. if (uniform) {
  13937. this._boundUniforms[index] = uniform;
  13938. }
  13939. }
  13940. this._currentEffect = null;
  13941. };
  13942. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  13943. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  13944. return;
  13945. }
  13946. // Remove
  13947. this._linkTrackers(internalTexture.previous, internalTexture.next);
  13948. // Bind last to it
  13949. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  13950. // Bind to dummy
  13951. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  13952. };
  13953. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  13954. if (!internalTexture) {
  13955. return -1;
  13956. }
  13957. internalTexture._initialSlot = channel;
  13958. if (this.disableTextureBindingOptimization) {
  13959. if (channel !== internalTexture._designatedSlot) {
  13960. this._textureCollisions.addCount(1, false);
  13961. }
  13962. }
  13963. else {
  13964. if (channel !== internalTexture._designatedSlot) {
  13965. if (internalTexture._designatedSlot > -1) {
  13966. return internalTexture._designatedSlot;
  13967. }
  13968. else {
  13969. // No slot for this texture, let's pick a new one (if we find a free slot)
  13970. if (this._nextFreeTextureSlots.length) {
  13971. return this._nextFreeTextureSlots[0];
  13972. }
  13973. // We need to recycle the oldest bound texture, sorry.
  13974. this._textureCollisions.addCount(1, false);
  13975. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  13976. }
  13977. }
  13978. }
  13979. return channel;
  13980. };
  13981. Engine.prototype._linkTrackers = function (previous, next) {
  13982. previous.next = next;
  13983. next.previous = previous;
  13984. };
  13985. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  13986. var currentSlot = internalTexture._designatedSlot;
  13987. if (currentSlot === -1) {
  13988. return -1;
  13989. }
  13990. internalTexture._designatedSlot = -1;
  13991. if (this.disableTextureBindingOptimization) {
  13992. return -1;
  13993. }
  13994. // Remove from bound list
  13995. this._linkTrackers(internalTexture.previous, internalTexture.next);
  13996. // Free the slot
  13997. this._boundTexturesCache[currentSlot] = null;
  13998. this._nextFreeTextureSlots.push(currentSlot);
  13999. return currentSlot;
  14000. };
  14001. Engine.prototype._activateCurrentTexture = function () {
  14002. if (this._currentTextureChannel !== this._activeChannel) {
  14003. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  14004. this._currentTextureChannel = this._activeChannel;
  14005. }
  14006. };
  14007. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate) {
  14008. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  14009. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  14010. this._activeChannel = texture._designatedSlot;
  14011. }
  14012. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  14013. var isTextureForRendering = texture && texture._initialSlot > -1;
  14014. if (currentTextureBound !== texture) {
  14015. if (currentTextureBound) {
  14016. this._removeDesignatedSlot(currentTextureBound);
  14017. }
  14018. this._activateCurrentTexture();
  14019. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  14020. this._boundTexturesCache[this._activeChannel] = texture;
  14021. if (texture) {
  14022. if (!this.disableTextureBindingOptimization) {
  14023. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  14024. if (slotIndex > -1) {
  14025. this._nextFreeTextureSlots.splice(slotIndex, 1);
  14026. }
  14027. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  14028. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  14029. }
  14030. texture._designatedSlot = this._activeChannel;
  14031. }
  14032. }
  14033. else if (forTextureDataUpdate) {
  14034. this._activateCurrentTexture();
  14035. }
  14036. if (isTextureForRendering && !forTextureDataUpdate) {
  14037. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  14038. }
  14039. };
  14040. Engine.prototype._bindTexture = function (channel, texture) {
  14041. if (channel < 0) {
  14042. return;
  14043. }
  14044. if (texture) {
  14045. channel = this._getCorrectTextureChannel(channel, texture);
  14046. }
  14047. this._activeChannel = channel;
  14048. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  14049. };
  14050. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  14051. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  14052. };
  14053. Engine.prototype.unbindAllTextures = function () {
  14054. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  14055. this._activeChannel = channel;
  14056. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14057. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14058. if (this.webGLVersion > 1) {
  14059. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14060. }
  14061. }
  14062. };
  14063. Engine.prototype.setTexture = function (channel, uniform, texture) {
  14064. if (channel < 0) {
  14065. return;
  14066. }
  14067. if (uniform) {
  14068. this._boundUniforms[channel] = uniform;
  14069. }
  14070. this._setTexture(channel, texture);
  14071. };
  14072. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  14073. var uniform = this._boundUniforms[sourceSlot];
  14074. if (uniform._currentState === destination) {
  14075. return;
  14076. }
  14077. this._gl.uniform1i(uniform, destination);
  14078. uniform._currentState = destination;
  14079. };
  14080. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray) {
  14081. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  14082. // Not ready?
  14083. if (!texture) {
  14084. if (this._boundTexturesCache[channel] != null) {
  14085. this._activeChannel = channel;
  14086. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14087. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14088. if (this.webGLVersion > 1) {
  14089. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14090. }
  14091. }
  14092. return false;
  14093. }
  14094. // Video
  14095. if (texture.video) {
  14096. this._activeChannel = channel;
  14097. texture.update();
  14098. }
  14099. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  14100. texture.delayLoad();
  14101. return false;
  14102. }
  14103. var internalTexture;
  14104. if (texture.isReady()) {
  14105. internalTexture = texture.getInternalTexture();
  14106. }
  14107. else if (texture.isCube) {
  14108. internalTexture = this.emptyCubeTexture;
  14109. }
  14110. else if (texture.is3D) {
  14111. internalTexture = this.emptyTexture3D;
  14112. }
  14113. else {
  14114. internalTexture = this.emptyTexture;
  14115. }
  14116. if (!isPartOfTextureArray) {
  14117. channel = this._getCorrectTextureChannel(channel, internalTexture);
  14118. }
  14119. if (this._boundTexturesCache[channel] === internalTexture) {
  14120. this._moveBoundTextureOnTop(internalTexture);
  14121. if (!isPartOfTextureArray) {
  14122. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  14123. }
  14124. return false;
  14125. }
  14126. this._activeChannel = channel;
  14127. if (internalTexture && internalTexture.is3D) {
  14128. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  14129. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  14130. internalTexture._cachedWrapU = texture.wrapU;
  14131. switch (texture.wrapU) {
  14132. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14133. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  14134. break;
  14135. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14136. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  14137. break;
  14138. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14139. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  14140. break;
  14141. }
  14142. }
  14143. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  14144. internalTexture._cachedWrapV = texture.wrapV;
  14145. switch (texture.wrapV) {
  14146. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14147. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  14148. break;
  14149. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14150. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  14151. break;
  14152. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14153. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  14154. break;
  14155. }
  14156. }
  14157. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  14158. internalTexture._cachedWrapR = texture.wrapR;
  14159. switch (texture.wrapR) {
  14160. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14161. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.REPEAT);
  14162. break;
  14163. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14164. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.CLAMP_TO_EDGE);
  14165. break;
  14166. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14167. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.MIRRORED_REPEAT);
  14168. break;
  14169. }
  14170. }
  14171. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  14172. }
  14173. else if (internalTexture && internalTexture.isCube) {
  14174. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  14175. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  14176. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  14177. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  14178. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  14179. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  14180. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  14181. }
  14182. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  14183. }
  14184. else {
  14185. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  14186. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  14187. internalTexture._cachedWrapU = texture.wrapU;
  14188. switch (texture.wrapU) {
  14189. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14190. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  14191. break;
  14192. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14193. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  14194. break;
  14195. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14196. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  14197. break;
  14198. }
  14199. }
  14200. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  14201. internalTexture._cachedWrapV = texture.wrapV;
  14202. switch (texture.wrapV) {
  14203. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14204. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  14205. break;
  14206. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14207. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  14208. break;
  14209. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14210. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  14211. break;
  14212. }
  14213. }
  14214. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  14215. }
  14216. return true;
  14217. };
  14218. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  14219. if (channel < 0 || !uniform) {
  14220. return;
  14221. }
  14222. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  14223. this._textureUnits = new Int32Array(textures.length);
  14224. }
  14225. for (var i = 0; i < textures.length; i++) {
  14226. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  14227. }
  14228. this._gl.uniform1iv(uniform, this._textureUnits);
  14229. for (var index = 0; index < textures.length; index++) {
  14230. this._setTexture(this._textureUnits[index], textures[index], true);
  14231. }
  14232. };
  14233. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  14234. var internalTexture = texture.getInternalTexture();
  14235. if (!internalTexture) {
  14236. return;
  14237. }
  14238. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  14239. var value = texture.anisotropicFilteringLevel;
  14240. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  14241. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  14242. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  14243. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  14244. }
  14245. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  14246. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  14247. internalTexture._cachedAnisotropicFilteringLevel = value;
  14248. }
  14249. };
  14250. Engine.prototype.readPixels = function (x, y, width, height) {
  14251. var data = new Uint8Array(height * width * 4);
  14252. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  14253. return data;
  14254. };
  14255. /**
  14256. * Add an externaly attached data from its key.
  14257. * This method call will fail and return false, if such key already exists.
  14258. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  14259. * @param key the unique key that identifies the data
  14260. * @param data the data object to associate to the key for this Engine instance
  14261. * @return true if no such key were already present and the data was added successfully, false otherwise
  14262. */
  14263. Engine.prototype.addExternalData = function (key, data) {
  14264. if (!this._externalData) {
  14265. this._externalData = new BABYLON.StringDictionary();
  14266. }
  14267. return this._externalData.add(key, data);
  14268. };
  14269. /**
  14270. * Get an externaly attached data from its key
  14271. * @param key the unique key that identifies the data
  14272. * @return the associated data, if present (can be null), or undefined if not present
  14273. */
  14274. Engine.prototype.getExternalData = function (key) {
  14275. if (!this._externalData) {
  14276. this._externalData = new BABYLON.StringDictionary();
  14277. }
  14278. return this._externalData.get(key);
  14279. };
  14280. /**
  14281. * Get an externaly attached data from its key, create it using a factory if it's not already present
  14282. * @param key the unique key that identifies the data
  14283. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  14284. * @return the associated data, can be null if the factory returned null.
  14285. */
  14286. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  14287. if (!this._externalData) {
  14288. this._externalData = new BABYLON.StringDictionary();
  14289. }
  14290. return this._externalData.getOrAddWithFactory(key, factory);
  14291. };
  14292. /**
  14293. * Remove an externaly attached data from the Engine instance
  14294. * @param key the unique key that identifies the data
  14295. * @return true if the data was successfully removed, false if it doesn't exist
  14296. */
  14297. Engine.prototype.removeExternalData = function (key) {
  14298. if (!this._externalData) {
  14299. this._externalData = new BABYLON.StringDictionary();
  14300. }
  14301. return this._externalData.remove(key);
  14302. };
  14303. Engine.prototype.unbindAllAttributes = function () {
  14304. if (this._mustWipeVertexAttributes) {
  14305. this._mustWipeVertexAttributes = false;
  14306. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  14307. this._gl.disableVertexAttribArray(i);
  14308. this._vertexAttribArraysEnabled[i] = false;
  14309. this._currentBufferPointers[i].active = false;
  14310. }
  14311. return;
  14312. }
  14313. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  14314. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  14315. continue;
  14316. }
  14317. this._gl.disableVertexAttribArray(i);
  14318. this._vertexAttribArraysEnabled[i] = false;
  14319. this._currentBufferPointers[i].active = false;
  14320. }
  14321. };
  14322. Engine.prototype.releaseEffects = function () {
  14323. for (var name in this._compiledEffects) {
  14324. this._deleteProgram(this._compiledEffects[name]._program);
  14325. }
  14326. this._compiledEffects = {};
  14327. };
  14328. // Dispose
  14329. Engine.prototype.dispose = function () {
  14330. this.hideLoadingUI();
  14331. this.stopRenderLoop();
  14332. // Release postProcesses
  14333. while (this.postProcesses.length) {
  14334. this.postProcesses[0].dispose();
  14335. }
  14336. // Empty texture
  14337. if (this._emptyTexture) {
  14338. this._releaseTexture(this._emptyTexture);
  14339. this._emptyTexture = null;
  14340. }
  14341. if (this._emptyCubeTexture) {
  14342. this._releaseTexture(this._emptyCubeTexture);
  14343. this._emptyCubeTexture = null;
  14344. }
  14345. // Rescale PP
  14346. if (this._rescalePostProcess) {
  14347. this._rescalePostProcess.dispose();
  14348. }
  14349. // Release scenes
  14350. while (this.scenes.length) {
  14351. this.scenes[0].dispose();
  14352. }
  14353. // Release audio engine
  14354. if (Engine.audioEngine) {
  14355. Engine.audioEngine.dispose();
  14356. }
  14357. // Release effects
  14358. this.releaseEffects();
  14359. // Unbind
  14360. this.unbindAllAttributes();
  14361. if (this._dummyFramebuffer) {
  14362. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  14363. }
  14364. //WebVR
  14365. this.disableVR();
  14366. // Events
  14367. if (BABYLON.Tools.IsWindowObjectExist()) {
  14368. window.removeEventListener("blur", this._onBlur);
  14369. window.removeEventListener("focus", this._onFocus);
  14370. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  14371. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  14372. if (this._renderingCanvas) {
  14373. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  14374. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  14375. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasBlur);
  14376. if (!this._doNotHandleContextLost) {
  14377. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  14378. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  14379. }
  14380. }
  14381. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  14382. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  14383. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  14384. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  14385. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  14386. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  14387. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  14388. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  14389. if (this._onVrDisplayConnect) {
  14390. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  14391. if (this._onVrDisplayDisconnect) {
  14392. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  14393. }
  14394. if (this._onVrDisplayPresentChange) {
  14395. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  14396. }
  14397. this._onVrDisplayConnect = null;
  14398. this._onVrDisplayDisconnect = null;
  14399. }
  14400. }
  14401. // Remove from Instances
  14402. var index = Engine.Instances.indexOf(this);
  14403. if (index >= 0) {
  14404. Engine.Instances.splice(index, 1);
  14405. }
  14406. this._workingCanvas = null;
  14407. this._workingContext = null;
  14408. this._currentBufferPointers = [];
  14409. this._renderingCanvas = null;
  14410. this._currentProgram = null;
  14411. this.onResizeObservable.clear();
  14412. this.onCanvasBlurObservable.clear();
  14413. this.onCanvasFocusObservable.clear();
  14414. this.onCanvasPointerOutObservable.clear();
  14415. this.onBeginFrameObservable.clear();
  14416. this.onEndFrameObservable.clear();
  14417. BABYLON.Effect.ResetCache();
  14418. // Abort active requests
  14419. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  14420. var request = _a[_i];
  14421. request.abort();
  14422. }
  14423. };
  14424. // Loading screen
  14425. Engine.prototype.displayLoadingUI = function () {
  14426. if (!BABYLON.Tools.IsWindowObjectExist()) {
  14427. return;
  14428. }
  14429. var loadingScreen = this.loadingScreen;
  14430. if (loadingScreen) {
  14431. loadingScreen.displayLoadingUI();
  14432. }
  14433. };
  14434. Engine.prototype.hideLoadingUI = function () {
  14435. if (!BABYLON.Tools.IsWindowObjectExist()) {
  14436. return;
  14437. }
  14438. var loadingScreen = this.loadingScreen;
  14439. if (loadingScreen) {
  14440. loadingScreen.hideLoadingUI();
  14441. }
  14442. };
  14443. Object.defineProperty(Engine.prototype, "loadingScreen", {
  14444. get: function () {
  14445. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  14446. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  14447. return this._loadingScreen;
  14448. },
  14449. set: function (loadingScreen) {
  14450. this._loadingScreen = loadingScreen;
  14451. },
  14452. enumerable: true,
  14453. configurable: true
  14454. });
  14455. Object.defineProperty(Engine.prototype, "loadingUIText", {
  14456. set: function (text) {
  14457. this.loadingScreen.loadingUIText = text;
  14458. },
  14459. enumerable: true,
  14460. configurable: true
  14461. });
  14462. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  14463. set: function (color) {
  14464. this.loadingScreen.loadingUIBackgroundColor = color;
  14465. },
  14466. enumerable: true,
  14467. configurable: true
  14468. });
  14469. Engine.prototype.attachContextLostEvent = function (callback) {
  14470. if (this._renderingCanvas) {
  14471. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  14472. }
  14473. };
  14474. Engine.prototype.attachContextRestoredEvent = function (callback) {
  14475. if (this._renderingCanvas) {
  14476. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  14477. }
  14478. };
  14479. Engine.prototype.getVertexShaderSource = function (program) {
  14480. var shaders = this._gl.getAttachedShaders(program);
  14481. if (!shaders) {
  14482. return null;
  14483. }
  14484. return this._gl.getShaderSource(shaders[0]);
  14485. };
  14486. Engine.prototype.getFragmentShaderSource = function (program) {
  14487. var shaders = this._gl.getAttachedShaders(program);
  14488. if (!shaders) {
  14489. return null;
  14490. }
  14491. return this._gl.getShaderSource(shaders[1]);
  14492. };
  14493. Engine.prototype.getError = function () {
  14494. return this._gl.getError();
  14495. };
  14496. // FPS
  14497. Engine.prototype.getFps = function () {
  14498. return this._fps;
  14499. };
  14500. Engine.prototype.getDeltaTime = function () {
  14501. return this._deltaTime;
  14502. };
  14503. Engine.prototype._measureFps = function () {
  14504. this._performanceMonitor.sampleFrame();
  14505. this._fps = this._performanceMonitor.averageFPS;
  14506. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  14507. };
  14508. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  14509. if (faceIndex === void 0) { faceIndex = -1; }
  14510. var gl = this._gl;
  14511. if (!this._dummyFramebuffer) {
  14512. var dummy = gl.createFramebuffer();
  14513. if (!dummy) {
  14514. throw new Error("Unable to create dummy framebuffer");
  14515. }
  14516. this._dummyFramebuffer = dummy;
  14517. }
  14518. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  14519. if (faceIndex > -1) {
  14520. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  14521. }
  14522. else {
  14523. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  14524. }
  14525. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  14526. var buffer;
  14527. switch (readType) {
  14528. case gl.UNSIGNED_BYTE:
  14529. buffer = new Uint8Array(4 * width * height);
  14530. readType = gl.UNSIGNED_BYTE;
  14531. break;
  14532. default:
  14533. buffer = new Float32Array(4 * width * height);
  14534. readType = gl.FLOAT;
  14535. break;
  14536. }
  14537. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  14538. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  14539. return buffer;
  14540. };
  14541. Engine.prototype._canRenderToFloatFramebuffer = function () {
  14542. if (this._webGLVersion > 1) {
  14543. return this._caps.colorBufferFloat;
  14544. }
  14545. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  14546. };
  14547. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  14548. if (this._webGLVersion > 1) {
  14549. return this._caps.colorBufferFloat;
  14550. }
  14551. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  14552. };
  14553. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  14554. Engine.prototype._canRenderToFramebuffer = function (type) {
  14555. var gl = this._gl;
  14556. //clear existing errors
  14557. while (gl.getError() !== gl.NO_ERROR) { }
  14558. var successful = true;
  14559. var texture = gl.createTexture();
  14560. gl.bindTexture(gl.TEXTURE_2D, texture);
  14561. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  14562. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  14563. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  14564. var fb = gl.createFramebuffer();
  14565. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  14566. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  14567. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  14568. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  14569. successful = successful && (gl.getError() === gl.NO_ERROR);
  14570. //try render by clearing frame buffer's color buffer
  14571. if (successful) {
  14572. gl.clear(gl.COLOR_BUFFER_BIT);
  14573. successful = successful && (gl.getError() === gl.NO_ERROR);
  14574. }
  14575. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  14576. if (successful) {
  14577. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  14578. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  14579. var readFormat = gl.RGBA;
  14580. var readType = gl.UNSIGNED_BYTE;
  14581. var buffer = new Uint8Array(4);
  14582. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  14583. successful = successful && (gl.getError() === gl.NO_ERROR);
  14584. }
  14585. //clean up
  14586. gl.deleteTexture(texture);
  14587. gl.deleteFramebuffer(fb);
  14588. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  14589. //clear accumulated errors
  14590. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  14591. return successful;
  14592. };
  14593. Engine.prototype._getWebGLTextureType = function (type) {
  14594. if (type === Engine.TEXTURETYPE_FLOAT) {
  14595. return this._gl.FLOAT;
  14596. }
  14597. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  14598. // Add Half Float Constant.
  14599. return this._gl.HALF_FLOAT_OES;
  14600. }
  14601. return this._gl.UNSIGNED_BYTE;
  14602. };
  14603. ;
  14604. Engine.prototype._getRGBABufferInternalSizedFormat = function (type) {
  14605. if (this._webGLVersion === 1) {
  14606. return this._gl.RGBA;
  14607. }
  14608. if (type === Engine.TEXTURETYPE_FLOAT) {
  14609. return this._gl.RGBA32F;
  14610. }
  14611. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  14612. return this._gl.RGBA16F;
  14613. }
  14614. return this._gl.RGBA;
  14615. };
  14616. ;
  14617. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  14618. if (type === Engine.TEXTURETYPE_FLOAT) {
  14619. return this._gl.RGBA32F;
  14620. }
  14621. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  14622. return this._gl.RGBA16F;
  14623. }
  14624. return this._gl.RGBA8;
  14625. };
  14626. ;
  14627. Engine.prototype.createQuery = function () {
  14628. return this._gl.createQuery();
  14629. };
  14630. Engine.prototype.deleteQuery = function (query) {
  14631. this._gl.deleteQuery(query);
  14632. return this;
  14633. };
  14634. Engine.prototype.isQueryResultAvailable = function (query) {
  14635. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  14636. };
  14637. Engine.prototype.getQueryResult = function (query) {
  14638. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  14639. };
  14640. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  14641. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  14642. this._gl.beginQuery(glAlgorithm, query);
  14643. return this;
  14644. };
  14645. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  14646. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  14647. this._gl.endQuery(glAlgorithm);
  14648. return this;
  14649. };
  14650. /* Time queries */
  14651. Engine.prototype._createTimeQuery = function () {
  14652. var timerQuery = this._caps.timerQuery;
  14653. if (timerQuery.createQueryEXT) {
  14654. return timerQuery.createQueryEXT();
  14655. }
  14656. return this.createQuery();
  14657. };
  14658. Engine.prototype._deleteTimeQuery = function (query) {
  14659. var timerQuery = this._caps.timerQuery;
  14660. if (timerQuery.deleteQueryEXT) {
  14661. timerQuery.deleteQueryEXT(query);
  14662. return;
  14663. }
  14664. this.deleteQuery(query);
  14665. };
  14666. Engine.prototype._getTimeQueryResult = function (query) {
  14667. var timerQuery = this._caps.timerQuery;
  14668. if (timerQuery.getQueryObjectEXT) {
  14669. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  14670. }
  14671. return this.getQueryResult(query);
  14672. };
  14673. Engine.prototype._getTimeQueryAvailability = function (query) {
  14674. var timerQuery = this._caps.timerQuery;
  14675. if (timerQuery.getQueryObjectEXT) {
  14676. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  14677. }
  14678. return this.isQueryResultAvailable(query);
  14679. };
  14680. Engine.prototype.startTimeQuery = function () {
  14681. var timerQuery = this._caps.timerQuery;
  14682. if (!timerQuery) {
  14683. return null;
  14684. }
  14685. var token = new BABYLON._TimeToken();
  14686. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  14687. if (this._caps.canUseTimestampForTimerQuery) {
  14688. token._startTimeQuery = this._createTimeQuery();
  14689. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  14690. }
  14691. else {
  14692. if (this._currentNonTimestampToken) {
  14693. return this._currentNonTimestampToken;
  14694. }
  14695. token._timeElapsedQuery = this._createTimeQuery();
  14696. if (timerQuery.beginQueryEXT) {
  14697. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  14698. }
  14699. else {
  14700. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  14701. }
  14702. this._currentNonTimestampToken = token;
  14703. }
  14704. return token;
  14705. };
  14706. Engine.prototype.endTimeQuery = function (token) {
  14707. var timerQuery = this._caps.timerQuery;
  14708. if (!timerQuery || !token) {
  14709. return -1;
  14710. }
  14711. if (this._caps.canUseTimestampForTimerQuery) {
  14712. if (!token._startTimeQuery) {
  14713. return -1;
  14714. }
  14715. if (!token._endTimeQuery) {
  14716. token._endTimeQuery = this._createTimeQuery();
  14717. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  14718. }
  14719. }
  14720. else if (!token._timeElapsedQueryEnded) {
  14721. if (!token._timeElapsedQuery) {
  14722. return -1;
  14723. }
  14724. if (timerQuery.endQueryEXT) {
  14725. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  14726. }
  14727. else {
  14728. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  14729. }
  14730. token._timeElapsedQueryEnded = true;
  14731. }
  14732. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  14733. var available = false;
  14734. if (token._endTimeQuery) {
  14735. available = this._getTimeQueryAvailability(token._endTimeQuery);
  14736. }
  14737. else if (token._timeElapsedQuery) {
  14738. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  14739. }
  14740. if (available && !disjoint) {
  14741. var result = 0;
  14742. if (this._caps.canUseTimestampForTimerQuery) {
  14743. if (!token._startTimeQuery || !token._endTimeQuery) {
  14744. return -1;
  14745. }
  14746. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  14747. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  14748. result = timeEnd - timeStart;
  14749. this._deleteTimeQuery(token._startTimeQuery);
  14750. this._deleteTimeQuery(token._endTimeQuery);
  14751. token._startTimeQuery = null;
  14752. token._endTimeQuery = null;
  14753. }
  14754. else {
  14755. if (!token._timeElapsedQuery) {
  14756. return -1;
  14757. }
  14758. result = this._getTimeQueryResult(token._timeElapsedQuery);
  14759. this._deleteTimeQuery(token._timeElapsedQuery);
  14760. token._timeElapsedQuery = null;
  14761. token._timeElapsedQueryEnded = false;
  14762. this._currentNonTimestampToken = null;
  14763. }
  14764. return result;
  14765. }
  14766. return -1;
  14767. };
  14768. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  14769. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  14770. };
  14771. // Transform feedback
  14772. Engine.prototype.createTransformFeedback = function () {
  14773. return this._gl.createTransformFeedback();
  14774. };
  14775. Engine.prototype.deleteTransformFeedback = function (value) {
  14776. this._gl.deleteTransformFeedback(value);
  14777. };
  14778. Engine.prototype.bindTransformFeedback = function (value) {
  14779. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  14780. };
  14781. Engine.prototype.beginTransformFeedback = function (usePoints) {
  14782. if (usePoints === void 0) { usePoints = true; }
  14783. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  14784. };
  14785. Engine.prototype.endTransformFeedback = function () {
  14786. this._gl.endTransformFeedback();
  14787. };
  14788. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  14789. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  14790. };
  14791. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  14792. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  14793. };
  14794. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  14795. var _this = this;
  14796. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  14797. this._activeRequests.push(request);
  14798. request.onCompleteObservable.add(function (request) {
  14799. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  14800. });
  14801. return request;
  14802. };
  14803. /** @ignore */
  14804. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  14805. var _this = this;
  14806. return new Promise(function (resolve, reject) {
  14807. _this._loadFile(url, function (data) {
  14808. resolve(data);
  14809. }, undefined, database, useArrayBuffer, function (request, exception) {
  14810. reject(exception);
  14811. });
  14812. });
  14813. };
  14814. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  14815. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  14816. var onload = function (data) {
  14817. loadedFiles[index] = data;
  14818. loadedFiles._internalCount++;
  14819. if (loadedFiles._internalCount === 6) {
  14820. onfinish(loadedFiles);
  14821. }
  14822. };
  14823. var onerror = function (request, exception) {
  14824. if (onErrorCallBack && request) {
  14825. onErrorCallBack(request.status + " " + request.statusText, exception);
  14826. }
  14827. };
  14828. this._loadFile(url, onload, undefined, undefined, true, onerror);
  14829. };
  14830. Engine.prototype._cascadeLoadFiles = function (rootUrl, scene, onfinish, files, onError) {
  14831. if (onError === void 0) { onError = null; }
  14832. var loadedFiles = [];
  14833. loadedFiles._internalCount = 0;
  14834. for (var index = 0; index < 6; index++) {
  14835. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  14836. }
  14837. };
  14838. // Statics
  14839. Engine.isSupported = function () {
  14840. try {
  14841. var tempcanvas = document.createElement("canvas");
  14842. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  14843. return gl != null && !!window.WebGLRenderingContext;
  14844. }
  14845. catch (e) {
  14846. return false;
  14847. }
  14848. };
  14849. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  14850. Engine.ExceptionList = [
  14851. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  14852. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  14853. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  14854. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  14855. ];
  14856. Engine.Instances = new Array();
  14857. // Const statics
  14858. Engine._ALPHA_DISABLE = 0;
  14859. Engine._ALPHA_ADD = 1;
  14860. Engine._ALPHA_COMBINE = 2;
  14861. Engine._ALPHA_SUBTRACT = 3;
  14862. Engine._ALPHA_MULTIPLY = 4;
  14863. Engine._ALPHA_MAXIMIZED = 5;
  14864. Engine._ALPHA_ONEONE = 6;
  14865. Engine._ALPHA_PREMULTIPLIED = 7;
  14866. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  14867. Engine._ALPHA_INTERPOLATE = 9;
  14868. Engine._ALPHA_SCREENMODE = 10;
  14869. Engine._DELAYLOADSTATE_NONE = 0;
  14870. Engine._DELAYLOADSTATE_LOADED = 1;
  14871. Engine._DELAYLOADSTATE_LOADING = 2;
  14872. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  14873. Engine._TEXTUREFORMAT_ALPHA = 0;
  14874. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  14875. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  14876. Engine._TEXTUREFORMAT_RGB = 4;
  14877. Engine._TEXTUREFORMAT_RGBA = 5;
  14878. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  14879. Engine._TEXTURETYPE_FLOAT = 1;
  14880. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  14881. // Depht or Stencil test Constants.
  14882. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  14883. 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.
  14884. 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.
  14885. 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.
  14886. 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.
  14887. 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.
  14888. 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.
  14889. 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.
  14890. // Stencil Actions Constants.
  14891. Engine._KEEP = 0x1E00;
  14892. Engine._REPLACE = 0x1E01;
  14893. Engine._INCR = 0x1E02;
  14894. Engine._DECR = 0x1E03;
  14895. Engine._INVERT = 0x150A;
  14896. Engine._INCR_WRAP = 0x8507;
  14897. Engine._DECR_WRAP = 0x8508;
  14898. // Texture rescaling mode
  14899. Engine._SCALEMODE_FLOOR = 1;
  14900. Engine._SCALEMODE_NEAREST = 2;
  14901. Engine._SCALEMODE_CEILING = 3;
  14902. // Updatable statics so stick with vars here
  14903. Engine.CollisionsEpsilon = 0.001;
  14904. Engine.CodeRepository = "src/";
  14905. Engine.ShadersRepository = "src/Shaders/";
  14906. return Engine;
  14907. }());
  14908. BABYLON.Engine = Engine;
  14909. })(BABYLON || (BABYLON = {}));
  14910. //# sourceMappingURL=babylon.engine.js.map
  14911. var BABYLON;
  14912. (function (BABYLON) {
  14913. /**
  14914. * Node is the basic class for all scene objects (Mesh, Light Camera).
  14915. */
  14916. var Node = /** @class */ (function () {
  14917. /**
  14918. * Creates a new Node
  14919. * @param {string} name - the name and id to be given to this node
  14920. * @param {BABYLON.Scene} the scene this node will be added to
  14921. */
  14922. function Node(name, scene) {
  14923. if (scene === void 0) { scene = null; }
  14924. /**
  14925. * Gets or sets a string used to store user defined state for the node
  14926. */
  14927. this.state = "";
  14928. /**
  14929. * Gets or sets an object used to store user defined information for the node
  14930. */
  14931. this.metadata = null;
  14932. /**
  14933. * Gets or sets a boolean used to define if the node must be serialized
  14934. */
  14935. this.doNotSerialize = false;
  14936. /** @ignore */
  14937. this._isDisposed = false;
  14938. /**
  14939. * Gets a list of {BABYLON.Animation} associated with the node
  14940. */
  14941. this.animations = new Array();
  14942. this._ranges = {};
  14943. this._isEnabled = true;
  14944. this._isReady = true;
  14945. /** @ignore */
  14946. this._currentRenderId = -1;
  14947. this._parentRenderId = -1;
  14948. /**
  14949. * An event triggered when the mesh is disposed
  14950. * @type {BABYLON.Observable}
  14951. */
  14952. this.onDisposeObservable = new BABYLON.Observable();
  14953. // Behaviors
  14954. this._behaviors = new Array();
  14955. this.name = name;
  14956. this.id = name;
  14957. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  14958. this.uniqueId = this._scene.getUniqueId();
  14959. this._initCache();
  14960. }
  14961. /**
  14962. * Gets a boolean indicating if the node has been disposed
  14963. * @returns true if the node was disposed
  14964. */
  14965. Node.prototype.isDisposed = function () {
  14966. return this._isDisposed;
  14967. };
  14968. Object.defineProperty(Node.prototype, "parent", {
  14969. get: function () {
  14970. return this._parentNode;
  14971. },
  14972. /**
  14973. * Gets or sets the parent of the node
  14974. */
  14975. set: function (parent) {
  14976. if (this._parentNode === parent) {
  14977. return;
  14978. }
  14979. // Remove self from list of children of parent
  14980. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  14981. var index = this._parentNode._children.indexOf(this);
  14982. if (index !== -1) {
  14983. this._parentNode._children.splice(index, 1);
  14984. }
  14985. }
  14986. // Store new parent
  14987. this._parentNode = parent;
  14988. // Add as child to new parent
  14989. if (this._parentNode) {
  14990. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  14991. this._parentNode._children = new Array();
  14992. }
  14993. this._parentNode._children.push(this);
  14994. }
  14995. },
  14996. enumerable: true,
  14997. configurable: true
  14998. });
  14999. /**
  15000. * Gets a string idenfifying the name of the class
  15001. * @returns "Node" string
  15002. */
  15003. Node.prototype.getClassName = function () {
  15004. return "Node";
  15005. };
  15006. Object.defineProperty(Node.prototype, "onDispose", {
  15007. /**
  15008. * Sets a callback that will be raised when the node will be disposed
  15009. */
  15010. set: function (callback) {
  15011. if (this._onDisposeObserver) {
  15012. this.onDisposeObservable.remove(this._onDisposeObserver);
  15013. }
  15014. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  15015. },
  15016. enumerable: true,
  15017. configurable: true
  15018. });
  15019. /**
  15020. * Gets the scene of the node
  15021. * @returns a {BABYLON.Scene}
  15022. */
  15023. Node.prototype.getScene = function () {
  15024. return this._scene;
  15025. };
  15026. /**
  15027. * Gets the engine of the node
  15028. * @returns a {BABYLON.Engine}
  15029. */
  15030. Node.prototype.getEngine = function () {
  15031. return this._scene.getEngine();
  15032. };
  15033. /**
  15034. * Attach a behavior to the node
  15035. * @see http://doc.babylonjs.com/features/behaviour
  15036. * @param behavior defines the behavior to attach
  15037. * @returns the current Node
  15038. */
  15039. Node.prototype.addBehavior = function (behavior) {
  15040. var _this = this;
  15041. var index = this._behaviors.indexOf(behavior);
  15042. if (index !== -1) {
  15043. return this;
  15044. }
  15045. behavior.init();
  15046. if (this._scene.isLoading) {
  15047. // We defer the attach when the scene will be loaded
  15048. var observer = this._scene.onDataLoadedObservable.add(function () {
  15049. behavior.attach(_this);
  15050. setTimeout(function () {
  15051. // Need to use a timeout to avoid removing an observer while iterating the list of observers
  15052. _this._scene.onDataLoadedObservable.remove(observer);
  15053. }, 0);
  15054. });
  15055. }
  15056. else {
  15057. behavior.attach(this);
  15058. }
  15059. this._behaviors.push(behavior);
  15060. return this;
  15061. };
  15062. /**
  15063. * Remove an attached behavior
  15064. * @see http://doc.babylonjs.com/features/behaviour
  15065. * @param behavior defines the behavior to attach
  15066. * @returns the current Node
  15067. */
  15068. Node.prototype.removeBehavior = function (behavior) {
  15069. var index = this._behaviors.indexOf(behavior);
  15070. if (index === -1) {
  15071. return this;
  15072. }
  15073. this._behaviors[index].detach();
  15074. this._behaviors.splice(index, 1);
  15075. return this;
  15076. };
  15077. Object.defineProperty(Node.prototype, "behaviors", {
  15078. /**
  15079. * Gets the list of attached behaviors
  15080. * @see http://doc.babylonjs.com/features/behaviour
  15081. */
  15082. get: function () {
  15083. return this._behaviors;
  15084. },
  15085. enumerable: true,
  15086. configurable: true
  15087. });
  15088. /**
  15089. * Gets an attached behavior by name
  15090. * @param name defines the name of the behavior to look for
  15091. * @see http://doc.babylonjs.com/features/behaviour
  15092. * @returns null if behavior was not found else the requested behavior
  15093. */
  15094. Node.prototype.getBehaviorByName = function (name) {
  15095. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  15096. var behavior = _a[_i];
  15097. if (behavior.name === name) {
  15098. return behavior;
  15099. }
  15100. }
  15101. return null;
  15102. };
  15103. /**
  15104. * Returns the world matrix of the node
  15105. * @returns a matrix containing the node's world matrix
  15106. */
  15107. Node.prototype.getWorldMatrix = function () {
  15108. return BABYLON.Matrix.Identity();
  15109. };
  15110. // override it in derived class if you add new variables to the cache
  15111. // and call the parent class method
  15112. /** @ignore */
  15113. Node.prototype._initCache = function () {
  15114. this._cache = {};
  15115. this._cache.parent = undefined;
  15116. };
  15117. /** @ignore */
  15118. Node.prototype.updateCache = function (force) {
  15119. if (!force && this.isSynchronized())
  15120. return;
  15121. this._cache.parent = this.parent;
  15122. this._updateCache();
  15123. };
  15124. // override it in derived class if you add new variables to the cache
  15125. // and call the parent class method if !ignoreParentClass
  15126. /** @ignore */
  15127. Node.prototype._updateCache = function (ignoreParentClass) {
  15128. };
  15129. // override it in derived class if you add new variables to the cache
  15130. /** @ignore */
  15131. Node.prototype._isSynchronized = function () {
  15132. return true;
  15133. };
  15134. /** @ignore */
  15135. Node.prototype._markSyncedWithParent = function () {
  15136. if (this.parent) {
  15137. this._parentRenderId = this.parent._currentRenderId;
  15138. }
  15139. };
  15140. /** @ignore */
  15141. Node.prototype.isSynchronizedWithParent = function () {
  15142. if (!this.parent) {
  15143. return true;
  15144. }
  15145. if (this._parentRenderId !== this.parent._currentRenderId) {
  15146. return false;
  15147. }
  15148. return this.parent.isSynchronized();
  15149. };
  15150. /** @ignore */
  15151. Node.prototype.isSynchronized = function (updateCache) {
  15152. var check = this.hasNewParent();
  15153. check = check || !this.isSynchronizedWithParent();
  15154. check = check || !this._isSynchronized();
  15155. if (updateCache)
  15156. this.updateCache(true);
  15157. return !check;
  15158. };
  15159. /** @ignore */
  15160. Node.prototype.hasNewParent = function (update) {
  15161. if (this._cache.parent === this.parent)
  15162. return false;
  15163. if (update)
  15164. this._cache.parent = this.parent;
  15165. return true;
  15166. };
  15167. /**
  15168. * Is this node ready to be used/rendered
  15169. * @return true if the node is ready
  15170. */
  15171. Node.prototype.isReady = function () {
  15172. return this._isReady;
  15173. };
  15174. /**
  15175. * Is this node enabled?
  15176. * 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
  15177. * @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
  15178. * @return whether this node (and its parent) is enabled
  15179. * @see setEnabled
  15180. */
  15181. Node.prototype.isEnabled = function (checkAncestors) {
  15182. if (checkAncestors === void 0) { checkAncestors = true; }
  15183. if (checkAncestors === false) {
  15184. return this._isEnabled;
  15185. }
  15186. if (this._isEnabled === false) {
  15187. return false;
  15188. }
  15189. if (this.parent !== undefined && this.parent !== null) {
  15190. return this.parent.isEnabled(checkAncestors);
  15191. }
  15192. return true;
  15193. };
  15194. /**
  15195. * Set the enabled state of this node
  15196. * @param value defines the new enabled state
  15197. * @see isEnabled
  15198. */
  15199. Node.prototype.setEnabled = function (value) {
  15200. this._isEnabled = value;
  15201. };
  15202. /**
  15203. * Is this node a descendant of the given node?
  15204. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  15205. * @param ancestor defines the parent node to inspect
  15206. * @see parent
  15207. * @returns a boolean indicating if this node is a descendant of the given node
  15208. */
  15209. Node.prototype.isDescendantOf = function (ancestor) {
  15210. if (this.parent) {
  15211. if (this.parent === ancestor) {
  15212. return true;
  15213. }
  15214. return this.parent.isDescendantOf(ancestor);
  15215. }
  15216. return false;
  15217. };
  15218. /** @ignore */
  15219. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  15220. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  15221. if (!this._children) {
  15222. return;
  15223. }
  15224. for (var index = 0; index < this._children.length; index++) {
  15225. var item = this._children[index];
  15226. if (!predicate || predicate(item)) {
  15227. results.push(item);
  15228. }
  15229. if (!directDescendantsOnly) {
  15230. item._getDescendants(results, false, predicate);
  15231. }
  15232. }
  15233. };
  15234. /**
  15235. * Will return all nodes that have this node as ascendant
  15236. * @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
  15237. * @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
  15238. * @return all children nodes of all types
  15239. */
  15240. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  15241. var results = new Array();
  15242. this._getDescendants(results, directDescendantsOnly, predicate);
  15243. return results;
  15244. };
  15245. /**
  15246. * Get all child-meshes of this node
  15247. * @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
  15248. * @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
  15249. * @returns an array of {BABYLON.AbstractMesh}
  15250. */
  15251. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  15252. var results = [];
  15253. this._getDescendants(results, directDescendantsOnly, function (node) {
  15254. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  15255. });
  15256. return results;
  15257. };
  15258. /**
  15259. * Get all child-transformNodes of this node
  15260. * @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
  15261. * @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
  15262. * @returns an array of {BABYLON.TransformNode}
  15263. */
  15264. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  15265. var results = [];
  15266. this._getDescendants(results, directDescendantsOnly, function (node) {
  15267. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  15268. });
  15269. return results;
  15270. };
  15271. /**
  15272. * Get all direct children of this node
  15273. * @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
  15274. * @returns an array of {BABYLON.Node}
  15275. */
  15276. Node.prototype.getChildren = function (predicate) {
  15277. return this.getDescendants(true, predicate);
  15278. };
  15279. /** @ignore */
  15280. Node.prototype._setReady = function (state) {
  15281. if (state === this._isReady) {
  15282. return;
  15283. }
  15284. if (!state) {
  15285. this._isReady = false;
  15286. return;
  15287. }
  15288. this._isReady = true;
  15289. if (this.onReady) {
  15290. this.onReady(this);
  15291. }
  15292. };
  15293. /**
  15294. * Get an animation by name
  15295. * @param name defines the name of the animation to look for
  15296. * @returns null if not found else the requested animation
  15297. */
  15298. Node.prototype.getAnimationByName = function (name) {
  15299. for (var i = 0; i < this.animations.length; i++) {
  15300. var animation = this.animations[i];
  15301. if (animation.name === name) {
  15302. return animation;
  15303. }
  15304. }
  15305. return null;
  15306. };
  15307. /**
  15308. * Creates an animation range for this node
  15309. * @param name defines the name of the range
  15310. * @param from defines the starting key
  15311. * @param to defines the end key
  15312. */
  15313. Node.prototype.createAnimationRange = function (name, from, to) {
  15314. // check name not already in use
  15315. if (!this._ranges[name]) {
  15316. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  15317. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  15318. if (this.animations[i]) {
  15319. this.animations[i].createRange(name, from, to);
  15320. }
  15321. }
  15322. }
  15323. };
  15324. /**
  15325. * Delete a specific animation range
  15326. * @param name defines the name of the range to delete
  15327. * @param deleteFrames defines if animation frames from the range must be deleted as well
  15328. */
  15329. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  15330. if (deleteFrames === void 0) { deleteFrames = true; }
  15331. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  15332. if (this.animations[i]) {
  15333. this.animations[i].deleteRange(name, deleteFrames);
  15334. }
  15335. }
  15336. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  15337. };
  15338. /**
  15339. * Get an animation range by name
  15340. * @param name defines the name of the animation range to look for
  15341. * @returns null if not found else the requested animation range
  15342. */
  15343. Node.prototype.getAnimationRange = function (name) {
  15344. return this._ranges[name];
  15345. };
  15346. /**
  15347. * Will start the animation sequence
  15348. * @param name defines the range frames for animation sequence
  15349. * @param loop defines if the animation should loop (false by default)
  15350. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  15351. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  15352. * @returns the object created for this animation. If range does not exist, it will return null
  15353. */
  15354. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  15355. var range = this.getAnimationRange(name);
  15356. if (!range) {
  15357. return null;
  15358. }
  15359. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  15360. };
  15361. /**
  15362. * Serialize animation ranges into a JSON compatible object
  15363. * @returns serialization object
  15364. */
  15365. Node.prototype.serializeAnimationRanges = function () {
  15366. var serializationRanges = [];
  15367. for (var name in this._ranges) {
  15368. var localRange = this._ranges[name];
  15369. if (!localRange) {
  15370. continue;
  15371. }
  15372. var range = {};
  15373. range.name = name;
  15374. range.from = localRange.from;
  15375. range.to = localRange.to;
  15376. serializationRanges.push(range);
  15377. }
  15378. return serializationRanges;
  15379. };
  15380. /**
  15381. * Computes the world matrix of the node
  15382. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  15383. * @returns the world matrix
  15384. */
  15385. Node.prototype.computeWorldMatrix = function (force) {
  15386. return BABYLON.Matrix.Identity();
  15387. };
  15388. /**
  15389. * Releases all associated resources
  15390. */
  15391. Node.prototype.dispose = function () {
  15392. this.parent = null;
  15393. // Callback
  15394. this.onDisposeObservable.notifyObservers(this);
  15395. this.onDisposeObservable.clear();
  15396. // Behaviors
  15397. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  15398. var behavior = _a[_i];
  15399. behavior.detach();
  15400. }
  15401. this._behaviors = [];
  15402. this._isDisposed = true;
  15403. };
  15404. /**
  15405. * Parse animation range data from a serialization object and store them into a given node
  15406. * @param node defines where to store the animation ranges
  15407. * @param parsedNode defines the serialization object to read data from
  15408. * @param scene defines the hosting scene
  15409. */
  15410. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  15411. if (parsedNode.ranges) {
  15412. for (var index = 0; index < parsedNode.ranges.length; index++) {
  15413. var data = parsedNode.ranges[index];
  15414. node.createAnimationRange(data.name, data.from, data.to);
  15415. }
  15416. }
  15417. };
  15418. __decorate([
  15419. BABYLON.serialize()
  15420. ], Node.prototype, "name", void 0);
  15421. __decorate([
  15422. BABYLON.serialize()
  15423. ], Node.prototype, "id", void 0);
  15424. __decorate([
  15425. BABYLON.serialize()
  15426. ], Node.prototype, "uniqueId", void 0);
  15427. __decorate([
  15428. BABYLON.serialize()
  15429. ], Node.prototype, "state", void 0);
  15430. __decorate([
  15431. BABYLON.serialize()
  15432. ], Node.prototype, "metadata", void 0);
  15433. return Node;
  15434. }());
  15435. BABYLON.Node = Node;
  15436. })(BABYLON || (BABYLON = {}));
  15437. //# sourceMappingURL=babylon.node.js.map
  15438. var BABYLON;
  15439. (function (BABYLON) {
  15440. var BoundingSphere = /** @class */ (function () {
  15441. function BoundingSphere(minimum, maximum) {
  15442. this.minimum = minimum;
  15443. this.maximum = maximum;
  15444. this._tempRadiusVector = BABYLON.Vector3.Zero();
  15445. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  15446. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  15447. this.radius = distance * 0.5;
  15448. this.centerWorld = BABYLON.Vector3.Zero();
  15449. this._update(BABYLON.Matrix.Identity());
  15450. }
  15451. // Methods
  15452. BoundingSphere.prototype._update = function (world) {
  15453. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  15454. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  15455. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  15456. };
  15457. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  15458. for (var i = 0; i < 6; i++) {
  15459. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  15460. return false;
  15461. }
  15462. return true;
  15463. };
  15464. BoundingSphere.prototype.intersectsPoint = function (point) {
  15465. var x = this.centerWorld.x - point.x;
  15466. var y = this.centerWorld.y - point.y;
  15467. var z = this.centerWorld.z - point.z;
  15468. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  15469. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  15470. return false;
  15471. return true;
  15472. };
  15473. // Statics
  15474. BoundingSphere.Intersects = function (sphere0, sphere1) {
  15475. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  15476. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  15477. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  15478. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  15479. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  15480. return false;
  15481. return true;
  15482. };
  15483. return BoundingSphere;
  15484. }());
  15485. BABYLON.BoundingSphere = BoundingSphere;
  15486. })(BABYLON || (BABYLON = {}));
  15487. //# sourceMappingURL=babylon.boundingSphere.js.map
  15488. var BABYLON;
  15489. (function (BABYLON) {
  15490. var BoundingBox = /** @class */ (function () {
  15491. function BoundingBox(minimum, maximum) {
  15492. this.minimum = minimum;
  15493. this.maximum = maximum;
  15494. this.vectors = new Array();
  15495. this.vectorsWorld = new Array();
  15496. // Bounding vectors
  15497. this.vectors.push(this.minimum.clone());
  15498. this.vectors.push(this.maximum.clone());
  15499. this.vectors.push(this.minimum.clone());
  15500. this.vectors[2].x = this.maximum.x;
  15501. this.vectors.push(this.minimum.clone());
  15502. this.vectors[3].y = this.maximum.y;
  15503. this.vectors.push(this.minimum.clone());
  15504. this.vectors[4].z = this.maximum.z;
  15505. this.vectors.push(this.maximum.clone());
  15506. this.vectors[5].z = this.minimum.z;
  15507. this.vectors.push(this.maximum.clone());
  15508. this.vectors[6].x = this.minimum.x;
  15509. this.vectors.push(this.maximum.clone());
  15510. this.vectors[7].y = this.minimum.y;
  15511. // OBB
  15512. this.center = this.maximum.add(this.minimum).scale(0.5);
  15513. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  15514. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  15515. // World
  15516. for (var index = 0; index < this.vectors.length; index++) {
  15517. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  15518. }
  15519. this.minimumWorld = BABYLON.Vector3.Zero();
  15520. this.maximumWorld = BABYLON.Vector3.Zero();
  15521. this.centerWorld = BABYLON.Vector3.Zero();
  15522. this.extendSizeWorld = BABYLON.Vector3.Zero();
  15523. this._update(BABYLON.Matrix.Identity());
  15524. }
  15525. // Methods
  15526. BoundingBox.prototype.getWorldMatrix = function () {
  15527. return this._worldMatrix;
  15528. };
  15529. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  15530. this._worldMatrix.copyFrom(matrix);
  15531. return this;
  15532. };
  15533. BoundingBox.prototype._update = function (world) {
  15534. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  15535. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  15536. for (var index = 0; index < this.vectors.length; index++) {
  15537. var v = this.vectorsWorld[index];
  15538. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  15539. if (v.x < this.minimumWorld.x)
  15540. this.minimumWorld.x = v.x;
  15541. if (v.y < this.minimumWorld.y)
  15542. this.minimumWorld.y = v.y;
  15543. if (v.z < this.minimumWorld.z)
  15544. this.minimumWorld.z = v.z;
  15545. if (v.x > this.maximumWorld.x)
  15546. this.maximumWorld.x = v.x;
  15547. if (v.y > this.maximumWorld.y)
  15548. this.maximumWorld.y = v.y;
  15549. if (v.z > this.maximumWorld.z)
  15550. this.maximumWorld.z = v.z;
  15551. }
  15552. // Extend
  15553. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  15554. this.extendSizeWorld.scaleInPlace(0.5);
  15555. // OBB
  15556. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  15557. this.centerWorld.scaleInPlace(0.5);
  15558. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  15559. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  15560. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  15561. this._worldMatrix = world;
  15562. };
  15563. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  15564. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  15565. };
  15566. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  15567. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  15568. };
  15569. BoundingBox.prototype.intersectsPoint = function (point) {
  15570. var delta = -BABYLON.Epsilon;
  15571. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  15572. return false;
  15573. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  15574. return false;
  15575. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  15576. return false;
  15577. return true;
  15578. };
  15579. BoundingBox.prototype.intersectsSphere = function (sphere) {
  15580. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  15581. };
  15582. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  15583. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  15584. return false;
  15585. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  15586. return false;
  15587. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  15588. return false;
  15589. return true;
  15590. };
  15591. // Statics
  15592. BoundingBox.Intersects = function (box0, box1) {
  15593. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  15594. return false;
  15595. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  15596. return false;
  15597. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  15598. return false;
  15599. return true;
  15600. };
  15601. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  15602. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  15603. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  15604. return (num <= (sphereRadius * sphereRadius));
  15605. };
  15606. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  15607. for (var p = 0; p < 6; p++) {
  15608. for (var i = 0; i < 8; i++) {
  15609. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  15610. return false;
  15611. }
  15612. }
  15613. }
  15614. return true;
  15615. };
  15616. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  15617. for (var p = 0; p < 6; p++) {
  15618. var inCount = 8;
  15619. for (var i = 0; i < 8; i++) {
  15620. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  15621. --inCount;
  15622. }
  15623. else {
  15624. break;
  15625. }
  15626. }
  15627. if (inCount === 0)
  15628. return false;
  15629. }
  15630. return true;
  15631. };
  15632. return BoundingBox;
  15633. }());
  15634. BABYLON.BoundingBox = BoundingBox;
  15635. })(BABYLON || (BABYLON = {}));
  15636. //# sourceMappingURL=babylon.boundingBox.js.map
  15637. var BABYLON;
  15638. (function (BABYLON) {
  15639. var computeBoxExtents = function (axis, box) {
  15640. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  15641. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  15642. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  15643. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  15644. var r = r0 + r1 + r2;
  15645. return {
  15646. min: p - r,
  15647. max: p + r
  15648. };
  15649. };
  15650. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  15651. var axisOverlap = function (axis, box0, box1) {
  15652. var result0 = computeBoxExtents(axis, box0);
  15653. var result1 = computeBoxExtents(axis, box1);
  15654. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  15655. };
  15656. var BoundingInfo = /** @class */ (function () {
  15657. function BoundingInfo(minimum, maximum) {
  15658. this.minimum = minimum;
  15659. this.maximum = maximum;
  15660. this._isLocked = false;
  15661. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  15662. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  15663. }
  15664. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  15665. get: function () {
  15666. return this._isLocked;
  15667. },
  15668. set: function (value) {
  15669. this._isLocked = value;
  15670. },
  15671. enumerable: true,
  15672. configurable: true
  15673. });
  15674. // Methods
  15675. BoundingInfo.prototype.update = function (world) {
  15676. if (this._isLocked) {
  15677. return;
  15678. }
  15679. this.boundingBox._update(world);
  15680. this.boundingSphere._update(world);
  15681. };
  15682. /**
  15683. * Recreate the bounding info to be centered around a specific point given a specific extend.
  15684. * @param center New center of the bounding info
  15685. * @param extend New extend of the bounding info
  15686. */
  15687. BoundingInfo.prototype.centerOn = function (center, extend) {
  15688. this.minimum = center.subtract(extend);
  15689. this.maximum = center.add(extend);
  15690. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  15691. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  15692. return this;
  15693. };
  15694. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  15695. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  15696. return false;
  15697. return this.boundingBox.isInFrustum(frustumPlanes);
  15698. };
  15699. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  15700. /**
  15701. * Gets the world distance between the min and max points of the bounding box
  15702. */
  15703. get: function () {
  15704. var boundingBox = this.boundingBox;
  15705. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  15706. return size.length();
  15707. },
  15708. enumerable: true,
  15709. configurable: true
  15710. });
  15711. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  15712. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  15713. };
  15714. BoundingInfo.prototype._checkCollision = function (collider) {
  15715. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  15716. };
  15717. BoundingInfo.prototype.intersectsPoint = function (point) {
  15718. if (!this.boundingSphere.centerWorld) {
  15719. return false;
  15720. }
  15721. if (!this.boundingSphere.intersectsPoint(point)) {
  15722. return false;
  15723. }
  15724. if (!this.boundingBox.intersectsPoint(point)) {
  15725. return false;
  15726. }
  15727. return true;
  15728. };
  15729. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  15730. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  15731. return false;
  15732. }
  15733. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  15734. return false;
  15735. }
  15736. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  15737. return false;
  15738. }
  15739. if (!precise) {
  15740. return true;
  15741. }
  15742. var box0 = this.boundingBox;
  15743. var box1 = boundingInfo.boundingBox;
  15744. if (!axisOverlap(box0.directions[0], box0, box1))
  15745. return false;
  15746. if (!axisOverlap(box0.directions[1], box0, box1))
  15747. return false;
  15748. if (!axisOverlap(box0.directions[2], box0, box1))
  15749. return false;
  15750. if (!axisOverlap(box1.directions[0], box0, box1))
  15751. return false;
  15752. if (!axisOverlap(box1.directions[1], box0, box1))
  15753. return false;
  15754. if (!axisOverlap(box1.directions[2], box0, box1))
  15755. return false;
  15756. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  15757. return false;
  15758. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  15759. return false;
  15760. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  15761. return false;
  15762. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  15763. return false;
  15764. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  15765. return false;
  15766. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  15767. return false;
  15768. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  15769. return false;
  15770. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  15771. return false;
  15772. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  15773. return false;
  15774. return true;
  15775. };
  15776. return BoundingInfo;
  15777. }());
  15778. BABYLON.BoundingInfo = BoundingInfo;
  15779. })(BABYLON || (BABYLON = {}));
  15780. //# sourceMappingURL=babylon.boundingInfo.js.map
  15781. var BABYLON;
  15782. (function (BABYLON) {
  15783. var TransformNode = /** @class */ (function (_super) {
  15784. __extends(TransformNode, _super);
  15785. function TransformNode(name, scene, isPure) {
  15786. if (scene === void 0) { scene = null; }
  15787. if (isPure === void 0) { isPure = true; }
  15788. var _this = _super.call(this, name, scene) || this;
  15789. // Properties
  15790. _this._rotation = BABYLON.Vector3.Zero();
  15791. _this._scaling = BABYLON.Vector3.One();
  15792. _this._isDirty = false;
  15793. _this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_NONE;
  15794. _this.scalingDeterminant = 1;
  15795. _this.infiniteDistance = false;
  15796. _this.position = BABYLON.Vector3.Zero();
  15797. _this._localWorld = BABYLON.Matrix.Zero();
  15798. _this._worldMatrix = BABYLON.Matrix.Zero();
  15799. _this._worldMatrixDeterminant = 0;
  15800. _this._absolutePosition = BABYLON.Vector3.Zero();
  15801. _this._pivotMatrix = BABYLON.Matrix.Identity();
  15802. _this._postMultiplyPivotMatrix = false;
  15803. _this._isWorldMatrixFrozen = false;
  15804. /**
  15805. * An event triggered after the world matrix is updated
  15806. * @type {BABYLON.Observable}
  15807. */
  15808. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  15809. _this._nonUniformScaling = false;
  15810. if (isPure) {
  15811. _this.getScene().addTransformNode(_this);
  15812. }
  15813. return _this;
  15814. }
  15815. Object.defineProperty(TransformNode.prototype, "rotation", {
  15816. /**
  15817. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  15818. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  15819. * Default : (0.0, 0.0, 0.0)
  15820. */
  15821. get: function () {
  15822. return this._rotation;
  15823. },
  15824. set: function (newRotation) {
  15825. this._rotation = newRotation;
  15826. },
  15827. enumerable: true,
  15828. configurable: true
  15829. });
  15830. Object.defineProperty(TransformNode.prototype, "scaling", {
  15831. /**
  15832. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  15833. * Default : (1.0, 1.0, 1.0)
  15834. */
  15835. get: function () {
  15836. return this._scaling;
  15837. },
  15838. /**
  15839. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  15840. * Default : (1.0, 1.0, 1.0)
  15841. */
  15842. set: function (newScaling) {
  15843. this._scaling = newScaling;
  15844. },
  15845. enumerable: true,
  15846. configurable: true
  15847. });
  15848. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  15849. /**
  15850. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  15851. * It's null by default.
  15852. * 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)
  15853. */
  15854. get: function () {
  15855. return this._rotationQuaternion;
  15856. },
  15857. set: function (quaternion) {
  15858. this._rotationQuaternion = quaternion;
  15859. //reset the rotation vector.
  15860. if (quaternion && this.rotation.length()) {
  15861. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  15862. }
  15863. },
  15864. enumerable: true,
  15865. configurable: true
  15866. });
  15867. /**
  15868. * Returns the latest update of the World matrix
  15869. * Returns a Matrix.
  15870. */
  15871. TransformNode.prototype.getWorldMatrix = function () {
  15872. if (this._currentRenderId !== this.getScene().getRenderId()) {
  15873. this.computeWorldMatrix();
  15874. }
  15875. return this._worldMatrix;
  15876. };
  15877. /**
  15878. * Returns the latest update of the World matrix determinant.
  15879. */
  15880. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  15881. return this._worldMatrixDeterminant;
  15882. };
  15883. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  15884. /**
  15885. * Returns directly the latest state of the mesh World matrix.
  15886. * A Matrix is returned.
  15887. */
  15888. get: function () {
  15889. return this._worldMatrix;
  15890. },
  15891. enumerable: true,
  15892. configurable: true
  15893. });
  15894. /**
  15895. * Copies the paramater passed Matrix into the mesh Pose matrix.
  15896. * Returns the AbstractMesh.
  15897. */
  15898. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  15899. this._poseMatrix.copyFrom(matrix);
  15900. return this;
  15901. };
  15902. /**
  15903. * Returns the mesh Pose matrix.
  15904. * Returned object : Matrix
  15905. */
  15906. TransformNode.prototype.getPoseMatrix = function () {
  15907. return this._poseMatrix;
  15908. };
  15909. TransformNode.prototype._isSynchronized = function () {
  15910. if (this._isDirty) {
  15911. return false;
  15912. }
  15913. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE)
  15914. return false;
  15915. if (this._cache.pivotMatrixUpdated) {
  15916. return false;
  15917. }
  15918. if (this.infiniteDistance) {
  15919. return false;
  15920. }
  15921. if (!this._cache.position.equals(this.position))
  15922. return false;
  15923. if (this.rotationQuaternion) {
  15924. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  15925. return false;
  15926. }
  15927. if (!this._cache.rotation.equals(this.rotation))
  15928. return false;
  15929. if (!this._cache.scaling.equals(this.scaling))
  15930. return false;
  15931. return true;
  15932. };
  15933. TransformNode.prototype._initCache = function () {
  15934. _super.prototype._initCache.call(this);
  15935. this._cache.localMatrixUpdated = false;
  15936. this._cache.position = BABYLON.Vector3.Zero();
  15937. this._cache.scaling = BABYLON.Vector3.Zero();
  15938. this._cache.rotation = BABYLON.Vector3.Zero();
  15939. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  15940. this._cache.billboardMode = -1;
  15941. };
  15942. TransformNode.prototype.markAsDirty = function (property) {
  15943. if (property === "rotation") {
  15944. this.rotationQuaternion = null;
  15945. }
  15946. this._currentRenderId = Number.MAX_VALUE;
  15947. this._isDirty = true;
  15948. return this;
  15949. };
  15950. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  15951. /**
  15952. * Returns the current mesh absolute position.
  15953. * Retuns a Vector3.
  15954. */
  15955. get: function () {
  15956. return this._absolutePosition;
  15957. },
  15958. enumerable: true,
  15959. configurable: true
  15960. });
  15961. /**
  15962. * Sets a new matrix to apply before all other transformation
  15963. * @param matrix defines the transform matrix
  15964. * @returns the current TransformNode
  15965. */
  15966. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  15967. return this.setPivotMatrix(matrix, false);
  15968. };
  15969. /**
  15970. * Sets a new pivot matrix to the current node
  15971. * @param matrix defines the new pivot matrix to use
  15972. * @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
  15973. * @returns the current TransformNode
  15974. */
  15975. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  15976. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  15977. this._pivotMatrix = matrix.clone();
  15978. this._cache.pivotMatrixUpdated = true;
  15979. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  15980. if (this._postMultiplyPivotMatrix) {
  15981. if (!this._pivotMatrixInverse) {
  15982. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  15983. }
  15984. else {
  15985. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  15986. }
  15987. }
  15988. return this;
  15989. };
  15990. /**
  15991. * Returns the mesh pivot matrix.
  15992. * Default : Identity.
  15993. * A Matrix is returned.
  15994. */
  15995. TransformNode.prototype.getPivotMatrix = function () {
  15996. return this._pivotMatrix;
  15997. };
  15998. /**
  15999. * Prevents the World matrix to be computed any longer.
  16000. * Returns the AbstractMesh.
  16001. */
  16002. TransformNode.prototype.freezeWorldMatrix = function () {
  16003. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  16004. this.computeWorldMatrix(true);
  16005. this._isWorldMatrixFrozen = true;
  16006. return this;
  16007. };
  16008. /**
  16009. * Allows back the World matrix computation.
  16010. * Returns the AbstractMesh.
  16011. */
  16012. TransformNode.prototype.unfreezeWorldMatrix = function () {
  16013. this._isWorldMatrixFrozen = false;
  16014. this.computeWorldMatrix(true);
  16015. return this;
  16016. };
  16017. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  16018. /**
  16019. * True if the World matrix has been frozen.
  16020. * Returns a boolean.
  16021. */
  16022. get: function () {
  16023. return this._isWorldMatrixFrozen;
  16024. },
  16025. enumerable: true,
  16026. configurable: true
  16027. });
  16028. /**
  16029. * Retuns the mesh absolute position in the World.
  16030. * Returns a Vector3.
  16031. */
  16032. TransformNode.prototype.getAbsolutePosition = function () {
  16033. this.computeWorldMatrix();
  16034. return this._absolutePosition;
  16035. };
  16036. /**
  16037. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  16038. * Returns the AbstractMesh.
  16039. */
  16040. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  16041. if (!absolutePosition) {
  16042. return this;
  16043. }
  16044. var absolutePositionX;
  16045. var absolutePositionY;
  16046. var absolutePositionZ;
  16047. if (absolutePosition.x === undefined) {
  16048. if (arguments.length < 3) {
  16049. return this;
  16050. }
  16051. absolutePositionX = arguments[0];
  16052. absolutePositionY = arguments[1];
  16053. absolutePositionZ = arguments[2];
  16054. }
  16055. else {
  16056. absolutePositionX = absolutePosition.x;
  16057. absolutePositionY = absolutePosition.y;
  16058. absolutePositionZ = absolutePosition.z;
  16059. }
  16060. if (this.parent) {
  16061. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  16062. invertParentWorldMatrix.invert();
  16063. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  16064. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  16065. }
  16066. else {
  16067. this.position.x = absolutePositionX;
  16068. this.position.y = absolutePositionY;
  16069. this.position.z = absolutePositionZ;
  16070. }
  16071. return this;
  16072. };
  16073. /**
  16074. * Sets the mesh position in its local space.
  16075. * Returns the AbstractMesh.
  16076. */
  16077. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  16078. this.computeWorldMatrix();
  16079. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  16080. return this;
  16081. };
  16082. /**
  16083. * Returns the mesh position in the local space from the current World matrix values.
  16084. * Returns a new Vector3.
  16085. */
  16086. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  16087. this.computeWorldMatrix();
  16088. var invLocalWorldMatrix = this._localWorld.clone();
  16089. invLocalWorldMatrix.invert();
  16090. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  16091. };
  16092. /**
  16093. * Translates the mesh along the passed Vector3 in its local space.
  16094. * Returns the AbstractMesh.
  16095. */
  16096. TransformNode.prototype.locallyTranslate = function (vector3) {
  16097. this.computeWorldMatrix(true);
  16098. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  16099. return this;
  16100. };
  16101. /**
  16102. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  16103. * @param targetPoint the position (must be in same space as current mesh) to look at
  16104. * @param yawCor optional yaw (y-axis) correction in radians
  16105. * @param pitchCor optional pitch (x-axis) correction in radians
  16106. * @param rollCor optional roll (z-axis) correction in radians
  16107. * @param space the choosen space of the target
  16108. * @returns the TransformNode.
  16109. */
  16110. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  16111. if (yawCor === void 0) { yawCor = 0; }
  16112. if (pitchCor === void 0) { pitchCor = 0; }
  16113. if (rollCor === void 0) { rollCor = 0; }
  16114. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  16115. var dv = BABYLON.AbstractMesh._lookAtVectorCache;
  16116. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  16117. targetPoint.subtractToRef(pos, dv);
  16118. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  16119. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  16120. var pitch = Math.atan2(dv.y, len);
  16121. if (this.rotationQuaternion) {
  16122. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  16123. }
  16124. else {
  16125. this.rotation.x = pitch + pitchCor;
  16126. this.rotation.y = yaw + yawCor;
  16127. this.rotation.z = rollCor;
  16128. }
  16129. return this;
  16130. };
  16131. /**
  16132. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  16133. * This Vector3 is expressed in the World space.
  16134. */
  16135. TransformNode.prototype.getDirection = function (localAxis) {
  16136. var result = BABYLON.Vector3.Zero();
  16137. this.getDirectionToRef(localAxis, result);
  16138. return result;
  16139. };
  16140. /**
  16141. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  16142. * localAxis is expressed in the mesh local space.
  16143. * result is computed in the Wordl space from the mesh World matrix.
  16144. * Returns the AbstractMesh.
  16145. */
  16146. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  16147. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  16148. return this;
  16149. };
  16150. /**
  16151. * Sets a new pivot point to the current node
  16152. * @param point defines the new pivot point to use
  16153. * @param space defines if the point is in world or local space (local by default)
  16154. * @returns the current TransformNode
  16155. */
  16156. TransformNode.prototype.setPivotPoint = function (point, space) {
  16157. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  16158. if (this.getScene().getRenderId() == 0) {
  16159. this.computeWorldMatrix(true);
  16160. }
  16161. var wm = this.getWorldMatrix();
  16162. if (space == BABYLON.Space.WORLD) {
  16163. var tmat = BABYLON.Tmp.Matrix[0];
  16164. wm.invertToRef(tmat);
  16165. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  16166. }
  16167. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  16168. };
  16169. /**
  16170. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  16171. */
  16172. TransformNode.prototype.getPivotPoint = function () {
  16173. var point = BABYLON.Vector3.Zero();
  16174. this.getPivotPointToRef(point);
  16175. return point;
  16176. };
  16177. /**
  16178. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  16179. * Returns the AbstractMesh.
  16180. */
  16181. TransformNode.prototype.getPivotPointToRef = function (result) {
  16182. result.x = -this._pivotMatrix.m[12];
  16183. result.y = -this._pivotMatrix.m[13];
  16184. result.z = -this._pivotMatrix.m[14];
  16185. return this;
  16186. };
  16187. /**
  16188. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  16189. */
  16190. TransformNode.prototype.getAbsolutePivotPoint = function () {
  16191. var point = BABYLON.Vector3.Zero();
  16192. this.getAbsolutePivotPointToRef(point);
  16193. return point;
  16194. };
  16195. /**
  16196. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  16197. * Returns the AbstractMesh.
  16198. */
  16199. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  16200. result.x = this._pivotMatrix.m[12];
  16201. result.y = this._pivotMatrix.m[13];
  16202. result.z = this._pivotMatrix.m[14];
  16203. this.getPivotPointToRef(result);
  16204. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  16205. return this;
  16206. };
  16207. /**
  16208. * Defines the passed node as the parent of the current node.
  16209. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  16210. * Returns the TransformNode.
  16211. */
  16212. TransformNode.prototype.setParent = function (node) {
  16213. if (node === null) {
  16214. var rotation = BABYLON.Tmp.Quaternion[0];
  16215. var position = BABYLON.Tmp.Vector3[0];
  16216. var scale = BABYLON.Tmp.Vector3[1];
  16217. if (this.parent && this.parent.computeWorldMatrix) {
  16218. this.parent.computeWorldMatrix(true);
  16219. }
  16220. this.computeWorldMatrix(true);
  16221. this.getWorldMatrix().decompose(scale, rotation, position);
  16222. if (this.rotationQuaternion) {
  16223. this.rotationQuaternion.copyFrom(rotation);
  16224. }
  16225. else {
  16226. rotation.toEulerAnglesToRef(this.rotation);
  16227. }
  16228. this.scaling.x = scale.x;
  16229. this.scaling.y = scale.y;
  16230. this.scaling.z = scale.z;
  16231. this.position.x = position.x;
  16232. this.position.y = position.y;
  16233. this.position.z = position.z;
  16234. }
  16235. else {
  16236. var rotation = BABYLON.Tmp.Quaternion[0];
  16237. var position = BABYLON.Tmp.Vector3[0];
  16238. var scale = BABYLON.Tmp.Vector3[1];
  16239. var diffMatrix = BABYLON.Tmp.Matrix[0];
  16240. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  16241. this.computeWorldMatrix(true);
  16242. node.computeWorldMatrix(true);
  16243. node.getWorldMatrix().invertToRef(invParentMatrix);
  16244. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  16245. diffMatrix.decompose(scale, rotation, position);
  16246. if (this.rotationQuaternion) {
  16247. this.rotationQuaternion.copyFrom(rotation);
  16248. }
  16249. else {
  16250. rotation.toEulerAnglesToRef(this.rotation);
  16251. }
  16252. this.position.x = position.x;
  16253. this.position.y = position.y;
  16254. this.position.z = position.z;
  16255. this.scaling.x = scale.x;
  16256. this.scaling.y = scale.y;
  16257. this.scaling.z = scale.z;
  16258. }
  16259. this.parent = node;
  16260. return this;
  16261. };
  16262. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  16263. get: function () {
  16264. return this._nonUniformScaling;
  16265. },
  16266. enumerable: true,
  16267. configurable: true
  16268. });
  16269. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  16270. if (this._nonUniformScaling === value) {
  16271. return false;
  16272. }
  16273. this._nonUniformScaling = true;
  16274. return true;
  16275. };
  16276. /**
  16277. * Attach the current TransformNode to another TransformNode associated with a bone
  16278. * @param bone Bone affecting the TransformNode
  16279. * @param affectedTransformNode TransformNode associated with the bone
  16280. */
  16281. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  16282. this._transformToBoneReferal = affectedTransformNode;
  16283. this.parent = bone;
  16284. if (bone.getWorldMatrix().determinant() < 0) {
  16285. this.scalingDeterminant *= -1;
  16286. }
  16287. return this;
  16288. };
  16289. TransformNode.prototype.detachFromBone = function () {
  16290. if (!this.parent) {
  16291. return this;
  16292. }
  16293. if (this.parent.getWorldMatrix().determinant() < 0) {
  16294. this.scalingDeterminant *= -1;
  16295. }
  16296. this._transformToBoneReferal = null;
  16297. this.parent = null;
  16298. return this;
  16299. };
  16300. /**
  16301. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  16302. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  16303. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  16304. * The passed axis is also normalized.
  16305. * Returns the AbstractMesh.
  16306. */
  16307. TransformNode.prototype.rotate = function (axis, amount, space) {
  16308. axis.normalize();
  16309. if (!this.rotationQuaternion) {
  16310. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  16311. this.rotation = BABYLON.Vector3.Zero();
  16312. }
  16313. var rotationQuaternion;
  16314. if (!space || space === BABYLON.Space.LOCAL) {
  16315. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  16316. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  16317. }
  16318. else {
  16319. if (this.parent) {
  16320. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  16321. invertParentWorldMatrix.invert();
  16322. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  16323. }
  16324. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  16325. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  16326. }
  16327. return this;
  16328. };
  16329. /**
  16330. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  16331. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  16332. * The passed axis is also normalized.
  16333. * Returns the AbstractMesh.
  16334. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  16335. */
  16336. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  16337. axis.normalize();
  16338. if (!this.rotationQuaternion) {
  16339. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  16340. this.rotation.copyFromFloats(0, 0, 0);
  16341. }
  16342. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  16343. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  16344. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  16345. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  16346. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  16347. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  16348. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  16349. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  16350. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  16351. return this;
  16352. };
  16353. /**
  16354. * Translates the mesh along the axis vector for the passed distance in the given space.
  16355. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  16356. * Returns the AbstractMesh.
  16357. */
  16358. TransformNode.prototype.translate = function (axis, distance, space) {
  16359. var displacementVector = axis.scale(distance);
  16360. if (!space || space === BABYLON.Space.LOCAL) {
  16361. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  16362. this.setPositionWithLocalVector(tempV3);
  16363. }
  16364. else {
  16365. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  16366. }
  16367. return this;
  16368. };
  16369. /**
  16370. * Adds a rotation step to the mesh current rotation.
  16371. * x, y, z are Euler angles expressed in radians.
  16372. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  16373. * This means this rotation is made in the mesh local space only.
  16374. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  16375. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  16376. * ```javascript
  16377. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  16378. * ```
  16379. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  16380. * 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.
  16381. * Returns the AbstractMesh.
  16382. */
  16383. TransformNode.prototype.addRotation = function (x, y, z) {
  16384. var rotationQuaternion;
  16385. if (this.rotationQuaternion) {
  16386. rotationQuaternion = this.rotationQuaternion;
  16387. }
  16388. else {
  16389. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  16390. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  16391. }
  16392. var accumulation = BABYLON.Tmp.Quaternion[0];
  16393. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  16394. rotationQuaternion.multiplyInPlace(accumulation);
  16395. if (!this.rotationQuaternion) {
  16396. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  16397. }
  16398. return this;
  16399. };
  16400. /**
  16401. * Computes the mesh World matrix and returns it.
  16402. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  16403. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  16404. * If the parameter `force`is set to `true`, the actual computation is done.
  16405. * Returns the mesh World Matrix.
  16406. */
  16407. TransformNode.prototype.computeWorldMatrix = function (force) {
  16408. if (this._isWorldMatrixFrozen) {
  16409. return this._worldMatrix;
  16410. }
  16411. if (!force && this.isSynchronized(true)) {
  16412. return this._worldMatrix;
  16413. }
  16414. this._cache.position.copyFrom(this.position);
  16415. this._cache.scaling.copyFrom(this.scaling);
  16416. this._cache.pivotMatrixUpdated = false;
  16417. this._cache.billboardMode = this.billboardMode;
  16418. this._currentRenderId = this.getScene().getRenderId();
  16419. this._isDirty = false;
  16420. // Scaling
  16421. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  16422. // Rotation
  16423. //rotate, if quaternion is set and rotation was used
  16424. if (this.rotationQuaternion) {
  16425. var len = this.rotation.length();
  16426. if (len) {
  16427. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  16428. this.rotation.copyFromFloats(0, 0, 0);
  16429. }
  16430. }
  16431. if (this.rotationQuaternion) {
  16432. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  16433. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  16434. }
  16435. else {
  16436. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  16437. this._cache.rotation.copyFrom(this.rotation);
  16438. }
  16439. // Translation
  16440. var camera = this.getScene().activeCamera;
  16441. if (this.infiniteDistance && !this.parent && camera) {
  16442. var cameraWorldMatrix = camera.getWorldMatrix();
  16443. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  16444. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  16445. }
  16446. else {
  16447. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  16448. }
  16449. // Composing transformations
  16450. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  16451. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  16452. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  16453. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE && camera) {
  16454. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_ALL) !== BABYLON.AbstractMesh.BILLBOARDMODE_ALL) {
  16455. // Need to decompose each rotation here
  16456. var currentPosition = BABYLON.Tmp.Vector3[3];
  16457. if (this.parent && this.parent.getWorldMatrix) {
  16458. if (this._transformToBoneReferal) {
  16459. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  16460. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  16461. }
  16462. else {
  16463. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  16464. }
  16465. }
  16466. else {
  16467. currentPosition.copyFrom(this.position);
  16468. }
  16469. currentPosition.subtractInPlace(camera.globalPosition);
  16470. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  16471. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_X) === BABYLON.AbstractMesh.BILLBOARDMODE_X) {
  16472. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  16473. }
  16474. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Y) === BABYLON.AbstractMesh.BILLBOARDMODE_Y) {
  16475. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  16476. }
  16477. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Z) === BABYLON.AbstractMesh.BILLBOARDMODE_Z) {
  16478. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  16479. }
  16480. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  16481. }
  16482. else {
  16483. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  16484. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  16485. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  16486. }
  16487. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  16488. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  16489. }
  16490. // Local world
  16491. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  16492. // Parent
  16493. if (this.parent && this.parent.getWorldMatrix) {
  16494. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE) {
  16495. if (this._transformToBoneReferal) {
  16496. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  16497. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  16498. }
  16499. else {
  16500. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  16501. }
  16502. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  16503. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  16504. this._worldMatrix.copyFrom(this._localWorld);
  16505. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  16506. }
  16507. else {
  16508. if (this._transformToBoneReferal) {
  16509. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  16510. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  16511. }
  16512. else {
  16513. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  16514. }
  16515. }
  16516. this._markSyncedWithParent();
  16517. }
  16518. else {
  16519. this._worldMatrix.copyFrom(this._localWorld);
  16520. }
  16521. // Post multiply inverse of pivotMatrix
  16522. if (this._postMultiplyPivotMatrix) {
  16523. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  16524. }
  16525. // Normal matrix
  16526. if (this.scaling.isNonUniform) {
  16527. this._updateNonUniformScalingState(true);
  16528. }
  16529. else if (this.parent && this.parent._nonUniformScaling) {
  16530. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  16531. }
  16532. else {
  16533. this._updateNonUniformScalingState(false);
  16534. }
  16535. this._afterComputeWorldMatrix();
  16536. // Absolute position
  16537. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  16538. // Callbacks
  16539. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  16540. if (!this._poseMatrix) {
  16541. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  16542. }
  16543. // Cache the determinant
  16544. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  16545. return this._worldMatrix;
  16546. };
  16547. TransformNode.prototype._afterComputeWorldMatrix = function () {
  16548. };
  16549. /**
  16550. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  16551. * @param func: callback function to add
  16552. *
  16553. * Returns the TransformNode.
  16554. */
  16555. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  16556. this.onAfterWorldMatrixUpdateObservable.add(func);
  16557. return this;
  16558. };
  16559. /**
  16560. * Removes a registered callback function.
  16561. * Returns the TransformNode.
  16562. */
  16563. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  16564. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  16565. return this;
  16566. };
  16567. /**
  16568. * Clone the current transform node
  16569. * Returns the new transform node
  16570. * @param name Name of the new clone
  16571. * @param newParent New parent for the clone
  16572. * @param doNotCloneChildren Do not clone children hierarchy
  16573. */
  16574. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  16575. var _this = this;
  16576. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  16577. result.name = name;
  16578. result.id = name;
  16579. if (newParent) {
  16580. result.parent = newParent;
  16581. }
  16582. if (!doNotCloneChildren) {
  16583. // Children
  16584. var directDescendants = this.getDescendants(true);
  16585. for (var index = 0; index < directDescendants.length; index++) {
  16586. var child = directDescendants[index];
  16587. if (child.clone) {
  16588. child.clone(name + "." + child.name, result);
  16589. }
  16590. }
  16591. }
  16592. return result;
  16593. };
  16594. TransformNode.prototype.serialize = function (currentSerializationObject) {
  16595. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  16596. serializationObject.type = this.getClassName();
  16597. // Parent
  16598. if (this.parent) {
  16599. serializationObject.parentId = this.parent.id;
  16600. }
  16601. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  16602. serializationObject.tags = BABYLON.Tags.GetTags(this);
  16603. }
  16604. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  16605. serializationObject.isEnabled = this.isEnabled();
  16606. // Parent
  16607. if (this.parent) {
  16608. serializationObject.parentId = this.parent.id;
  16609. }
  16610. return serializationObject;
  16611. };
  16612. // Statics
  16613. /**
  16614. * Returns a new TransformNode object parsed from the source provided.
  16615. * The parameter `parsedMesh` is the source.
  16616. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  16617. */
  16618. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  16619. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  16620. if (BABYLON.Tags) {
  16621. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  16622. }
  16623. if (parsedTransformNode.localMatrix) {
  16624. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  16625. }
  16626. else if (parsedTransformNode.pivotMatrix) {
  16627. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  16628. }
  16629. transformNode.setEnabled(parsedTransformNode.isEnabled);
  16630. // Parent
  16631. if (parsedTransformNode.parentId) {
  16632. transformNode._waitingParentId = parsedTransformNode.parentId;
  16633. }
  16634. return transformNode;
  16635. };
  16636. /**
  16637. * Disposes the TransformNode.
  16638. * By default, all the children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  16639. * Returns nothing.
  16640. */
  16641. TransformNode.prototype.dispose = function (doNotRecurse) {
  16642. // Animations
  16643. this.getScene().stopAnimation(this);
  16644. // Remove from scene
  16645. this.getScene().removeTransformNode(this);
  16646. if (!doNotRecurse) {
  16647. // Children
  16648. var objects = this.getDescendants(true);
  16649. for (var index = 0; index < objects.length; index++) {
  16650. objects[index].dispose();
  16651. }
  16652. }
  16653. else {
  16654. var childMeshes = this.getChildMeshes(true);
  16655. for (index = 0; index < childMeshes.length; index++) {
  16656. var child = childMeshes[index];
  16657. child.parent = null;
  16658. child.computeWorldMatrix(true);
  16659. }
  16660. }
  16661. this.onAfterWorldMatrixUpdateObservable.clear();
  16662. _super.prototype.dispose.call(this);
  16663. };
  16664. // Statics
  16665. TransformNode.BILLBOARDMODE_NONE = 0;
  16666. TransformNode.BILLBOARDMODE_X = 1;
  16667. TransformNode.BILLBOARDMODE_Y = 2;
  16668. TransformNode.BILLBOARDMODE_Z = 4;
  16669. TransformNode.BILLBOARDMODE_ALL = 7;
  16670. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  16671. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  16672. __decorate([
  16673. BABYLON.serializeAsVector3()
  16674. ], TransformNode.prototype, "_rotation", void 0);
  16675. __decorate([
  16676. BABYLON.serializeAsQuaternion()
  16677. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  16678. __decorate([
  16679. BABYLON.serializeAsVector3()
  16680. ], TransformNode.prototype, "_scaling", void 0);
  16681. __decorate([
  16682. BABYLON.serialize()
  16683. ], TransformNode.prototype, "billboardMode", void 0);
  16684. __decorate([
  16685. BABYLON.serialize()
  16686. ], TransformNode.prototype, "scalingDeterminant", void 0);
  16687. __decorate([
  16688. BABYLON.serialize()
  16689. ], TransformNode.prototype, "infiniteDistance", void 0);
  16690. __decorate([
  16691. BABYLON.serializeAsVector3()
  16692. ], TransformNode.prototype, "position", void 0);
  16693. return TransformNode;
  16694. }(BABYLON.Node));
  16695. BABYLON.TransformNode = TransformNode;
  16696. })(BABYLON || (BABYLON = {}));
  16697. //# sourceMappingURL=babylon.transformNode.js.map
  16698. var BABYLON;
  16699. (function (BABYLON) {
  16700. var AbstractMesh = /** @class */ (function (_super) {
  16701. __extends(AbstractMesh, _super);
  16702. // Constructor
  16703. function AbstractMesh(name, scene) {
  16704. if (scene === void 0) { scene = null; }
  16705. var _this = _super.call(this, name, scene, false) || this;
  16706. _this._facetNb = 0; // facet number
  16707. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  16708. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  16709. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  16710. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  16711. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  16712. _this._subDiv = {
  16713. max: 1,
  16714. X: 1,
  16715. Y: 1,
  16716. Z: 1
  16717. };
  16718. _this._facetDepthSort = false; // is the facet depth sort to be computed
  16719. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  16720. // Events
  16721. /**
  16722. * An event triggered when this mesh collides with another one
  16723. * @type {BABYLON.Observable}
  16724. */
  16725. _this.onCollideObservable = new BABYLON.Observable();
  16726. /**
  16727. * An event triggered when the collision's position changes
  16728. * @type {BABYLON.Observable}
  16729. */
  16730. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  16731. /**
  16732. * An event triggered when material is changed
  16733. * @type {BABYLON.Observable}
  16734. */
  16735. _this.onMaterialChangedObservable = new BABYLON.Observable();
  16736. // Properties
  16737. _this.definedFacingForward = true; // orientation for POV movement & rotation
  16738. /**
  16739. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  16740. * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  16741. * or
  16742. * 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.
  16743. * for more info check WebGl documentations
  16744. */
  16745. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  16746. /**
  16747. * 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:
  16748. * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  16749. * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  16750. * 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.
  16751. */
  16752. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  16753. /**
  16754. * 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.
  16755. * The default value is -1 which means don't break the query and wait till the result.
  16756. */
  16757. _this.occlusionRetryCount = -1;
  16758. _this._occlusionInternalRetryCounter = 0;
  16759. _this._isOccluded = false;
  16760. _this._isOcclusionQueryInProgress = false;
  16761. _this._visibility = 1.0;
  16762. _this.alphaIndex = Number.MAX_VALUE;
  16763. _this.isVisible = true;
  16764. _this.isPickable = true;
  16765. _this.showBoundingBox = false;
  16766. _this.showSubMeshesBoundingBox = false;
  16767. _this.isBlocker = false;
  16768. _this.enablePointerMoveEvents = false;
  16769. _this.renderingGroupId = 0;
  16770. _this._receiveShadows = false;
  16771. _this.renderOutline = false;
  16772. _this.outlineColor = BABYLON.Color3.Red();
  16773. _this.outlineWidth = 0.02;
  16774. _this.renderOverlay = false;
  16775. _this.overlayColor = BABYLON.Color3.Red();
  16776. _this.overlayAlpha = 0.5;
  16777. _this._hasVertexAlpha = false;
  16778. _this._useVertexColors = true;
  16779. _this._computeBonesUsingShaders = true;
  16780. _this._numBoneInfluencers = 4;
  16781. _this._applyFog = true;
  16782. _this.useOctreeForRenderingSelection = true;
  16783. _this.useOctreeForPicking = true;
  16784. _this.useOctreeForCollisions = true;
  16785. _this._layerMask = 0x0FFFFFFF;
  16786. /**
  16787. * True if the mesh must be rendered in any case.
  16788. */
  16789. _this.alwaysSelectAsActiveMesh = false;
  16790. /**
  16791. * This scene's action manager
  16792. * @type {BABYLON.ActionManager}
  16793. */
  16794. _this.actionManager = null;
  16795. // Physics
  16796. _this.physicsImpostor = null;
  16797. // Collisions
  16798. _this._checkCollisions = false;
  16799. _this._collisionMask = -1;
  16800. _this._collisionGroup = -1;
  16801. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  16802. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  16803. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  16804. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  16805. // Edges
  16806. _this.edgesWidth = 1;
  16807. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  16808. // Cache
  16809. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  16810. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  16811. _this._renderId = 0;
  16812. _this._intersectionsInProgress = new Array();
  16813. _this._unIndexed = false;
  16814. _this._lightSources = new Array();
  16815. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  16816. if (collidedMesh === void 0) { collidedMesh = null; }
  16817. //TODO move this to the collision coordinator!
  16818. if (_this.getScene().workerCollisions)
  16819. newPosition.multiplyInPlace(_this._collider._radius);
  16820. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  16821. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  16822. _this.position.addInPlace(_this._diffPositionForCollisions);
  16823. }
  16824. if (collidedMesh) {
  16825. _this.onCollideObservable.notifyObservers(collidedMesh);
  16826. }
  16827. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  16828. };
  16829. _this.getScene().addMesh(_this);
  16830. _this._resyncLightSources();
  16831. return _this;
  16832. }
  16833. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  16834. get: function () {
  16835. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  16836. },
  16837. enumerable: true,
  16838. configurable: true
  16839. });
  16840. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  16841. get: function () {
  16842. return BABYLON.TransformNode.BILLBOARDMODE_X;
  16843. },
  16844. enumerable: true,
  16845. configurable: true
  16846. });
  16847. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  16848. get: function () {
  16849. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  16850. },
  16851. enumerable: true,
  16852. configurable: true
  16853. });
  16854. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  16855. get: function () {
  16856. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  16857. },
  16858. enumerable: true,
  16859. configurable: true
  16860. });
  16861. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  16862. get: function () {
  16863. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  16864. },
  16865. enumerable: true,
  16866. configurable: true
  16867. });
  16868. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  16869. /**
  16870. * Read-only : the number of facets in the mesh
  16871. */
  16872. get: function () {
  16873. return this._facetNb;
  16874. },
  16875. enumerable: true,
  16876. configurable: true
  16877. });
  16878. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  16879. /**
  16880. * The number (integer) of subdivisions per axis in the partioning space
  16881. */
  16882. get: function () {
  16883. return this._partitioningSubdivisions;
  16884. },
  16885. set: function (nb) {
  16886. this._partitioningSubdivisions = nb;
  16887. },
  16888. enumerable: true,
  16889. configurable: true
  16890. });
  16891. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  16892. /**
  16893. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  16894. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  16895. */
  16896. get: function () {
  16897. return this._partitioningBBoxRatio;
  16898. },
  16899. set: function (ratio) {
  16900. this._partitioningBBoxRatio = ratio;
  16901. },
  16902. enumerable: true,
  16903. configurable: true
  16904. });
  16905. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  16906. /**
  16907. * Boolean : must the facet be depth sorted on next call to `updateFacetData()` ?
  16908. * Works only for updatable meshes.
  16909. * Doesn't work with multi-materials.
  16910. */
  16911. get: function () {
  16912. return this._facetDepthSort;
  16913. },
  16914. set: function (sort) {
  16915. this._facetDepthSort = sort;
  16916. },
  16917. enumerable: true,
  16918. configurable: true
  16919. });
  16920. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  16921. /**
  16922. * The location (Vector3) where the facet depth sort must be computed from.
  16923. * By default, the active camera position.
  16924. * Used only when facet depth sort is enabled.
  16925. */
  16926. get: function () {
  16927. return this._facetDepthSortFrom;
  16928. },
  16929. set: function (location) {
  16930. this._facetDepthSortFrom = location;
  16931. },
  16932. enumerable: true,
  16933. configurable: true
  16934. });
  16935. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  16936. /**
  16937. * Read-only boolean : is the feature facetData enabled ?
  16938. */
  16939. get: function () {
  16940. return this._facetDataEnabled;
  16941. },
  16942. enumerable: true,
  16943. configurable: true
  16944. });
  16945. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  16946. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  16947. return false;
  16948. }
  16949. this._markSubMeshesAsMiscDirty();
  16950. return true;
  16951. };
  16952. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  16953. set: function (callback) {
  16954. if (this._onCollideObserver) {
  16955. this.onCollideObservable.remove(this._onCollideObserver);
  16956. }
  16957. this._onCollideObserver = this.onCollideObservable.add(callback);
  16958. },
  16959. enumerable: true,
  16960. configurable: true
  16961. });
  16962. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  16963. set: function (callback) {
  16964. if (this._onCollisionPositionChangeObserver) {
  16965. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  16966. }
  16967. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  16968. },
  16969. enumerable: true,
  16970. configurable: true
  16971. });
  16972. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  16973. /**
  16974. * 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.
  16975. */
  16976. get: function () {
  16977. return this._isOccluded;
  16978. },
  16979. set: function (value) {
  16980. this._isOccluded = value;
  16981. },
  16982. enumerable: true,
  16983. configurable: true
  16984. });
  16985. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  16986. /**
  16987. * Flag to check the progress status of the query
  16988. */
  16989. get: function () {
  16990. return this._isOcclusionQueryInProgress;
  16991. },
  16992. enumerable: true,
  16993. configurable: true
  16994. });
  16995. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  16996. /**
  16997. * Gets or sets mesh visibility between 0 and 1 (defult is 1)
  16998. */
  16999. get: function () {
  17000. return this._visibility;
  17001. },
  17002. /**
  17003. * Gets or sets mesh visibility between 0 and 1 (defult is 1)
  17004. */
  17005. set: function (value) {
  17006. if (this._visibility === value) {
  17007. return;
  17008. }
  17009. this._visibility = value;
  17010. this._markSubMeshesAsMiscDirty();
  17011. },
  17012. enumerable: true,
  17013. configurable: true
  17014. });
  17015. Object.defineProperty(AbstractMesh.prototype, "material", {
  17016. get: function () {
  17017. return this._material;
  17018. },
  17019. set: function (value) {
  17020. if (this._material === value) {
  17021. return;
  17022. }
  17023. this._material = value;
  17024. if (this.onMaterialChangedObservable.hasObservers) {
  17025. this.onMaterialChangedObservable.notifyObservers(this);
  17026. }
  17027. if (!this.subMeshes) {
  17028. return;
  17029. }
  17030. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17031. var subMesh = _a[_i];
  17032. subMesh.setEffect(null);
  17033. }
  17034. },
  17035. enumerable: true,
  17036. configurable: true
  17037. });
  17038. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  17039. get: function () {
  17040. return this._receiveShadows;
  17041. },
  17042. set: function (value) {
  17043. if (this._receiveShadows === value) {
  17044. return;
  17045. }
  17046. this._receiveShadows = value;
  17047. this._markSubMeshesAsLightDirty();
  17048. },
  17049. enumerable: true,
  17050. configurable: true
  17051. });
  17052. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  17053. get: function () {
  17054. return this._hasVertexAlpha;
  17055. },
  17056. set: function (value) {
  17057. if (this._hasVertexAlpha === value) {
  17058. return;
  17059. }
  17060. this._hasVertexAlpha = value;
  17061. this._markSubMeshesAsAttributesDirty();
  17062. this._markSubMeshesAsMiscDirty();
  17063. },
  17064. enumerable: true,
  17065. configurable: true
  17066. });
  17067. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  17068. get: function () {
  17069. return this._useVertexColors;
  17070. },
  17071. set: function (value) {
  17072. if (this._useVertexColors === value) {
  17073. return;
  17074. }
  17075. this._useVertexColors = value;
  17076. this._markSubMeshesAsAttributesDirty();
  17077. },
  17078. enumerable: true,
  17079. configurable: true
  17080. });
  17081. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  17082. get: function () {
  17083. return this._computeBonesUsingShaders;
  17084. },
  17085. set: function (value) {
  17086. if (this._computeBonesUsingShaders === value) {
  17087. return;
  17088. }
  17089. this._computeBonesUsingShaders = value;
  17090. this._markSubMeshesAsAttributesDirty();
  17091. },
  17092. enumerable: true,
  17093. configurable: true
  17094. });
  17095. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  17096. get: function () {
  17097. return this._numBoneInfluencers;
  17098. },
  17099. set: function (value) {
  17100. if (this._numBoneInfluencers === value) {
  17101. return;
  17102. }
  17103. this._numBoneInfluencers = value;
  17104. this._markSubMeshesAsAttributesDirty();
  17105. },
  17106. enumerable: true,
  17107. configurable: true
  17108. });
  17109. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  17110. get: function () {
  17111. return this._applyFog;
  17112. },
  17113. set: function (value) {
  17114. if (this._applyFog === value) {
  17115. return;
  17116. }
  17117. this._applyFog = value;
  17118. this._markSubMeshesAsMiscDirty();
  17119. },
  17120. enumerable: true,
  17121. configurable: true
  17122. });
  17123. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  17124. get: function () {
  17125. return this._layerMask;
  17126. },
  17127. set: function (value) {
  17128. if (value === this._layerMask) {
  17129. return;
  17130. }
  17131. this._layerMask = value;
  17132. this._resyncLightSources();
  17133. },
  17134. enumerable: true,
  17135. configurable: true
  17136. });
  17137. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  17138. get: function () {
  17139. return this._collisionMask;
  17140. },
  17141. set: function (mask) {
  17142. this._collisionMask = !isNaN(mask) ? mask : -1;
  17143. },
  17144. enumerable: true,
  17145. configurable: true
  17146. });
  17147. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  17148. get: function () {
  17149. return this._collisionGroup;
  17150. },
  17151. set: function (mask) {
  17152. this._collisionGroup = !isNaN(mask) ? mask : -1;
  17153. },
  17154. enumerable: true,
  17155. configurable: true
  17156. });
  17157. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  17158. get: function () {
  17159. return null;
  17160. },
  17161. enumerable: true,
  17162. configurable: true
  17163. });
  17164. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  17165. get: function () {
  17166. return this._skeleton;
  17167. },
  17168. set: function (value) {
  17169. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  17170. this._skeleton._unregisterMeshWithPoseMatrix(this);
  17171. }
  17172. if (value && value.needInitialSkinMatrix) {
  17173. value._registerMeshWithPoseMatrix(this);
  17174. }
  17175. this._skeleton = value;
  17176. if (!this._skeleton) {
  17177. this._bonesTransformMatrices = null;
  17178. }
  17179. this._markSubMeshesAsAttributesDirty();
  17180. },
  17181. enumerable: true,
  17182. configurable: true
  17183. });
  17184. /**
  17185. * Returns the string "AbstractMesh"
  17186. */
  17187. AbstractMesh.prototype.getClassName = function () {
  17188. return "AbstractMesh";
  17189. };
  17190. /**
  17191. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  17192. */
  17193. AbstractMesh.prototype.toString = function (fullDetails) {
  17194. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  17195. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  17196. if (this._skeleton) {
  17197. ret += ", skeleton: " + this._skeleton.name;
  17198. }
  17199. if (fullDetails) {
  17200. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  17201. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  17202. }
  17203. return ret;
  17204. };
  17205. AbstractMesh.prototype._rebuild = function () {
  17206. if (this._occlusionQuery) {
  17207. this._occlusionQuery = null;
  17208. }
  17209. if (this._edgesRenderer) {
  17210. this._edgesRenderer._rebuild();
  17211. }
  17212. if (!this.subMeshes) {
  17213. return;
  17214. }
  17215. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17216. var subMesh = _a[_i];
  17217. subMesh._rebuild();
  17218. }
  17219. };
  17220. AbstractMesh.prototype._resyncLightSources = function () {
  17221. this._lightSources.length = 0;
  17222. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  17223. var light = _a[_i];
  17224. if (!light.isEnabled()) {
  17225. continue;
  17226. }
  17227. if (light.canAffectMesh(this)) {
  17228. this._lightSources.push(light);
  17229. }
  17230. }
  17231. this._markSubMeshesAsLightDirty();
  17232. };
  17233. AbstractMesh.prototype._resyncLighSource = function (light) {
  17234. var isIn = light.isEnabled() && light.canAffectMesh(this);
  17235. var index = this._lightSources.indexOf(light);
  17236. if (index === -1) {
  17237. if (!isIn) {
  17238. return;
  17239. }
  17240. this._lightSources.push(light);
  17241. }
  17242. else {
  17243. if (isIn) {
  17244. return;
  17245. }
  17246. this._lightSources.splice(index, 1);
  17247. }
  17248. this._markSubMeshesAsLightDirty();
  17249. };
  17250. AbstractMesh.prototype._removeLightSource = function (light) {
  17251. var index = this._lightSources.indexOf(light);
  17252. if (index === -1) {
  17253. return;
  17254. }
  17255. this._lightSources.splice(index, 1);
  17256. this._markSubMeshesAsLightDirty();
  17257. };
  17258. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  17259. if (!this.subMeshes) {
  17260. return;
  17261. }
  17262. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17263. var subMesh = _a[_i];
  17264. if (subMesh._materialDefines) {
  17265. func(subMesh._materialDefines);
  17266. }
  17267. }
  17268. };
  17269. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  17270. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  17271. };
  17272. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  17273. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  17274. };
  17275. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  17276. if (!this.subMeshes) {
  17277. return;
  17278. }
  17279. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17280. var subMesh = _a[_i];
  17281. var material = subMesh.getMaterial();
  17282. if (material) {
  17283. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  17284. }
  17285. }
  17286. };
  17287. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  17288. /**
  17289. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  17290. * Default : (1.0, 1.0, 1.0)
  17291. */
  17292. get: function () {
  17293. return this._scaling;
  17294. },
  17295. /**
  17296. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  17297. * Default : (1.0, 1.0, 1.0)
  17298. */
  17299. set: function (newScaling) {
  17300. this._scaling = newScaling;
  17301. if (this.physicsImpostor) {
  17302. this.physicsImpostor.forceUpdate();
  17303. }
  17304. },
  17305. enumerable: true,
  17306. configurable: true
  17307. });
  17308. // Methods
  17309. /**
  17310. * Disables the mesh edger rendering mode.
  17311. * Returns the AbstractMesh.
  17312. */
  17313. AbstractMesh.prototype.disableEdgesRendering = function () {
  17314. if (this._edgesRenderer) {
  17315. this._edgesRenderer.dispose();
  17316. this._edgesRenderer = null;
  17317. }
  17318. return this;
  17319. };
  17320. /**
  17321. * Enables the edge rendering mode on the mesh.
  17322. * This mode makes the mesh edges visible.
  17323. * Returns the AbstractMesh.
  17324. */
  17325. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  17326. if (epsilon === void 0) { epsilon = 0.95; }
  17327. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  17328. this.disableEdgesRendering();
  17329. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  17330. return this;
  17331. };
  17332. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  17333. /**
  17334. * Returns true if the mesh is blocked. Used by the class Mesh.
  17335. * Returns the boolean `false` by default.
  17336. */
  17337. get: function () {
  17338. return false;
  17339. },
  17340. enumerable: true,
  17341. configurable: true
  17342. });
  17343. /**
  17344. * Returns the mesh itself by default, used by the class Mesh.
  17345. * Returned type : AbstractMesh
  17346. */
  17347. AbstractMesh.prototype.getLOD = function (camera) {
  17348. return this;
  17349. };
  17350. /**
  17351. * Returns 0 by default, used by the class Mesh.
  17352. * Returns an integer.
  17353. */
  17354. AbstractMesh.prototype.getTotalVertices = function () {
  17355. return 0;
  17356. };
  17357. /**
  17358. * Returns null by default, used by the class Mesh.
  17359. * Returned type : integer array
  17360. */
  17361. AbstractMesh.prototype.getIndices = function () {
  17362. return null;
  17363. };
  17364. /**
  17365. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  17366. * Returned type : float array or Float32Array
  17367. */
  17368. AbstractMesh.prototype.getVerticesData = function (kind) {
  17369. return null;
  17370. };
  17371. /**
  17372. * Sets the vertex data of the mesh geometry for the requested `kind`.
  17373. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  17374. * The `data` are either a numeric array either a Float32Array.
  17375. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  17376. * 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).
  17377. * Note that a new underlying VertexBuffer object is created each call.
  17378. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  17379. *
  17380. * Possible `kind` values :
  17381. * - BABYLON.VertexBuffer.PositionKind
  17382. * - BABYLON.VertexBuffer.UVKind
  17383. * - BABYLON.VertexBuffer.UV2Kind
  17384. * - BABYLON.VertexBuffer.UV3Kind
  17385. * - BABYLON.VertexBuffer.UV4Kind
  17386. * - BABYLON.VertexBuffer.UV5Kind
  17387. * - BABYLON.VertexBuffer.UV6Kind
  17388. * - BABYLON.VertexBuffer.ColorKind
  17389. * - BABYLON.VertexBuffer.MatricesIndicesKind
  17390. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  17391. * - BABYLON.VertexBuffer.MatricesWeightsKind
  17392. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  17393. *
  17394. * Returns the Mesh.
  17395. */
  17396. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  17397. return this;
  17398. };
  17399. /**
  17400. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  17401. * If the mesh has no geometry, it is simply returned as it is.
  17402. * The `data` are either a numeric array either a Float32Array.
  17403. * No new underlying VertexBuffer object is created.
  17404. * 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.
  17405. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  17406. *
  17407. * Possible `kind` values :
  17408. * - BABYLON.VertexBuffer.PositionKind
  17409. * - BABYLON.VertexBuffer.UVKind
  17410. * - BABYLON.VertexBuffer.UV2Kind
  17411. * - BABYLON.VertexBuffer.UV3Kind
  17412. * - BABYLON.VertexBuffer.UV4Kind
  17413. * - BABYLON.VertexBuffer.UV5Kind
  17414. * - BABYLON.VertexBuffer.UV6Kind
  17415. * - BABYLON.VertexBuffer.ColorKind
  17416. * - BABYLON.VertexBuffer.MatricesIndicesKind
  17417. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  17418. * - BABYLON.VertexBuffer.MatricesWeightsKind
  17419. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  17420. *
  17421. * Returns the Mesh.
  17422. */
  17423. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  17424. return this;
  17425. };
  17426. /**
  17427. * Sets the mesh indices.
  17428. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  17429. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  17430. * This method creates a new index buffer each call.
  17431. * Returns the Mesh.
  17432. */
  17433. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  17434. return this;
  17435. };
  17436. /** Returns false by default, used by the class Mesh.
  17437. * Returns a boolean
  17438. */
  17439. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  17440. return false;
  17441. };
  17442. /**
  17443. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  17444. * Returns a BoundingInfo
  17445. */
  17446. AbstractMesh.prototype.getBoundingInfo = function () {
  17447. if (this._masterMesh) {
  17448. return this._masterMesh.getBoundingInfo();
  17449. }
  17450. if (!this._boundingInfo) {
  17451. // this._boundingInfo is being created here
  17452. this._updateBoundingInfo();
  17453. }
  17454. // cannot be null.
  17455. return this._boundingInfo;
  17456. };
  17457. /**
  17458. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units).
  17459. * @param includeDescendants Take the hierarchy's bounding box instead of the mesh's bounding box.
  17460. */
  17461. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  17462. if (includeDescendants === void 0) { includeDescendants = true; }
  17463. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  17464. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  17465. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  17466. if (maxDimension === 0) {
  17467. return this;
  17468. }
  17469. var scale = 1 / maxDimension;
  17470. this.scaling.scaleInPlace(scale);
  17471. return this;
  17472. };
  17473. /**
  17474. * Sets a mesh new object BoundingInfo.
  17475. * Returns the AbstractMesh.
  17476. */
  17477. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  17478. this._boundingInfo = boundingInfo;
  17479. return this;
  17480. };
  17481. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  17482. get: function () {
  17483. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  17484. },
  17485. enumerable: true,
  17486. configurable: true
  17487. });
  17488. AbstractMesh.prototype._preActivate = function () {
  17489. };
  17490. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  17491. };
  17492. AbstractMesh.prototype._activate = function (renderId) {
  17493. this._renderId = renderId;
  17494. };
  17495. /**
  17496. * Returns the latest update of the World matrix
  17497. * Returns a Matrix.
  17498. */
  17499. AbstractMesh.prototype.getWorldMatrix = function () {
  17500. if (this._masterMesh) {
  17501. return this._masterMesh.getWorldMatrix();
  17502. }
  17503. return _super.prototype.getWorldMatrix.call(this);
  17504. };
  17505. /**
  17506. * Returns the latest update of the World matrix determinant.
  17507. */
  17508. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  17509. if (this._masterMesh) {
  17510. return this._masterMesh._getWorldMatrixDeterminant();
  17511. }
  17512. return _super.prototype._getWorldMatrixDeterminant.call(this);
  17513. };
  17514. // ================================== Point of View Movement =================================
  17515. /**
  17516. * Perform relative position change from the point of view of behind the front of the mesh.
  17517. * This is performed taking into account the meshes current rotation, so you do not have to care.
  17518. * Supports definition of mesh facing forward or backward.
  17519. * @param {number} amountRight
  17520. * @param {number} amountUp
  17521. * @param {number} amountForward
  17522. *
  17523. * Returns the AbstractMesh.
  17524. */
  17525. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  17526. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  17527. return this;
  17528. };
  17529. /**
  17530. * Calculate relative position change from the point of view of behind the front of the mesh.
  17531. * This is performed taking into account the meshes current rotation, so you do not have to care.
  17532. * Supports definition of mesh facing forward or backward.
  17533. * @param {number} amountRight
  17534. * @param {number} amountUp
  17535. * @param {number} amountForward
  17536. *
  17537. * Returns a new Vector3.
  17538. */
  17539. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  17540. var rotMatrix = new BABYLON.Matrix();
  17541. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  17542. rotQuaternion.toRotationMatrix(rotMatrix);
  17543. var translationDelta = BABYLON.Vector3.Zero();
  17544. var defForwardMult = this.definedFacingForward ? -1 : 1;
  17545. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  17546. return translationDelta;
  17547. };
  17548. // ================================== Point of View Rotation =================================
  17549. /**
  17550. * Perform relative rotation change from the point of view of behind the front of the mesh.
  17551. * Supports definition of mesh facing forward or backward.
  17552. * @param {number} flipBack
  17553. * @param {number} twirlClockwise
  17554. * @param {number} tiltRight
  17555. *
  17556. * Returns the AbstractMesh.
  17557. */
  17558. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  17559. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  17560. return this;
  17561. };
  17562. /**
  17563. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  17564. * Supports definition of mesh facing forward or backward.
  17565. * @param {number} flipBack
  17566. * @param {number} twirlClockwise
  17567. * @param {number} tiltRight
  17568. *
  17569. * Returns a new Vector3.
  17570. */
  17571. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  17572. var defForwardMult = this.definedFacingForward ? 1 : -1;
  17573. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  17574. };
  17575. /**
  17576. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  17577. * @param includeDescendants Include bounding info from descendants as well (true by default).
  17578. */
  17579. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants) {
  17580. if (includeDescendants === void 0) { includeDescendants = true; }
  17581. this.computeWorldMatrix(true);
  17582. var min;
  17583. var max;
  17584. var boundingInfo = this.getBoundingInfo();
  17585. if (!this.subMeshes) {
  17586. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  17587. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  17588. }
  17589. else {
  17590. min = boundingInfo.boundingBox.minimumWorld;
  17591. max = boundingInfo.boundingBox.maximumWorld;
  17592. }
  17593. if (includeDescendants) {
  17594. var descendants = this.getDescendants(false);
  17595. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  17596. var descendant = descendants_1[_i];
  17597. var childMesh = descendant;
  17598. childMesh.computeWorldMatrix(true);
  17599. //make sure we have the needed params to get mix and max
  17600. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  17601. continue;
  17602. }
  17603. var childBoundingInfo = childMesh.getBoundingInfo();
  17604. var boundingBox = childBoundingInfo.boundingBox;
  17605. var minBox = boundingBox.minimumWorld;
  17606. var maxBox = boundingBox.maximumWorld;
  17607. BABYLON.Tools.CheckExtends(minBox, min, max);
  17608. BABYLON.Tools.CheckExtends(maxBox, min, max);
  17609. }
  17610. }
  17611. return {
  17612. min: min,
  17613. max: max
  17614. };
  17615. };
  17616. /**
  17617. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  17618. * Returns the AbstractMesh.
  17619. */
  17620. AbstractMesh.prototype._updateBoundingInfo = function () {
  17621. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  17622. this._boundingInfo.update(this.worldMatrixFromCache);
  17623. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  17624. return this;
  17625. };
  17626. /**
  17627. * Update a mesh's children BoundingInfo objects only.
  17628. * Returns the AbstractMesh.
  17629. */
  17630. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  17631. if (!this.subMeshes) {
  17632. return this;
  17633. }
  17634. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  17635. var subMesh = this.subMeshes[subIndex];
  17636. if (!subMesh.IsGlobal) {
  17637. subMesh.updateBoundingInfo(matrix);
  17638. }
  17639. }
  17640. return this;
  17641. };
  17642. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  17643. // Bounding info
  17644. this._updateBoundingInfo();
  17645. };
  17646. /**
  17647. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  17648. * A mesh is in the frustum if its bounding box intersects the frustum.
  17649. * Boolean returned.
  17650. */
  17651. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  17652. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  17653. };
  17654. /**
  17655. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  17656. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  17657. * Boolean returned.
  17658. */
  17659. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  17660. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  17661. ;
  17662. };
  17663. /**
  17664. * True if the mesh intersects another mesh or a SolidParticle object.
  17665. * 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)
  17666. * includeDescendants can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  17667. * Returns a boolean.
  17668. */
  17669. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  17670. if (precise === void 0) { precise = false; }
  17671. if (!this._boundingInfo || !mesh._boundingInfo) {
  17672. return false;
  17673. }
  17674. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  17675. return true;
  17676. }
  17677. if (includeDescendants) {
  17678. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  17679. var child = _a[_i];
  17680. if (child.intersectsMesh(mesh, precise, true)) {
  17681. return true;
  17682. }
  17683. }
  17684. }
  17685. return false;
  17686. };
  17687. /**
  17688. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  17689. * Returns a boolean.
  17690. */
  17691. AbstractMesh.prototype.intersectsPoint = function (point) {
  17692. if (!this._boundingInfo) {
  17693. return false;
  17694. }
  17695. return this._boundingInfo.intersectsPoint(point);
  17696. };
  17697. AbstractMesh.prototype.getPhysicsImpostor = function () {
  17698. return this.physicsImpostor;
  17699. };
  17700. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  17701. if (camera === void 0) { camera = null; }
  17702. if (!camera) {
  17703. camera = this.getScene().activeCamera;
  17704. }
  17705. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  17706. };
  17707. /**
  17708. * Returns the distance from the mesh to the active camera.
  17709. * Returns a float.
  17710. */
  17711. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  17712. if (camera === void 0) { camera = null; }
  17713. if (!camera) {
  17714. camera = this.getScene().activeCamera;
  17715. }
  17716. return this.absolutePosition.subtract(camera.position).length();
  17717. };
  17718. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  17719. if (!this.physicsImpostor) {
  17720. return this;
  17721. }
  17722. this.physicsImpostor.applyImpulse(force, contactPoint);
  17723. return this;
  17724. };
  17725. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  17726. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  17727. return this;
  17728. }
  17729. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  17730. mainPivot: pivot1,
  17731. connectedPivot: pivot2,
  17732. nativeParams: options
  17733. });
  17734. return this;
  17735. };
  17736. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  17737. // Collisions
  17738. /**
  17739. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  17740. * Default `false`.
  17741. */
  17742. get: function () {
  17743. return this._checkCollisions;
  17744. },
  17745. set: function (collisionEnabled) {
  17746. this._checkCollisions = collisionEnabled;
  17747. if (this.getScene().workerCollisions) {
  17748. this.getScene().collisionCoordinator.onMeshUpdated(this);
  17749. }
  17750. },
  17751. enumerable: true,
  17752. configurable: true
  17753. });
  17754. Object.defineProperty(AbstractMesh.prototype, "collider", {
  17755. /**
  17756. * Gets Collider object used to compute collisions (not physics)
  17757. */
  17758. get: function () {
  17759. return this._collider;
  17760. },
  17761. enumerable: true,
  17762. configurable: true
  17763. });
  17764. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  17765. var globalPosition = this.getAbsolutePosition();
  17766. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  17767. if (!this._collider) {
  17768. this._collider = new BABYLON.Collider();
  17769. }
  17770. this._collider._radius = this.ellipsoid;
  17771. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  17772. return this;
  17773. };
  17774. // Submeshes octree
  17775. /**
  17776. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  17777. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  17778. * Returns an Octree of submeshes.
  17779. */
  17780. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  17781. if (maxCapacity === void 0) { maxCapacity = 64; }
  17782. if (maxDepth === void 0) { maxDepth = 2; }
  17783. if (!this._submeshesOctree) {
  17784. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  17785. }
  17786. this.computeWorldMatrix(true);
  17787. var boundingInfo = this.getBoundingInfo();
  17788. // Update octree
  17789. var bbox = boundingInfo.boundingBox;
  17790. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  17791. return this._submeshesOctree;
  17792. };
  17793. // Collisions
  17794. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  17795. this._generatePointsArray();
  17796. if (!this._positions) {
  17797. return this;
  17798. }
  17799. // Transformation
  17800. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  17801. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  17802. subMesh._lastColliderWorldVertices = [];
  17803. subMesh._trianglePlanes = [];
  17804. var start = subMesh.verticesStart;
  17805. var end = (subMesh.verticesStart + subMesh.verticesCount);
  17806. for (var i = start; i < end; i++) {
  17807. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  17808. }
  17809. }
  17810. // Collide
  17811. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  17812. if (collider.collisionFound) {
  17813. collider.collidedMesh = this;
  17814. }
  17815. return this;
  17816. };
  17817. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  17818. var subMeshes;
  17819. var len;
  17820. // Octrees
  17821. if (this._submeshesOctree && this.useOctreeForCollisions) {
  17822. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  17823. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  17824. len = intersections.length;
  17825. subMeshes = intersections.data;
  17826. }
  17827. else {
  17828. subMeshes = this.subMeshes;
  17829. len = subMeshes.length;
  17830. }
  17831. for (var index = 0; index < len; index++) {
  17832. var subMesh = subMeshes[index];
  17833. // Bounding test
  17834. if (len > 1 && !subMesh._checkCollision(collider))
  17835. continue;
  17836. this._collideForSubMesh(subMesh, transformMatrix, collider);
  17837. }
  17838. return this;
  17839. };
  17840. AbstractMesh.prototype._checkCollision = function (collider) {
  17841. // Bounding box test
  17842. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  17843. return this;
  17844. // Transformation matrix
  17845. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  17846. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  17847. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  17848. return this;
  17849. };
  17850. // Picking
  17851. AbstractMesh.prototype._generatePointsArray = function () {
  17852. return false;
  17853. };
  17854. /**
  17855. * Checks if the passed Ray intersects with the mesh.
  17856. * Returns an object PickingInfo.
  17857. */
  17858. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  17859. var pickingInfo = new BABYLON.PickingInfo();
  17860. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  17861. return pickingInfo;
  17862. }
  17863. if (!this._generatePointsArray()) {
  17864. return pickingInfo;
  17865. }
  17866. var intersectInfo = null;
  17867. // Octrees
  17868. var subMeshes;
  17869. var len;
  17870. if (this._submeshesOctree && this.useOctreeForPicking) {
  17871. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  17872. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  17873. len = intersections.length;
  17874. subMeshes = intersections.data;
  17875. }
  17876. else {
  17877. subMeshes = this.subMeshes;
  17878. len = subMeshes.length;
  17879. }
  17880. for (var index = 0; index < len; index++) {
  17881. var subMesh = subMeshes[index];
  17882. // Bounding test
  17883. if (len > 1 && !subMesh.canIntersects(ray))
  17884. continue;
  17885. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  17886. if (currentIntersectInfo) {
  17887. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  17888. intersectInfo = currentIntersectInfo;
  17889. intersectInfo.subMeshId = index;
  17890. if (fastCheck) {
  17891. break;
  17892. }
  17893. }
  17894. }
  17895. }
  17896. if (intersectInfo) {
  17897. // Get picked point
  17898. var world = this.getWorldMatrix();
  17899. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  17900. var direction = ray.direction.clone();
  17901. direction = direction.scale(intersectInfo.distance);
  17902. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  17903. var pickedPoint = worldOrigin.add(worldDirection);
  17904. // Return result
  17905. pickingInfo.hit = true;
  17906. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  17907. pickingInfo.pickedPoint = pickedPoint;
  17908. pickingInfo.pickedMesh = this;
  17909. pickingInfo.bu = intersectInfo.bu || 0;
  17910. pickingInfo.bv = intersectInfo.bv || 0;
  17911. pickingInfo.faceId = intersectInfo.faceId;
  17912. pickingInfo.subMeshId = intersectInfo.subMeshId;
  17913. return pickingInfo;
  17914. }
  17915. return pickingInfo;
  17916. };
  17917. /**
  17918. * Clones the mesh, used by the class Mesh.
  17919. * Just returns `null` for an AbstractMesh.
  17920. */
  17921. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  17922. return null;
  17923. };
  17924. /**
  17925. * Disposes all the mesh submeshes.
  17926. * Returns the AbstractMesh.
  17927. */
  17928. AbstractMesh.prototype.releaseSubMeshes = function () {
  17929. if (this.subMeshes) {
  17930. while (this.subMeshes.length) {
  17931. this.subMeshes[0].dispose();
  17932. }
  17933. }
  17934. else {
  17935. this.subMeshes = new Array();
  17936. }
  17937. return this;
  17938. };
  17939. /**
  17940. * Disposes the AbstractMesh.
  17941. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  17942. * Returns nothing.
  17943. */
  17944. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  17945. var _this = this;
  17946. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  17947. var index;
  17948. // Action manager
  17949. if (this.actionManager !== undefined && this.actionManager !== null) {
  17950. this.actionManager.dispose();
  17951. this.actionManager = null;
  17952. }
  17953. // Skeleton
  17954. this.skeleton = null;
  17955. // Physics
  17956. if (this.physicsImpostor) {
  17957. this.physicsImpostor.dispose();
  17958. }
  17959. // Intersections in progress
  17960. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  17961. var other = this._intersectionsInProgress[index];
  17962. var pos = other._intersectionsInProgress.indexOf(this);
  17963. other._intersectionsInProgress.splice(pos, 1);
  17964. }
  17965. this._intersectionsInProgress = [];
  17966. // Lights
  17967. var lights = this.getScene().lights;
  17968. lights.forEach(function (light) {
  17969. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  17970. if (meshIndex !== -1) {
  17971. light.includedOnlyMeshes.splice(meshIndex, 1);
  17972. }
  17973. meshIndex = light.excludedMeshes.indexOf(_this);
  17974. if (meshIndex !== -1) {
  17975. light.excludedMeshes.splice(meshIndex, 1);
  17976. }
  17977. // Shadow generators
  17978. var generator = light.getShadowGenerator();
  17979. if (generator) {
  17980. var shadowMap = generator.getShadowMap();
  17981. if (shadowMap && shadowMap.renderList) {
  17982. meshIndex = shadowMap.renderList.indexOf(_this);
  17983. if (meshIndex !== -1) {
  17984. shadowMap.renderList.splice(meshIndex, 1);
  17985. }
  17986. }
  17987. }
  17988. });
  17989. // Edges
  17990. if (this._edgesRenderer) {
  17991. this._edgesRenderer.dispose();
  17992. this._edgesRenderer = null;
  17993. }
  17994. // SubMeshes
  17995. if (this.getClassName() !== "InstancedMesh") {
  17996. this.releaseSubMeshes();
  17997. }
  17998. // Octree
  17999. var sceneOctree = this.getScene().selectionOctree;
  18000. if (sceneOctree !== undefined && sceneOctree !== null) {
  18001. var index = sceneOctree.dynamicContent.indexOf(this);
  18002. if (index !== -1) {
  18003. sceneOctree.dynamicContent.splice(index, 1);
  18004. }
  18005. }
  18006. // Query
  18007. var engine = this.getScene().getEngine();
  18008. if (this._occlusionQuery) {
  18009. this._isOcclusionQueryInProgress = false;
  18010. engine.deleteQuery(this._occlusionQuery);
  18011. this._occlusionQuery = null;
  18012. }
  18013. // Engine
  18014. engine.wipeCaches();
  18015. // Remove from scene
  18016. this.getScene().removeMesh(this);
  18017. if (disposeMaterialAndTextures) {
  18018. if (this.material) {
  18019. this.material.dispose(false, true);
  18020. }
  18021. }
  18022. if (!doNotRecurse) {
  18023. // Particles
  18024. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  18025. if (this.getScene().particleSystems[index].emitter === this) {
  18026. this.getScene().particleSystems[index].dispose();
  18027. index--;
  18028. }
  18029. }
  18030. }
  18031. // facet data
  18032. if (this._facetDataEnabled) {
  18033. this.disableFacetData();
  18034. }
  18035. this.onAfterWorldMatrixUpdateObservable.clear();
  18036. this.onCollideObservable.clear();
  18037. this.onCollisionPositionChangeObservable.clear();
  18038. _super.prototype.dispose.call(this, doNotRecurse);
  18039. };
  18040. /**
  18041. * Adds the passed mesh as a child to the current mesh.
  18042. * Returns the AbstractMesh.
  18043. */
  18044. AbstractMesh.prototype.addChild = function (mesh) {
  18045. mesh.setParent(this);
  18046. return this;
  18047. };
  18048. /**
  18049. * Removes the passed mesh from the current mesh children list.
  18050. * Returns the AbstractMesh.
  18051. */
  18052. AbstractMesh.prototype.removeChild = function (mesh) {
  18053. mesh.setParent(null);
  18054. return this;
  18055. };
  18056. // Facet data
  18057. /**
  18058. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  18059. * Returns the AbstractMesh.
  18060. */
  18061. AbstractMesh.prototype._initFacetData = function () {
  18062. if (!this._facetNormals) {
  18063. this._facetNormals = new Array();
  18064. }
  18065. if (!this._facetPositions) {
  18066. this._facetPositions = new Array();
  18067. }
  18068. if (!this._facetPartitioning) {
  18069. this._facetPartitioning = new Array();
  18070. }
  18071. this._facetNb = (this.getIndices().length / 3) | 0;
  18072. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  18073. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  18074. for (var f = 0; f < this._facetNb; f++) {
  18075. this._facetNormals[f] = BABYLON.Vector3.Zero();
  18076. this._facetPositions[f] = BABYLON.Vector3.Zero();
  18077. }
  18078. this._facetDataEnabled = true;
  18079. return this;
  18080. };
  18081. /**
  18082. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  18083. * This method can be called within the render loop.
  18084. * 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.
  18085. * Returns the AbstractMesh.
  18086. */
  18087. AbstractMesh.prototype.updateFacetData = function () {
  18088. if (!this._facetDataEnabled) {
  18089. this._initFacetData();
  18090. }
  18091. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18092. var indices = this.getIndices();
  18093. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18094. var bInfo = this.getBoundingInfo();
  18095. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  18096. // init arrays, matrix and sort function on first call
  18097. this._facetDepthSortEnabled = true;
  18098. if (indices instanceof Uint16Array) {
  18099. this._depthSortedIndices = new Uint16Array(indices);
  18100. }
  18101. else if (indices instanceof Uint32Array) {
  18102. this._depthSortedIndices = new Uint32Array(indices);
  18103. }
  18104. else {
  18105. var needs32bits = false;
  18106. for (var i = 0; i < indices.length; i++) {
  18107. if (indices[i] > 65535) {
  18108. needs32bits = true;
  18109. break;
  18110. }
  18111. }
  18112. if (needs32bits) {
  18113. this._depthSortedIndices = new Uint32Array(indices);
  18114. }
  18115. else {
  18116. this._depthSortedIndices = new Uint16Array(indices);
  18117. }
  18118. }
  18119. this._facetDepthSortFunction = function (f1, f2) {
  18120. return (f2.sqDistance - f1.sqDistance);
  18121. };
  18122. if (!this._facetDepthSortFrom) {
  18123. var camera = this.getScene().activeCamera;
  18124. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  18125. }
  18126. this._depthSortedFacets = [];
  18127. for (var f = 0; f < this._facetNb; f++) {
  18128. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  18129. this._depthSortedFacets.push(depthSortedFacet);
  18130. }
  18131. this._invertedMatrix = BABYLON.Matrix.Identity();
  18132. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  18133. }
  18134. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  18135. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  18136. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  18137. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  18138. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  18139. this._subDiv.max = this._partitioningSubdivisions;
  18140. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  18141. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  18142. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  18143. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  18144. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  18145. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  18146. // set the parameters for ComputeNormals()
  18147. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  18148. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  18149. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  18150. this._facetParameters.bInfo = bInfo;
  18151. this._facetParameters.bbSize = this._bbSize;
  18152. this._facetParameters.subDiv = this._subDiv;
  18153. this._facetParameters.ratio = this.partitioningBBoxRatio;
  18154. this._facetParameters.depthSort = this._facetDepthSort;
  18155. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  18156. this.computeWorldMatrix(true);
  18157. this._worldMatrix.invertToRef(this._invertedMatrix);
  18158. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  18159. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  18160. }
  18161. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  18162. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  18163. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  18164. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  18165. var l = (this._depthSortedIndices.length / 3) | 0;
  18166. for (var f = 0; f < l; f++) {
  18167. var sind = this._depthSortedFacets[f].ind;
  18168. this._depthSortedIndices[f * 3] = indices[sind];
  18169. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  18170. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  18171. }
  18172. this.updateIndices(this._depthSortedIndices);
  18173. }
  18174. return this;
  18175. };
  18176. /**
  18177. * Returns the facetLocalNormals array.
  18178. * The normals are expressed in the mesh local space.
  18179. */
  18180. AbstractMesh.prototype.getFacetLocalNormals = function () {
  18181. if (!this._facetNormals) {
  18182. this.updateFacetData();
  18183. }
  18184. return this._facetNormals;
  18185. };
  18186. /**
  18187. * Returns the facetLocalPositions array.
  18188. * The facet positions are expressed in the mesh local space.
  18189. */
  18190. AbstractMesh.prototype.getFacetLocalPositions = function () {
  18191. if (!this._facetPositions) {
  18192. this.updateFacetData();
  18193. }
  18194. return this._facetPositions;
  18195. };
  18196. /**
  18197. * Returns the facetLocalPartioning array.
  18198. */
  18199. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  18200. if (!this._facetPartitioning) {
  18201. this.updateFacetData();
  18202. }
  18203. return this._facetPartitioning;
  18204. };
  18205. /**
  18206. * Returns the i-th facet position in the world system.
  18207. * This method allocates a new Vector3 per call.
  18208. */
  18209. AbstractMesh.prototype.getFacetPosition = function (i) {
  18210. var pos = BABYLON.Vector3.Zero();
  18211. this.getFacetPositionToRef(i, pos);
  18212. return pos;
  18213. };
  18214. /**
  18215. * Sets the reference Vector3 with the i-th facet position in the world system.
  18216. * Returns the AbstractMesh.
  18217. */
  18218. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  18219. var localPos = (this.getFacetLocalPositions())[i];
  18220. var world = this.getWorldMatrix();
  18221. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  18222. return this;
  18223. };
  18224. /**
  18225. * Returns the i-th facet normal in the world system.
  18226. * This method allocates a new Vector3 per call.
  18227. */
  18228. AbstractMesh.prototype.getFacetNormal = function (i) {
  18229. var norm = BABYLON.Vector3.Zero();
  18230. this.getFacetNormalToRef(i, norm);
  18231. return norm;
  18232. };
  18233. /**
  18234. * Sets the reference Vector3 with the i-th facet normal in the world system.
  18235. * Returns the AbstractMesh.
  18236. */
  18237. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  18238. var localNorm = (this.getFacetLocalNormals())[i];
  18239. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  18240. return this;
  18241. };
  18242. /**
  18243. * 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).
  18244. */
  18245. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  18246. var bInfo = this.getBoundingInfo();
  18247. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  18248. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  18249. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  18250. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  18251. return null;
  18252. }
  18253. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  18254. };
  18255. /**
  18256. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  18257. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  18258. * 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.
  18259. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  18260. * 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.
  18261. */
  18262. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  18263. if (checkFace === void 0) { checkFace = false; }
  18264. if (facing === void 0) { facing = true; }
  18265. var world = this.getWorldMatrix();
  18266. var invMat = BABYLON.Tmp.Matrix[5];
  18267. world.invertToRef(invMat);
  18268. var invVect = BABYLON.Tmp.Vector3[8];
  18269. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  18270. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  18271. if (projected) {
  18272. // tranform the local computed projected vector to world coordinates
  18273. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  18274. }
  18275. return closest;
  18276. };
  18277. /**
  18278. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  18279. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  18280. * 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.
  18281. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  18282. * 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.
  18283. */
  18284. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  18285. if (checkFace === void 0) { checkFace = false; }
  18286. if (facing === void 0) { facing = true; }
  18287. var closest = null;
  18288. var tmpx = 0.0;
  18289. var tmpy = 0.0;
  18290. var tmpz = 0.0;
  18291. var d = 0.0; // tmp dot facet normal * facet position
  18292. var t0 = 0.0;
  18293. var projx = 0.0;
  18294. var projy = 0.0;
  18295. var projz = 0.0;
  18296. // Get all the facets in the same partitioning block than (x, y, z)
  18297. var facetPositions = this.getFacetLocalPositions();
  18298. var facetNormals = this.getFacetLocalNormals();
  18299. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  18300. if (!facetsInBlock) {
  18301. return null;
  18302. }
  18303. // Get the closest facet to (x, y, z)
  18304. var shortest = Number.MAX_VALUE; // init distance vars
  18305. var tmpDistance = shortest;
  18306. var fib; // current facet in the block
  18307. var norm; // current facet normal
  18308. var p0; // current facet barycenter position
  18309. // loop on all the facets in the current partitioning block
  18310. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  18311. fib = facetsInBlock[idx];
  18312. norm = facetNormals[fib];
  18313. p0 = facetPositions[fib];
  18314. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  18315. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  18316. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  18317. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  18318. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  18319. projx = x + norm.x * t0;
  18320. projy = y + norm.y * t0;
  18321. projz = z + norm.z * t0;
  18322. tmpx = projx - x;
  18323. tmpy = projy - y;
  18324. tmpz = projz - z;
  18325. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  18326. if (tmpDistance < shortest) {
  18327. shortest = tmpDistance;
  18328. closest = fib;
  18329. if (projected) {
  18330. projected.x = projx;
  18331. projected.y = projy;
  18332. projected.z = projz;
  18333. }
  18334. }
  18335. }
  18336. }
  18337. return closest;
  18338. };
  18339. /**
  18340. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  18341. */
  18342. AbstractMesh.prototype.getFacetDataParameters = function () {
  18343. return this._facetParameters;
  18344. };
  18345. /**
  18346. * Disables the feature FacetData and frees the related memory.
  18347. * Returns the AbstractMesh.
  18348. */
  18349. AbstractMesh.prototype.disableFacetData = function () {
  18350. if (this._facetDataEnabled) {
  18351. this._facetDataEnabled = false;
  18352. this._facetPositions = new Array();
  18353. this._facetNormals = new Array();
  18354. this._facetPartitioning = new Array();
  18355. this._facetParameters = null;
  18356. this._depthSortedIndices = new Uint32Array(0);
  18357. }
  18358. return this;
  18359. };
  18360. /**
  18361. * Updates the AbstractMesh indices array. Actually, used by the Mesh object.
  18362. * Returns the mesh.
  18363. */
  18364. AbstractMesh.prototype.updateIndices = function (indices) {
  18365. return this;
  18366. };
  18367. /**
  18368. * The mesh Geometry. Actually used by the Mesh object.
  18369. * Returns a blank geometry object.
  18370. */
  18371. /**
  18372. * Creates new normals data for the mesh.
  18373. * @param updatable.
  18374. */
  18375. AbstractMesh.prototype.createNormals = function (updatable) {
  18376. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18377. var indices = this.getIndices();
  18378. var normals;
  18379. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  18380. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18381. }
  18382. else {
  18383. normals = [];
  18384. }
  18385. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  18386. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  18387. };
  18388. /**
  18389. * Align the mesh with a normal.
  18390. * Returns the mesh.
  18391. */
  18392. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  18393. if (!upDirection) {
  18394. upDirection = BABYLON.Axis.Y;
  18395. }
  18396. var axisX = BABYLON.Tmp.Vector3[0];
  18397. var axisZ = BABYLON.Tmp.Vector3[1];
  18398. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  18399. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  18400. if (this.rotationQuaternion) {
  18401. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  18402. }
  18403. else {
  18404. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  18405. }
  18406. return this;
  18407. };
  18408. AbstractMesh.prototype.checkOcclusionQuery = function () {
  18409. var engine = this.getEngine();
  18410. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  18411. this._isOccluded = false;
  18412. return;
  18413. }
  18414. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  18415. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  18416. if (isOcclusionQueryAvailable) {
  18417. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  18418. this._isOcclusionQueryInProgress = false;
  18419. this._occlusionInternalRetryCounter = 0;
  18420. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  18421. }
  18422. else {
  18423. this._occlusionInternalRetryCounter++;
  18424. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  18425. this._isOcclusionQueryInProgress = false;
  18426. this._occlusionInternalRetryCounter = 0;
  18427. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  18428. // if strict continue the last state of the object.
  18429. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  18430. }
  18431. else {
  18432. return;
  18433. }
  18434. }
  18435. }
  18436. var scene = this.getScene();
  18437. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  18438. if (!this._occlusionQuery) {
  18439. this._occlusionQuery = engine.createQuery();
  18440. }
  18441. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  18442. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  18443. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  18444. this._isOcclusionQueryInProgress = true;
  18445. };
  18446. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  18447. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  18448. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  18449. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  18450. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  18451. return AbstractMesh;
  18452. }(BABYLON.TransformNode));
  18453. BABYLON.AbstractMesh = AbstractMesh;
  18454. })(BABYLON || (BABYLON = {}));
  18455. //# sourceMappingURL=babylon.abstractMesh.js.map
  18456. var BABYLON;
  18457. (function (BABYLON) {
  18458. /**
  18459. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  18460. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  18461. * 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.
  18462. */
  18463. var Light = /** @class */ (function (_super) {
  18464. __extends(Light, _super);
  18465. /**
  18466. * Creates a Light object in the scene.
  18467. * Documentation : http://doc.babylonjs.com/tutorials/lights
  18468. * @param name The firendly name of the light
  18469. * @param scene The scene the light belongs too
  18470. */
  18471. function Light(name, scene) {
  18472. var _this = _super.call(this, name, scene) || this;
  18473. /**
  18474. * Diffuse gives the basic color to an object.
  18475. */
  18476. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  18477. /**
  18478. * Specular produces a highlight color on an object.
  18479. * Note: This is note affecting PBR materials.
  18480. */
  18481. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  18482. /**
  18483. * Strength of the light.
  18484. * Note: By default it is define in the framework own unit.
  18485. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  18486. */
  18487. _this.intensity = 1.0;
  18488. /**
  18489. * Defines how far from the source the light is impacting in scene units.
  18490. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  18491. */
  18492. _this.range = Number.MAX_VALUE;
  18493. /**
  18494. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  18495. * of light.
  18496. */
  18497. _this._photometricScale = 1.0;
  18498. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  18499. _this._radius = 0.00001;
  18500. /**
  18501. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  18502. * exceeding the number allowed of the materials.
  18503. */
  18504. _this.renderPriority = 0;
  18505. /**
  18506. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  18507. * the current shadow generator.
  18508. */
  18509. _this.shadowEnabled = true;
  18510. _this._excludeWithLayerMask = 0;
  18511. _this._includeOnlyWithLayerMask = 0;
  18512. _this._lightmapMode = 0;
  18513. /**
  18514. * @ignore Internal use only.
  18515. */
  18516. _this._excludedMeshesIds = new Array();
  18517. /**
  18518. * @ignore Internal use only.
  18519. */
  18520. _this._includedOnlyMeshesIds = new Array();
  18521. _this.getScene().addLight(_this);
  18522. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  18523. _this._buildUniformLayout();
  18524. _this.includedOnlyMeshes = new Array();
  18525. _this.excludedMeshes = new Array();
  18526. _this._resyncMeshes();
  18527. return _this;
  18528. }
  18529. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  18530. /**
  18531. * If every light affecting the material is in this lightmapMode,
  18532. * material.lightmapTexture adds or multiplies
  18533. * (depends on material.useLightmapAsShadowmap)
  18534. * after every other light calculations.
  18535. */
  18536. get: function () {
  18537. return Light._LIGHTMAP_DEFAULT;
  18538. },
  18539. enumerable: true,
  18540. configurable: true
  18541. });
  18542. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  18543. /**
  18544. * material.lightmapTexture as only diffuse lighting from this light
  18545. * adds only specular lighting from this light
  18546. * adds dynamic shadows
  18547. */
  18548. get: function () {
  18549. return Light._LIGHTMAP_SPECULAR;
  18550. },
  18551. enumerable: true,
  18552. configurable: true
  18553. });
  18554. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  18555. /**
  18556. * material.lightmapTexture as only lighting
  18557. * no light calculation from this light
  18558. * only adds dynamic shadows from this light
  18559. */
  18560. get: function () {
  18561. return Light._LIGHTMAP_SHADOWSONLY;
  18562. },
  18563. enumerable: true,
  18564. configurable: true
  18565. });
  18566. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  18567. /**
  18568. * Each light type uses the default quantity according to its type:
  18569. * point/spot lights use luminous intensity
  18570. * directional lights use illuminance
  18571. */
  18572. get: function () {
  18573. return Light._INTENSITYMODE_AUTOMATIC;
  18574. },
  18575. enumerable: true,
  18576. configurable: true
  18577. });
  18578. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  18579. /**
  18580. * lumen (lm)
  18581. */
  18582. get: function () {
  18583. return Light._INTENSITYMODE_LUMINOUSPOWER;
  18584. },
  18585. enumerable: true,
  18586. configurable: true
  18587. });
  18588. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  18589. /**
  18590. * candela (lm/sr)
  18591. */
  18592. get: function () {
  18593. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  18594. },
  18595. enumerable: true,
  18596. configurable: true
  18597. });
  18598. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  18599. /**
  18600. * lux (lm/m^2)
  18601. */
  18602. get: function () {
  18603. return Light._INTENSITYMODE_ILLUMINANCE;
  18604. },
  18605. enumerable: true,
  18606. configurable: true
  18607. });
  18608. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  18609. /**
  18610. * nit (cd/m^2)
  18611. */
  18612. get: function () {
  18613. return Light._INTENSITYMODE_LUMINANCE;
  18614. },
  18615. enumerable: true,
  18616. configurable: true
  18617. });
  18618. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  18619. /**
  18620. * Light type const id of the point light.
  18621. */
  18622. get: function () {
  18623. return Light._LIGHTTYPEID_POINTLIGHT;
  18624. },
  18625. enumerable: true,
  18626. configurable: true
  18627. });
  18628. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  18629. /**
  18630. * Light type const id of the directional light.
  18631. */
  18632. get: function () {
  18633. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  18634. },
  18635. enumerable: true,
  18636. configurable: true
  18637. });
  18638. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  18639. /**
  18640. * Light type const id of the spot light.
  18641. */
  18642. get: function () {
  18643. return Light._LIGHTTYPEID_SPOTLIGHT;
  18644. },
  18645. enumerable: true,
  18646. configurable: true
  18647. });
  18648. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  18649. /**
  18650. * Light type const id of the hemispheric light.
  18651. */
  18652. get: function () {
  18653. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  18654. },
  18655. enumerable: true,
  18656. configurable: true
  18657. });
  18658. Object.defineProperty(Light.prototype, "intensityMode", {
  18659. /**
  18660. * Gets the photometric scale used to interpret the intensity.
  18661. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  18662. */
  18663. get: function () {
  18664. return this._intensityMode;
  18665. },
  18666. /**
  18667. * Sets the photometric scale used to interpret the intensity.
  18668. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  18669. */
  18670. set: function (value) {
  18671. this._intensityMode = value;
  18672. this._computePhotometricScale();
  18673. },
  18674. enumerable: true,
  18675. configurable: true
  18676. });
  18677. ;
  18678. ;
  18679. Object.defineProperty(Light.prototype, "radius", {
  18680. /**
  18681. * Gets the light radius used by PBR Materials to simulate soft area lights.
  18682. */
  18683. get: function () {
  18684. return this._radius;
  18685. },
  18686. /**
  18687. * sets the light radius used by PBR Materials to simulate soft area lights.
  18688. */
  18689. set: function (value) {
  18690. this._radius = value;
  18691. this._computePhotometricScale();
  18692. },
  18693. enumerable: true,
  18694. configurable: true
  18695. });
  18696. ;
  18697. ;
  18698. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  18699. /**
  18700. * Gets the only meshes impacted by this light.
  18701. */
  18702. get: function () {
  18703. return this._includedOnlyMeshes;
  18704. },
  18705. /**
  18706. * Sets the only meshes impacted by this light.
  18707. */
  18708. set: function (value) {
  18709. this._includedOnlyMeshes = value;
  18710. this._hookArrayForIncludedOnly(value);
  18711. },
  18712. enumerable: true,
  18713. configurable: true
  18714. });
  18715. Object.defineProperty(Light.prototype, "excludedMeshes", {
  18716. /**
  18717. * Gets the meshes not impacted by this light.
  18718. */
  18719. get: function () {
  18720. return this._excludedMeshes;
  18721. },
  18722. /**
  18723. * Sets the meshes not impacted by this light.
  18724. */
  18725. set: function (value) {
  18726. this._excludedMeshes = value;
  18727. this._hookArrayForExcluded(value);
  18728. },
  18729. enumerable: true,
  18730. configurable: true
  18731. });
  18732. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  18733. /**
  18734. * Gets the layer id use to find what meshes are not impacted by the light.
  18735. * Inactive if 0
  18736. */
  18737. get: function () {
  18738. return this._excludeWithLayerMask;
  18739. },
  18740. /**
  18741. * Sets the layer id use to find what meshes are not impacted by the light.
  18742. * Inactive if 0
  18743. */
  18744. set: function (value) {
  18745. this._excludeWithLayerMask = value;
  18746. this._resyncMeshes();
  18747. },
  18748. enumerable: true,
  18749. configurable: true
  18750. });
  18751. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  18752. /**
  18753. * Gets the layer id use to find what meshes are impacted by the light.
  18754. * Inactive if 0
  18755. */
  18756. get: function () {
  18757. return this._includeOnlyWithLayerMask;
  18758. },
  18759. /**
  18760. * Sets the layer id use to find what meshes are impacted by the light.
  18761. * Inactive if 0
  18762. */
  18763. set: function (value) {
  18764. this._includeOnlyWithLayerMask = value;
  18765. this._resyncMeshes();
  18766. },
  18767. enumerable: true,
  18768. configurable: true
  18769. });
  18770. Object.defineProperty(Light.prototype, "lightmapMode", {
  18771. /**
  18772. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  18773. */
  18774. get: function () {
  18775. return this._lightmapMode;
  18776. },
  18777. /**
  18778. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  18779. */
  18780. set: function (value) {
  18781. if (this._lightmapMode === value) {
  18782. return;
  18783. }
  18784. this._lightmapMode = value;
  18785. this._markMeshesAsLightDirty();
  18786. },
  18787. enumerable: true,
  18788. configurable: true
  18789. });
  18790. /**
  18791. * Returns the string "Light".
  18792. * @returns the class name
  18793. */
  18794. Light.prototype.getClassName = function () {
  18795. return "Light";
  18796. };
  18797. /**
  18798. * Converts the light information to a readable string for debug purpose.
  18799. * @param fullDetails Supports for multiple levels of logging within scene loading
  18800. * @returns the human readable light info
  18801. */
  18802. Light.prototype.toString = function (fullDetails) {
  18803. var ret = "Name: " + this.name;
  18804. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  18805. if (this.animations) {
  18806. for (var i = 0; i < this.animations.length; i++) {
  18807. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  18808. }
  18809. }
  18810. if (fullDetails) {
  18811. }
  18812. return ret;
  18813. };
  18814. /**
  18815. * Set the enabled state of this node.
  18816. * @param value - the new enabled state
  18817. * @see isEnabled
  18818. */
  18819. Light.prototype.setEnabled = function (value) {
  18820. _super.prototype.setEnabled.call(this, value);
  18821. this._resyncMeshes();
  18822. };
  18823. /**
  18824. * Returns the Light associated shadow generator if any.
  18825. * @return the associated shadow generator.
  18826. */
  18827. Light.prototype.getShadowGenerator = function () {
  18828. return this._shadowGenerator;
  18829. };
  18830. /**
  18831. * Returns a Vector3, the absolute light position in the World.
  18832. * @returns the world space position of the light
  18833. */
  18834. Light.prototype.getAbsolutePosition = function () {
  18835. return BABYLON.Vector3.Zero();
  18836. };
  18837. /**
  18838. * Specifies if the light will affect the passed mesh.
  18839. * @param mesh The mesh to test against the light
  18840. * @return true the mesh is affected otherwise, false.
  18841. */
  18842. Light.prototype.canAffectMesh = function (mesh) {
  18843. if (!mesh) {
  18844. return true;
  18845. }
  18846. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  18847. return false;
  18848. }
  18849. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  18850. return false;
  18851. }
  18852. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  18853. return false;
  18854. }
  18855. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  18856. return false;
  18857. }
  18858. return true;
  18859. };
  18860. /**
  18861. * Computes and Returns the light World matrix.
  18862. * @returns the world matrix
  18863. */
  18864. Light.prototype.getWorldMatrix = function () {
  18865. this._currentRenderId = this.getScene().getRenderId();
  18866. var worldMatrix = this._getWorldMatrix();
  18867. if (this.parent && this.parent.getWorldMatrix) {
  18868. if (!this._parentedWorldMatrix) {
  18869. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  18870. }
  18871. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  18872. this._markSyncedWithParent();
  18873. return this._parentedWorldMatrix;
  18874. }
  18875. return worldMatrix;
  18876. };
  18877. /**
  18878. * Sort function to order lights for rendering.
  18879. * @param a First Light object to compare to second.
  18880. * @param b Second Light object to compare first.
  18881. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  18882. */
  18883. Light.CompareLightsPriority = function (a, b) {
  18884. //shadow-casting lights have priority over non-shadow-casting lights
  18885. //the renderPrioirty is a secondary sort criterion
  18886. if (a.shadowEnabled !== b.shadowEnabled) {
  18887. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  18888. }
  18889. return b.renderPriority - a.renderPriority;
  18890. };
  18891. /**
  18892. * Disposes the light.
  18893. */
  18894. Light.prototype.dispose = function () {
  18895. if (this._shadowGenerator) {
  18896. this._shadowGenerator.dispose();
  18897. this._shadowGenerator = null;
  18898. }
  18899. // Animations
  18900. this.getScene().stopAnimation(this);
  18901. // Remove from meshes
  18902. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  18903. var mesh = _a[_i];
  18904. mesh._removeLightSource(this);
  18905. }
  18906. this._uniformBuffer.dispose();
  18907. // Remove from scene
  18908. this.getScene().removeLight(this);
  18909. _super.prototype.dispose.call(this);
  18910. };
  18911. /**
  18912. * Returns the light type ID (integer).
  18913. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  18914. */
  18915. Light.prototype.getTypeID = function () {
  18916. return 0;
  18917. };
  18918. /**
  18919. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  18920. * @returns the scaled intensity in intensity mode unit
  18921. */
  18922. Light.prototype.getScaledIntensity = function () {
  18923. return this._photometricScale * this.intensity;
  18924. };
  18925. /**
  18926. * Returns a new Light object, named "name", from the current one.
  18927. * @param name The name of the cloned light
  18928. * @returns the new created light
  18929. */
  18930. Light.prototype.clone = function (name) {
  18931. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  18932. if (!constructor) {
  18933. return null;
  18934. }
  18935. return BABYLON.SerializationHelper.Clone(constructor, this);
  18936. };
  18937. /**
  18938. * Serializes the current light into a Serialization object.
  18939. * @returns the serialized object.
  18940. */
  18941. Light.prototype.serialize = function () {
  18942. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  18943. // Type
  18944. serializationObject.type = this.getTypeID();
  18945. // Parent
  18946. if (this.parent) {
  18947. serializationObject.parentId = this.parent.id;
  18948. }
  18949. // Inclusion / exclusions
  18950. if (this.excludedMeshes.length > 0) {
  18951. serializationObject.excludedMeshesIds = [];
  18952. this.excludedMeshes.forEach(function (mesh) {
  18953. serializationObject.excludedMeshesIds.push(mesh.id);
  18954. });
  18955. }
  18956. if (this.includedOnlyMeshes.length > 0) {
  18957. serializationObject.includedOnlyMeshesIds = [];
  18958. this.includedOnlyMeshes.forEach(function (mesh) {
  18959. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  18960. });
  18961. }
  18962. // Animations
  18963. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  18964. serializationObject.ranges = this.serializeAnimationRanges();
  18965. return serializationObject;
  18966. };
  18967. /**
  18968. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  18969. * This new light is named "name" and added to the passed scene.
  18970. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  18971. * @param name The friendly name of the light
  18972. * @param scene The scene the new light will belong to
  18973. * @returns the constructor function
  18974. */
  18975. Light.GetConstructorFromName = function (type, name, scene) {
  18976. switch (type) {
  18977. case 0:
  18978. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  18979. case 1:
  18980. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  18981. case 2:
  18982. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  18983. case 3:
  18984. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  18985. }
  18986. return null;
  18987. };
  18988. /**
  18989. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  18990. * @param parsedLight The JSON representation of the light
  18991. * @param scene The scene to create the parsed light in
  18992. * @returns the created light after parsing
  18993. */
  18994. Light.Parse = function (parsedLight, scene) {
  18995. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  18996. if (!constructor) {
  18997. return null;
  18998. }
  18999. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  19000. // Inclusion / exclusions
  19001. if (parsedLight.excludedMeshesIds) {
  19002. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  19003. }
  19004. if (parsedLight.includedOnlyMeshesIds) {
  19005. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  19006. }
  19007. // Parent
  19008. if (parsedLight.parentId) {
  19009. light._waitingParentId = parsedLight.parentId;
  19010. }
  19011. // Animations
  19012. if (parsedLight.animations) {
  19013. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  19014. var parsedAnimation = parsedLight.animations[animationIndex];
  19015. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  19016. }
  19017. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  19018. }
  19019. if (parsedLight.autoAnimate) {
  19020. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  19021. }
  19022. return light;
  19023. };
  19024. Light.prototype._hookArrayForExcluded = function (array) {
  19025. var _this = this;
  19026. var oldPush = array.push;
  19027. array.push = function () {
  19028. var items = [];
  19029. for (var _i = 0; _i < arguments.length; _i++) {
  19030. items[_i] = arguments[_i];
  19031. }
  19032. var result = oldPush.apply(array, items);
  19033. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  19034. var item = items_1[_a];
  19035. item._resyncLighSource(_this);
  19036. }
  19037. return result;
  19038. };
  19039. var oldSplice = array.splice;
  19040. array.splice = function (index, deleteCount) {
  19041. var deleted = oldSplice.apply(array, [index, deleteCount]);
  19042. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  19043. var item = deleted_1[_i];
  19044. item._resyncLighSource(_this);
  19045. }
  19046. return deleted;
  19047. };
  19048. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  19049. var item = array_1[_i];
  19050. item._resyncLighSource(this);
  19051. }
  19052. };
  19053. Light.prototype._hookArrayForIncludedOnly = function (array) {
  19054. var _this = this;
  19055. var oldPush = array.push;
  19056. array.push = function () {
  19057. var items = [];
  19058. for (var _i = 0; _i < arguments.length; _i++) {
  19059. items[_i] = arguments[_i];
  19060. }
  19061. var result = oldPush.apply(array, items);
  19062. _this._resyncMeshes();
  19063. return result;
  19064. };
  19065. var oldSplice = array.splice;
  19066. array.splice = function (index, deleteCount) {
  19067. var deleted = oldSplice.apply(array, [index, deleteCount]);
  19068. _this._resyncMeshes();
  19069. return deleted;
  19070. };
  19071. this._resyncMeshes();
  19072. };
  19073. Light.prototype._resyncMeshes = function () {
  19074. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  19075. var mesh = _a[_i];
  19076. mesh._resyncLighSource(this);
  19077. }
  19078. };
  19079. /**
  19080. * Forces the meshes to update their light related information in their rendering used effects
  19081. * @ignore Internal Use Only
  19082. */
  19083. Light.prototype._markMeshesAsLightDirty = function () {
  19084. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  19085. var mesh = _a[_i];
  19086. if (mesh._lightSources.indexOf(this) !== -1) {
  19087. mesh._markSubMeshesAsLightDirty();
  19088. }
  19089. }
  19090. };
  19091. /**
  19092. * Recomputes the cached photometric scale if needed.
  19093. */
  19094. Light.prototype._computePhotometricScale = function () {
  19095. this._photometricScale = this._getPhotometricScale();
  19096. this.getScene().resetCachedMaterial();
  19097. };
  19098. /**
  19099. * Returns the Photometric Scale according to the light type and intensity mode.
  19100. */
  19101. Light.prototype._getPhotometricScale = function () {
  19102. var photometricScale = 0.0;
  19103. var lightTypeID = this.getTypeID();
  19104. //get photometric mode
  19105. var photometricMode = this.intensityMode;
  19106. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  19107. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  19108. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  19109. }
  19110. else {
  19111. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  19112. }
  19113. }
  19114. //compute photometric scale
  19115. switch (lightTypeID) {
  19116. case Light.LIGHTTYPEID_POINTLIGHT:
  19117. case Light.LIGHTTYPEID_SPOTLIGHT:
  19118. switch (photometricMode) {
  19119. case Light.INTENSITYMODE_LUMINOUSPOWER:
  19120. photometricScale = 1.0 / (4.0 * Math.PI);
  19121. break;
  19122. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  19123. photometricScale = 1.0;
  19124. break;
  19125. case Light.INTENSITYMODE_LUMINANCE:
  19126. photometricScale = this.radius * this.radius;
  19127. break;
  19128. }
  19129. break;
  19130. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  19131. switch (photometricMode) {
  19132. case Light.INTENSITYMODE_ILLUMINANCE:
  19133. photometricScale = 1.0;
  19134. break;
  19135. case Light.INTENSITYMODE_LUMINANCE:
  19136. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  19137. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  19138. var apexAngleRadians = this.radius;
  19139. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  19140. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  19141. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  19142. photometricScale = solidAngle;
  19143. break;
  19144. }
  19145. break;
  19146. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  19147. // No fall off in hemisperic light.
  19148. photometricScale = 1.0;
  19149. break;
  19150. }
  19151. return photometricScale;
  19152. };
  19153. /**
  19154. * Reorder the light in the scene according to their defined priority.
  19155. * @ignore Internal Use Only
  19156. */
  19157. Light.prototype._reorderLightsInScene = function () {
  19158. var scene = this.getScene();
  19159. if (this._renderPriority != 0) {
  19160. scene.requireLightSorting = true;
  19161. }
  19162. this.getScene().sortLightsByPriority();
  19163. };
  19164. //lightmapMode Consts
  19165. Light._LIGHTMAP_DEFAULT = 0;
  19166. Light._LIGHTMAP_SPECULAR = 1;
  19167. Light._LIGHTMAP_SHADOWSONLY = 2;
  19168. // Intensity Mode Consts
  19169. Light._INTENSITYMODE_AUTOMATIC = 0;
  19170. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  19171. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  19172. Light._INTENSITYMODE_ILLUMINANCE = 3;
  19173. Light._INTENSITYMODE_LUMINANCE = 4;
  19174. // Light types ids const.
  19175. Light._LIGHTTYPEID_POINTLIGHT = 0;
  19176. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  19177. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  19178. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  19179. __decorate([
  19180. BABYLON.serializeAsColor3()
  19181. ], Light.prototype, "diffuse", void 0);
  19182. __decorate([
  19183. BABYLON.serializeAsColor3()
  19184. ], Light.prototype, "specular", void 0);
  19185. __decorate([
  19186. BABYLON.serialize()
  19187. ], Light.prototype, "intensity", void 0);
  19188. __decorate([
  19189. BABYLON.serialize()
  19190. ], Light.prototype, "range", void 0);
  19191. __decorate([
  19192. BABYLON.serialize()
  19193. ], Light.prototype, "intensityMode", null);
  19194. __decorate([
  19195. BABYLON.serialize()
  19196. ], Light.prototype, "radius", null);
  19197. __decorate([
  19198. BABYLON.serialize()
  19199. ], Light.prototype, "_renderPriority", void 0);
  19200. __decorate([
  19201. BABYLON.expandToProperty("_reorderLightsInScene")
  19202. ], Light.prototype, "renderPriority", void 0);
  19203. __decorate([
  19204. BABYLON.serialize()
  19205. ], Light.prototype, "shadowEnabled", void 0);
  19206. __decorate([
  19207. BABYLON.serialize("excludeWithLayerMask")
  19208. ], Light.prototype, "_excludeWithLayerMask", void 0);
  19209. __decorate([
  19210. BABYLON.serialize("includeOnlyWithLayerMask")
  19211. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  19212. __decorate([
  19213. BABYLON.serialize("lightmapMode")
  19214. ], Light.prototype, "_lightmapMode", void 0);
  19215. return Light;
  19216. }(BABYLON.Node));
  19217. BABYLON.Light = Light;
  19218. })(BABYLON || (BABYLON = {}));
  19219. //# sourceMappingURL=babylon.light.js.map
  19220. var BABYLON;
  19221. (function (BABYLON) {
  19222. var Camera = /** @class */ (function (_super) {
  19223. __extends(Camera, _super);
  19224. function Camera(name, position, scene) {
  19225. var _this = _super.call(this, name, scene) || this;
  19226. /**
  19227. * The vector the camera should consider as up.
  19228. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  19229. */
  19230. _this.upVector = BABYLON.Vector3.Up();
  19231. _this.orthoLeft = null;
  19232. _this.orthoRight = null;
  19233. _this.orthoBottom = null;
  19234. _this.orthoTop = null;
  19235. /**
  19236. * FOV is set in Radians. (default is 0.8)
  19237. */
  19238. _this.fov = 0.8;
  19239. _this.minZ = 1;
  19240. _this.maxZ = 10000.0;
  19241. _this.inertia = 0.9;
  19242. _this.mode = Camera.PERSPECTIVE_CAMERA;
  19243. _this.isIntermediate = false;
  19244. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  19245. /**
  19246. * Restricts the camera to viewing objects with the same layerMask.
  19247. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  19248. */
  19249. _this.layerMask = 0x0FFFFFFF;
  19250. /**
  19251. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  19252. */
  19253. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  19254. // Camera rig members
  19255. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  19256. _this._rigCameras = new Array();
  19257. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  19258. _this._skipRendering = false;
  19259. _this.customRenderTargets = new Array();
  19260. // Observables
  19261. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  19262. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  19263. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  19264. _this.onRestoreStateObservable = new BABYLON.Observable();
  19265. // Cache
  19266. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  19267. _this._projectionMatrix = new BABYLON.Matrix();
  19268. _this._doNotComputeProjectionMatrix = false;
  19269. _this._postProcesses = new Array();
  19270. _this._transformMatrix = BABYLON.Matrix.Zero();
  19271. _this._activeMeshes = new BABYLON.SmartArray(256);
  19272. _this._globalPosition = BABYLON.Vector3.Zero();
  19273. _this._refreshFrustumPlanes = true;
  19274. _this.getScene().addCamera(_this);
  19275. if (!_this.getScene().activeCamera) {
  19276. _this.getScene().activeCamera = _this;
  19277. }
  19278. _this.position = position;
  19279. return _this;
  19280. }
  19281. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  19282. get: function () {
  19283. return Camera._PERSPECTIVE_CAMERA;
  19284. },
  19285. enumerable: true,
  19286. configurable: true
  19287. });
  19288. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  19289. get: function () {
  19290. return Camera._ORTHOGRAPHIC_CAMERA;
  19291. },
  19292. enumerable: true,
  19293. configurable: true
  19294. });
  19295. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  19296. /**
  19297. * This is the default FOV mode for perspective cameras.
  19298. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  19299. *
  19300. */
  19301. get: function () {
  19302. return Camera._FOVMODE_VERTICAL_FIXED;
  19303. },
  19304. enumerable: true,
  19305. configurable: true
  19306. });
  19307. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  19308. /**
  19309. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  19310. *
  19311. */
  19312. get: function () {
  19313. return Camera._FOVMODE_HORIZONTAL_FIXED;
  19314. },
  19315. enumerable: true,
  19316. configurable: true
  19317. });
  19318. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  19319. get: function () {
  19320. return Camera._RIG_MODE_NONE;
  19321. },
  19322. enumerable: true,
  19323. configurable: true
  19324. });
  19325. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  19326. get: function () {
  19327. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  19328. },
  19329. enumerable: true,
  19330. configurable: true
  19331. });
  19332. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  19333. get: function () {
  19334. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  19335. },
  19336. enumerable: true,
  19337. configurable: true
  19338. });
  19339. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  19340. get: function () {
  19341. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  19342. },
  19343. enumerable: true,
  19344. configurable: true
  19345. });
  19346. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  19347. get: function () {
  19348. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  19349. },
  19350. enumerable: true,
  19351. configurable: true
  19352. });
  19353. Object.defineProperty(Camera, "RIG_MODE_VR", {
  19354. get: function () {
  19355. return Camera._RIG_MODE_VR;
  19356. },
  19357. enumerable: true,
  19358. configurable: true
  19359. });
  19360. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  19361. get: function () {
  19362. return Camera._RIG_MODE_WEBVR;
  19363. },
  19364. enumerable: true,
  19365. configurable: true
  19366. });
  19367. /**
  19368. * Store current camera state (fov, position, etc..)
  19369. */
  19370. Camera.prototype.storeState = function () {
  19371. this._stateStored = true;
  19372. this._storedFov = this.fov;
  19373. return this;
  19374. };
  19375. /**
  19376. * Restores the camera state values if it has been stored. You must call storeState() first
  19377. */
  19378. Camera.prototype._restoreStateValues = function () {
  19379. if (!this._stateStored) {
  19380. return false;
  19381. }
  19382. this.fov = this._storedFov;
  19383. return true;
  19384. };
  19385. /**
  19386. * Restored camera state. You must call storeState() first
  19387. */
  19388. Camera.prototype.restoreState = function () {
  19389. if (this._restoreStateValues()) {
  19390. this.onRestoreStateObservable.notifyObservers(this);
  19391. return true;
  19392. }
  19393. return false;
  19394. };
  19395. Camera.prototype.getClassName = function () {
  19396. return "Camera";
  19397. };
  19398. /**
  19399. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  19400. */
  19401. Camera.prototype.toString = function (fullDetails) {
  19402. var ret = "Name: " + this.name;
  19403. ret += ", type: " + this.getClassName();
  19404. if (this.animations) {
  19405. for (var i = 0; i < this.animations.length; i++) {
  19406. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  19407. }
  19408. }
  19409. if (fullDetails) {
  19410. }
  19411. return ret;
  19412. };
  19413. Object.defineProperty(Camera.prototype, "globalPosition", {
  19414. get: function () {
  19415. return this._globalPosition;
  19416. },
  19417. enumerable: true,
  19418. configurable: true
  19419. });
  19420. Camera.prototype.getActiveMeshes = function () {
  19421. return this._activeMeshes;
  19422. };
  19423. Camera.prototype.isActiveMesh = function (mesh) {
  19424. return (this._activeMeshes.indexOf(mesh) !== -1);
  19425. };
  19426. //Cache
  19427. Camera.prototype._initCache = function () {
  19428. _super.prototype._initCache.call(this);
  19429. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  19430. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  19431. this._cache.mode = undefined;
  19432. this._cache.minZ = undefined;
  19433. this._cache.maxZ = undefined;
  19434. this._cache.fov = undefined;
  19435. this._cache.fovMode = undefined;
  19436. this._cache.aspectRatio = undefined;
  19437. this._cache.orthoLeft = undefined;
  19438. this._cache.orthoRight = undefined;
  19439. this._cache.orthoBottom = undefined;
  19440. this._cache.orthoTop = undefined;
  19441. this._cache.renderWidth = undefined;
  19442. this._cache.renderHeight = undefined;
  19443. };
  19444. Camera.prototype._updateCache = function (ignoreParentClass) {
  19445. if (!ignoreParentClass) {
  19446. _super.prototype._updateCache.call(this);
  19447. }
  19448. this._cache.position.copyFrom(this.position);
  19449. this._cache.upVector.copyFrom(this.upVector);
  19450. };
  19451. // Synchronized
  19452. Camera.prototype._isSynchronized = function () {
  19453. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  19454. };
  19455. Camera.prototype._isSynchronizedViewMatrix = function () {
  19456. if (!_super.prototype._isSynchronized.call(this))
  19457. return false;
  19458. return this._cache.position.equals(this.position)
  19459. && this._cache.upVector.equals(this.upVector)
  19460. && this.isSynchronizedWithParent();
  19461. };
  19462. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  19463. var check = this._cache.mode === this.mode
  19464. && this._cache.minZ === this.minZ
  19465. && this._cache.maxZ === this.maxZ;
  19466. if (!check) {
  19467. return false;
  19468. }
  19469. var engine = this.getEngine();
  19470. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  19471. check = this._cache.fov === this.fov
  19472. && this._cache.fovMode === this.fovMode
  19473. && this._cache.aspectRatio === engine.getAspectRatio(this);
  19474. }
  19475. else {
  19476. check = this._cache.orthoLeft === this.orthoLeft
  19477. && this._cache.orthoRight === this.orthoRight
  19478. && this._cache.orthoBottom === this.orthoBottom
  19479. && this._cache.orthoTop === this.orthoTop
  19480. && this._cache.renderWidth === engine.getRenderWidth()
  19481. && this._cache.renderHeight === engine.getRenderHeight();
  19482. }
  19483. return check;
  19484. };
  19485. // Controls
  19486. Camera.prototype.attachControl = function (element, noPreventDefault) {
  19487. };
  19488. Camera.prototype.detachControl = function (element) {
  19489. };
  19490. Camera.prototype.update = function () {
  19491. this._checkInputs();
  19492. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  19493. this._updateRigCameras();
  19494. }
  19495. };
  19496. Camera.prototype._checkInputs = function () {
  19497. this.onAfterCheckInputsObservable.notifyObservers(this);
  19498. };
  19499. Object.defineProperty(Camera.prototype, "rigCameras", {
  19500. get: function () {
  19501. return this._rigCameras;
  19502. },
  19503. enumerable: true,
  19504. configurable: true
  19505. });
  19506. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  19507. get: function () {
  19508. return this._rigPostProcess;
  19509. },
  19510. enumerable: true,
  19511. configurable: true
  19512. });
  19513. Camera.prototype._cascadePostProcessesToRigCams = function () {
  19514. // invalidate framebuffer
  19515. if (this._postProcesses.length > 0) {
  19516. this._postProcesses[0].markTextureDirty();
  19517. }
  19518. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  19519. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  19520. var cam = this._rigCameras[i];
  19521. var rigPostProcess = cam._rigPostProcess;
  19522. // for VR rig, there does not have to be a post process
  19523. if (rigPostProcess) {
  19524. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  19525. if (isPass) {
  19526. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  19527. cam.isIntermediate = this._postProcesses.length === 0;
  19528. }
  19529. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  19530. rigPostProcess.markTextureDirty();
  19531. }
  19532. else {
  19533. cam._postProcesses = this._postProcesses.slice(0);
  19534. }
  19535. }
  19536. };
  19537. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  19538. if (insertAt === void 0) { insertAt = null; }
  19539. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  19540. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  19541. return 0;
  19542. }
  19543. if (insertAt == null || insertAt < 0) {
  19544. this._postProcesses.push(postProcess);
  19545. }
  19546. else {
  19547. this._postProcesses.splice(insertAt, 0, postProcess);
  19548. }
  19549. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  19550. return this._postProcesses.indexOf(postProcess);
  19551. };
  19552. Camera.prototype.detachPostProcess = function (postProcess) {
  19553. var idx = this._postProcesses.indexOf(postProcess);
  19554. if (idx !== -1) {
  19555. this._postProcesses.splice(idx, 1);
  19556. }
  19557. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  19558. };
  19559. Camera.prototype.getWorldMatrix = function () {
  19560. if (!this._worldMatrix) {
  19561. this._worldMatrix = BABYLON.Matrix.Identity();
  19562. }
  19563. var viewMatrix = this.getViewMatrix();
  19564. viewMatrix.invertToRef(this._worldMatrix);
  19565. return this._worldMatrix;
  19566. };
  19567. Camera.prototype._getViewMatrix = function () {
  19568. return BABYLON.Matrix.Identity();
  19569. };
  19570. Camera.prototype.getViewMatrix = function (force) {
  19571. if (!force && this._isSynchronizedViewMatrix()) {
  19572. return this._computedViewMatrix;
  19573. }
  19574. this.updateCache();
  19575. this._computedViewMatrix = this._getViewMatrix();
  19576. this._currentRenderId = this.getScene().getRenderId();
  19577. this._refreshFrustumPlanes = true;
  19578. if (!this.parent || !this.parent.getWorldMatrix) {
  19579. this._globalPosition.copyFrom(this.position);
  19580. }
  19581. else {
  19582. if (!this._worldMatrix) {
  19583. this._worldMatrix = BABYLON.Matrix.Identity();
  19584. }
  19585. this._computedViewMatrix.invertToRef(this._worldMatrix);
  19586. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  19587. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  19588. this._computedViewMatrix.invert();
  19589. this._markSyncedWithParent();
  19590. }
  19591. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  19592. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  19593. }
  19594. this.onViewMatrixChangedObservable.notifyObservers(this);
  19595. return this._computedViewMatrix;
  19596. };
  19597. Camera.prototype.freezeProjectionMatrix = function (projection) {
  19598. this._doNotComputeProjectionMatrix = true;
  19599. if (projection !== undefined) {
  19600. this._projectionMatrix = projection;
  19601. }
  19602. };
  19603. ;
  19604. Camera.prototype.unfreezeProjectionMatrix = function () {
  19605. this._doNotComputeProjectionMatrix = false;
  19606. };
  19607. ;
  19608. Camera.prototype.getProjectionMatrix = function (force) {
  19609. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  19610. return this._projectionMatrix;
  19611. }
  19612. // Cache
  19613. this._cache.mode = this.mode;
  19614. this._cache.minZ = this.minZ;
  19615. this._cache.maxZ = this.maxZ;
  19616. // Matrix
  19617. this._refreshFrustumPlanes = true;
  19618. var engine = this.getEngine();
  19619. var scene = this.getScene();
  19620. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  19621. this._cache.fov = this.fov;
  19622. this._cache.fovMode = this.fovMode;
  19623. this._cache.aspectRatio = engine.getAspectRatio(this);
  19624. if (this.minZ <= 0) {
  19625. this.minZ = 0.1;
  19626. }
  19627. if (scene.useRightHandedSystem) {
  19628. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  19629. }
  19630. else {
  19631. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  19632. }
  19633. }
  19634. else {
  19635. var halfWidth = engine.getRenderWidth() / 2.0;
  19636. var halfHeight = engine.getRenderHeight() / 2.0;
  19637. if (scene.useRightHandedSystem) {
  19638. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  19639. }
  19640. else {
  19641. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  19642. }
  19643. this._cache.orthoLeft = this.orthoLeft;
  19644. this._cache.orthoRight = this.orthoRight;
  19645. this._cache.orthoBottom = this.orthoBottom;
  19646. this._cache.orthoTop = this.orthoTop;
  19647. this._cache.renderWidth = engine.getRenderWidth();
  19648. this._cache.renderHeight = engine.getRenderHeight();
  19649. }
  19650. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  19651. return this._projectionMatrix;
  19652. };
  19653. Camera.prototype.getTranformationMatrix = function () {
  19654. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  19655. return this._transformMatrix;
  19656. };
  19657. Camera.prototype.updateFrustumPlanes = function () {
  19658. if (!this._refreshFrustumPlanes) {
  19659. return;
  19660. }
  19661. this.getTranformationMatrix();
  19662. if (!this._frustumPlanes) {
  19663. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  19664. }
  19665. else {
  19666. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  19667. }
  19668. this._refreshFrustumPlanes = false;
  19669. };
  19670. Camera.prototype.isInFrustum = function (target) {
  19671. this.updateFrustumPlanes();
  19672. return target.isInFrustum(this._frustumPlanes);
  19673. };
  19674. Camera.prototype.isCompletelyInFrustum = function (target) {
  19675. this.updateFrustumPlanes();
  19676. return target.isCompletelyInFrustum(this._frustumPlanes);
  19677. };
  19678. Camera.prototype.getForwardRay = function (length, transform, origin) {
  19679. if (length === void 0) { length = 100; }
  19680. if (!transform) {
  19681. transform = this.getWorldMatrix();
  19682. }
  19683. if (!origin) {
  19684. origin = this.position;
  19685. }
  19686. var forward = new BABYLON.Vector3(0, 0, 1);
  19687. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  19688. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  19689. return new BABYLON.Ray(origin, direction, length);
  19690. };
  19691. Camera.prototype.dispose = function () {
  19692. // Observables
  19693. this.onViewMatrixChangedObservable.clear();
  19694. this.onProjectionMatrixChangedObservable.clear();
  19695. this.onAfterCheckInputsObservable.clear();
  19696. this.onRestoreStateObservable.clear();
  19697. // Inputs
  19698. if (this.inputs) {
  19699. this.inputs.clear();
  19700. }
  19701. // Animations
  19702. this.getScene().stopAnimation(this);
  19703. // Remove from scene
  19704. this.getScene().removeCamera(this);
  19705. while (this._rigCameras.length > 0) {
  19706. var camera = this._rigCameras.pop();
  19707. if (camera) {
  19708. camera.dispose();
  19709. }
  19710. }
  19711. // Postprocesses
  19712. if (this._rigPostProcess) {
  19713. this._rigPostProcess.dispose(this);
  19714. this._rigPostProcess = null;
  19715. this._postProcesses = [];
  19716. }
  19717. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  19718. this._rigPostProcess = null;
  19719. this._postProcesses = [];
  19720. }
  19721. else {
  19722. var i = this._postProcesses.length;
  19723. while (--i >= 0) {
  19724. this._postProcesses[i].dispose(this);
  19725. }
  19726. }
  19727. // Render targets
  19728. var i = this.customRenderTargets.length;
  19729. while (--i >= 0) {
  19730. this.customRenderTargets[i].dispose();
  19731. }
  19732. this.customRenderTargets = [];
  19733. // Active Meshes
  19734. this._activeMeshes.dispose();
  19735. _super.prototype.dispose.call(this);
  19736. };
  19737. Object.defineProperty(Camera.prototype, "leftCamera", {
  19738. // ---- Camera rigs section ----
  19739. get: function () {
  19740. if (this._rigCameras.length < 1) {
  19741. return null;
  19742. }
  19743. return this._rigCameras[0];
  19744. },
  19745. enumerable: true,
  19746. configurable: true
  19747. });
  19748. Object.defineProperty(Camera.prototype, "rightCamera", {
  19749. get: function () {
  19750. if (this._rigCameras.length < 2) {
  19751. return null;
  19752. }
  19753. return this._rigCameras[1];
  19754. },
  19755. enumerable: true,
  19756. configurable: true
  19757. });
  19758. Camera.prototype.getLeftTarget = function () {
  19759. if (this._rigCameras.length < 1) {
  19760. return null;
  19761. }
  19762. return this._rigCameras[0].getTarget();
  19763. };
  19764. Camera.prototype.getRightTarget = function () {
  19765. if (this._rigCameras.length < 2) {
  19766. return null;
  19767. }
  19768. return this._rigCameras[1].getTarget();
  19769. };
  19770. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  19771. if (this.cameraRigMode === mode) {
  19772. return;
  19773. }
  19774. while (this._rigCameras.length > 0) {
  19775. var camera = this._rigCameras.pop();
  19776. if (camera) {
  19777. camera.dispose();
  19778. }
  19779. }
  19780. this.cameraRigMode = mode;
  19781. this._cameraRigParams = {};
  19782. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  19783. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  19784. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  19785. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  19786. // create the rig cameras, unless none
  19787. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  19788. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  19789. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  19790. if (leftCamera && rightCamera) {
  19791. this._rigCameras.push(leftCamera);
  19792. this._rigCameras.push(rightCamera);
  19793. }
  19794. }
  19795. switch (this.cameraRigMode) {
  19796. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  19797. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  19798. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  19799. break;
  19800. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  19801. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  19802. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  19803. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  19804. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  19805. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  19806. break;
  19807. case Camera.RIG_MODE_VR:
  19808. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  19809. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  19810. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  19811. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  19812. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  19813. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  19814. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  19815. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  19816. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  19817. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  19818. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  19819. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  19820. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  19821. if (metrics.compensateDistortion) {
  19822. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  19823. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  19824. }
  19825. break;
  19826. case Camera.RIG_MODE_WEBVR:
  19827. if (rigParams.vrDisplay) {
  19828. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  19829. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  19830. //Left eye
  19831. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  19832. this._rigCameras[0].setCameraRigParameter("left", true);
  19833. //leaving this for future reference
  19834. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  19835. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  19836. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  19837. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  19838. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  19839. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  19840. this._rigCameras[0].parent = this;
  19841. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  19842. //Right eye
  19843. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  19844. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  19845. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  19846. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  19847. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  19848. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  19849. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  19850. this._rigCameras[1].parent = this;
  19851. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  19852. if (Camera.UseAlternateWebVRRendering) {
  19853. this._rigCameras[1]._skipRendering = true;
  19854. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  19855. }
  19856. }
  19857. break;
  19858. }
  19859. this._cascadePostProcessesToRigCams();
  19860. this.update();
  19861. };
  19862. Camera.prototype._getVRProjectionMatrix = function () {
  19863. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  19864. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  19865. return this._projectionMatrix;
  19866. };
  19867. Camera.prototype._updateCameraRotationMatrix = function () {
  19868. //Here for WebVR
  19869. };
  19870. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  19871. //Here for WebVR
  19872. };
  19873. /**
  19874. * This function MUST be overwritten by the different WebVR cameras available.
  19875. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  19876. */
  19877. Camera.prototype._getWebVRProjectionMatrix = function () {
  19878. return BABYLON.Matrix.Identity();
  19879. };
  19880. /**
  19881. * This function MUST be overwritten by the different WebVR cameras available.
  19882. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  19883. */
  19884. Camera.prototype._getWebVRViewMatrix = function () {
  19885. return BABYLON.Matrix.Identity();
  19886. };
  19887. Camera.prototype.setCameraRigParameter = function (name, value) {
  19888. if (!this._cameraRigParams) {
  19889. this._cameraRigParams = {};
  19890. }
  19891. this._cameraRigParams[name] = value;
  19892. //provisionnally:
  19893. if (name === "interaxialDistance") {
  19894. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  19895. }
  19896. };
  19897. /**
  19898. * needs to be overridden by children so sub has required properties to be copied
  19899. */
  19900. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  19901. return null;
  19902. };
  19903. /**
  19904. * May need to be overridden by children
  19905. */
  19906. Camera.prototype._updateRigCameras = function () {
  19907. for (var i = 0; i < this._rigCameras.length; i++) {
  19908. this._rigCameras[i].minZ = this.minZ;
  19909. this._rigCameras[i].maxZ = this.maxZ;
  19910. this._rigCameras[i].fov = this.fov;
  19911. }
  19912. // only update viewport when ANAGLYPH
  19913. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  19914. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  19915. }
  19916. };
  19917. Camera.prototype._setupInputs = function () {
  19918. };
  19919. Camera.prototype.serialize = function () {
  19920. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  19921. // Type
  19922. serializationObject.type = this.getClassName();
  19923. // Parent
  19924. if (this.parent) {
  19925. serializationObject.parentId = this.parent.id;
  19926. }
  19927. if (this.inputs) {
  19928. this.inputs.serialize(serializationObject);
  19929. }
  19930. // Animations
  19931. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  19932. serializationObject.ranges = this.serializeAnimationRanges();
  19933. return serializationObject;
  19934. };
  19935. Camera.prototype.clone = function (name) {
  19936. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  19937. };
  19938. Camera.prototype.getDirection = function (localAxis) {
  19939. var result = BABYLON.Vector3.Zero();
  19940. this.getDirectionToRef(localAxis, result);
  19941. return result;
  19942. };
  19943. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  19944. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  19945. };
  19946. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  19947. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  19948. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  19949. switch (type) {
  19950. case "ArcRotateCamera":
  19951. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  19952. case "DeviceOrientationCamera":
  19953. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  19954. case "FollowCamera":
  19955. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  19956. case "ArcFollowCamera":
  19957. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  19958. case "GamepadCamera":
  19959. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  19960. case "TouchCamera":
  19961. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  19962. case "VirtualJoysticksCamera":
  19963. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  19964. case "WebVRFreeCamera":
  19965. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  19966. case "WebVRGamepadCamera":
  19967. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  19968. case "VRDeviceOrientationFreeCamera":
  19969. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  19970. case "VRDeviceOrientationGamepadCamera":
  19971. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  19972. case "AnaglyphArcRotateCamera":
  19973. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  19974. case "AnaglyphFreeCamera":
  19975. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  19976. case "AnaglyphGamepadCamera":
  19977. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  19978. case "AnaglyphUniversalCamera":
  19979. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  19980. case "StereoscopicArcRotateCamera":
  19981. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  19982. case "StereoscopicFreeCamera":
  19983. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  19984. case "StereoscopicGamepadCamera":
  19985. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  19986. case "StereoscopicUniversalCamera":
  19987. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  19988. case "FreeCamera":// Forcing Universal here
  19989. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  19990. default:// Universal Camera is the default value
  19991. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  19992. }
  19993. };
  19994. Camera.prototype.computeWorldMatrix = function () {
  19995. return this.getWorldMatrix();
  19996. };
  19997. Camera.Parse = function (parsedCamera, scene) {
  19998. var type = parsedCamera.type;
  19999. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  20000. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  20001. // Parent
  20002. if (parsedCamera.parentId) {
  20003. camera._waitingParentId = parsedCamera.parentId;
  20004. }
  20005. //If camera has an input manager, let it parse inputs settings
  20006. if (camera.inputs) {
  20007. camera.inputs.parse(parsedCamera);
  20008. camera._setupInputs();
  20009. }
  20010. if (camera.setPosition) {
  20011. camera.position.copyFromFloats(0, 0, 0);
  20012. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  20013. }
  20014. // Target
  20015. if (parsedCamera.target) {
  20016. if (camera.setTarget) {
  20017. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  20018. }
  20019. }
  20020. // Apply 3d rig, when found
  20021. if (parsedCamera.cameraRigMode) {
  20022. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  20023. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  20024. }
  20025. // Animations
  20026. if (parsedCamera.animations) {
  20027. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  20028. var parsedAnimation = parsedCamera.animations[animationIndex];
  20029. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  20030. }
  20031. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  20032. }
  20033. if (parsedCamera.autoAnimate) {
  20034. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  20035. }
  20036. return camera;
  20037. };
  20038. // Statics
  20039. Camera._PERSPECTIVE_CAMERA = 0;
  20040. Camera._ORTHOGRAPHIC_CAMERA = 1;
  20041. Camera._FOVMODE_VERTICAL_FIXED = 0;
  20042. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  20043. Camera._RIG_MODE_NONE = 0;
  20044. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  20045. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  20046. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  20047. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  20048. Camera._RIG_MODE_VR = 20;
  20049. Camera._RIG_MODE_WEBVR = 21;
  20050. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  20051. Camera.UseAlternateWebVRRendering = false;
  20052. __decorate([
  20053. BABYLON.serializeAsVector3()
  20054. ], Camera.prototype, "position", void 0);
  20055. __decorate([
  20056. BABYLON.serializeAsVector3()
  20057. ], Camera.prototype, "upVector", void 0);
  20058. __decorate([
  20059. BABYLON.serialize()
  20060. ], Camera.prototype, "orthoLeft", void 0);
  20061. __decorate([
  20062. BABYLON.serialize()
  20063. ], Camera.prototype, "orthoRight", void 0);
  20064. __decorate([
  20065. BABYLON.serialize()
  20066. ], Camera.prototype, "orthoBottom", void 0);
  20067. __decorate([
  20068. BABYLON.serialize()
  20069. ], Camera.prototype, "orthoTop", void 0);
  20070. __decorate([
  20071. BABYLON.serialize()
  20072. ], Camera.prototype, "fov", void 0);
  20073. __decorate([
  20074. BABYLON.serialize()
  20075. ], Camera.prototype, "minZ", void 0);
  20076. __decorate([
  20077. BABYLON.serialize()
  20078. ], Camera.prototype, "maxZ", void 0);
  20079. __decorate([
  20080. BABYLON.serialize()
  20081. ], Camera.prototype, "inertia", void 0);
  20082. __decorate([
  20083. BABYLON.serialize()
  20084. ], Camera.prototype, "mode", void 0);
  20085. __decorate([
  20086. BABYLON.serialize()
  20087. ], Camera.prototype, "layerMask", void 0);
  20088. __decorate([
  20089. BABYLON.serialize()
  20090. ], Camera.prototype, "fovMode", void 0);
  20091. __decorate([
  20092. BABYLON.serialize()
  20093. ], Camera.prototype, "cameraRigMode", void 0);
  20094. __decorate([
  20095. BABYLON.serialize()
  20096. ], Camera.prototype, "interaxialDistance", void 0);
  20097. __decorate([
  20098. BABYLON.serialize()
  20099. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  20100. return Camera;
  20101. }(BABYLON.Node));
  20102. BABYLON.Camera = Camera;
  20103. })(BABYLON || (BABYLON = {}));
  20104. //# sourceMappingURL=babylon.camera.js.map
  20105. var BABYLON;
  20106. (function (BABYLON) {
  20107. var RenderingManager = /** @class */ (function () {
  20108. function RenderingManager(scene) {
  20109. this._renderingGroups = new Array();
  20110. this._autoClearDepthStencil = {};
  20111. this._customOpaqueSortCompareFn = {};
  20112. this._customAlphaTestSortCompareFn = {};
  20113. this._customTransparentSortCompareFn = {};
  20114. this._renderinGroupInfo = null;
  20115. this._scene = scene;
  20116. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  20117. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  20118. }
  20119. }
  20120. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  20121. if (depth === void 0) { depth = true; }
  20122. if (stencil === void 0) { stencil = true; }
  20123. if (this._depthStencilBufferAlreadyCleaned) {
  20124. return;
  20125. }
  20126. this._scene.getEngine().clear(null, false, depth, stencil);
  20127. this._depthStencilBufferAlreadyCleaned = true;
  20128. };
  20129. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  20130. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  20131. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  20132. var info = null;
  20133. if (observable) {
  20134. if (!this._renderinGroupInfo) {
  20135. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  20136. }
  20137. info = this._renderinGroupInfo;
  20138. info.scene = this._scene;
  20139. info.camera = this._scene.activeCamera;
  20140. }
  20141. // Dispatch sprites
  20142. if (renderSprites) {
  20143. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  20144. var manager = this._scene.spriteManagers[index];
  20145. this.dispatchSprites(manager);
  20146. }
  20147. }
  20148. // Render
  20149. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  20150. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  20151. var renderingGroup = this._renderingGroups[index];
  20152. if (!renderingGroup && !observable)
  20153. continue;
  20154. var renderingGroupMask = 0;
  20155. // Fire PRECLEAR stage
  20156. if (observable && info) {
  20157. renderingGroupMask = Math.pow(2, index);
  20158. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  20159. info.renderingGroupId = index;
  20160. observable.notifyObservers(info, renderingGroupMask);
  20161. }
  20162. // Clear depth/stencil if needed
  20163. if (RenderingManager.AUTOCLEAR) {
  20164. var autoClear = this._autoClearDepthStencil[index];
  20165. if (autoClear && autoClear.autoClear) {
  20166. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  20167. }
  20168. }
  20169. if (observable && info) {
  20170. // Fire PREOPAQUE stage
  20171. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  20172. observable.notifyObservers(info, renderingGroupMask);
  20173. // Fire PRETRANSPARENT stage
  20174. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  20175. observable.notifyObservers(info, renderingGroupMask);
  20176. }
  20177. if (renderingGroup)
  20178. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  20179. // Fire POSTTRANSPARENT stage
  20180. if (observable && info) {
  20181. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  20182. observable.notifyObservers(info, renderingGroupMask);
  20183. }
  20184. }
  20185. };
  20186. RenderingManager.prototype.reset = function () {
  20187. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  20188. var renderingGroup = this._renderingGroups[index];
  20189. if (renderingGroup) {
  20190. renderingGroup.prepare();
  20191. }
  20192. }
  20193. };
  20194. RenderingManager.prototype.dispose = function () {
  20195. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  20196. var renderingGroup = this._renderingGroups[index];
  20197. if (renderingGroup) {
  20198. renderingGroup.dispose();
  20199. }
  20200. }
  20201. this._renderingGroups.length = 0;
  20202. };
  20203. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  20204. if (this._renderingGroups[renderingGroupId] === undefined) {
  20205. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  20206. }
  20207. };
  20208. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  20209. var renderingGroupId = spriteManager.renderingGroupId || 0;
  20210. this._prepareRenderingGroup(renderingGroupId);
  20211. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  20212. };
  20213. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  20214. var renderingGroupId = particleSystem.renderingGroupId || 0;
  20215. this._prepareRenderingGroup(renderingGroupId);
  20216. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  20217. };
  20218. /**
  20219. * @param subMesh The submesh to dispatch
  20220. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  20221. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  20222. */
  20223. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  20224. if (mesh === undefined) {
  20225. mesh = subMesh.getMesh();
  20226. }
  20227. var renderingGroupId = mesh.renderingGroupId || 0;
  20228. this._prepareRenderingGroup(renderingGroupId);
  20229. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  20230. };
  20231. /**
  20232. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  20233. * This allowed control for front to back rendering or reversly depending of the special needs.
  20234. *
  20235. * @param renderingGroupId The rendering group id corresponding to its index
  20236. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  20237. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  20238. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  20239. */
  20240. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  20241. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  20242. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  20243. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  20244. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  20245. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  20246. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  20247. if (this._renderingGroups[renderingGroupId]) {
  20248. var group = this._renderingGroups[renderingGroupId];
  20249. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  20250. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  20251. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  20252. }
  20253. };
  20254. /**
  20255. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  20256. *
  20257. * @param renderingGroupId The rendering group id corresponding to its index
  20258. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  20259. * @param depth Automatically clears depth between groups if true and autoClear is true.
  20260. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  20261. */
  20262. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  20263. if (depth === void 0) { depth = true; }
  20264. if (stencil === void 0) { stencil = true; }
  20265. this._autoClearDepthStencil[renderingGroupId] = {
  20266. autoClear: autoClearDepthStencil,
  20267. depth: depth,
  20268. stencil: stencil
  20269. };
  20270. };
  20271. /**
  20272. * The max id used for rendering groups (not included)
  20273. */
  20274. RenderingManager.MAX_RENDERINGGROUPS = 4;
  20275. /**
  20276. * The min id used for rendering groups (included)
  20277. */
  20278. RenderingManager.MIN_RENDERINGGROUPS = 0;
  20279. /**
  20280. * Used to globally prevent autoclearing scenes.
  20281. */
  20282. RenderingManager.AUTOCLEAR = true;
  20283. return RenderingManager;
  20284. }());
  20285. BABYLON.RenderingManager = RenderingManager;
  20286. })(BABYLON || (BABYLON = {}));
  20287. //# sourceMappingURL=babylon.renderingManager.js.map
  20288. var BABYLON;
  20289. (function (BABYLON) {
  20290. var RenderingGroup = /** @class */ (function () {
  20291. /**
  20292. * Creates a new rendering group.
  20293. * @param index The rendering group index
  20294. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  20295. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  20296. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  20297. */
  20298. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  20299. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  20300. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  20301. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  20302. this.index = index;
  20303. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  20304. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  20305. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  20306. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  20307. this._particleSystems = new BABYLON.SmartArray(256);
  20308. this._spriteManagers = new BABYLON.SmartArray(256);
  20309. this._edgesRenderers = new BABYLON.SmartArray(16);
  20310. this._scene = scene;
  20311. this.opaqueSortCompareFn = opaqueSortCompareFn;
  20312. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  20313. this.transparentSortCompareFn = transparentSortCompareFn;
  20314. }
  20315. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  20316. /**
  20317. * Set the opaque sort comparison function.
  20318. * If null the sub meshes will be render in the order they were created
  20319. */
  20320. set: function (value) {
  20321. this._opaqueSortCompareFn = value;
  20322. if (value) {
  20323. this._renderOpaque = this.renderOpaqueSorted;
  20324. }
  20325. else {
  20326. this._renderOpaque = RenderingGroup.renderUnsorted;
  20327. }
  20328. },
  20329. enumerable: true,
  20330. configurable: true
  20331. });
  20332. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  20333. /**
  20334. * Set the alpha test sort comparison function.
  20335. * If null the sub meshes will be render in the order they were created
  20336. */
  20337. set: function (value) {
  20338. this._alphaTestSortCompareFn = value;
  20339. if (value) {
  20340. this._renderAlphaTest = this.renderAlphaTestSorted;
  20341. }
  20342. else {
  20343. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  20344. }
  20345. },
  20346. enumerable: true,
  20347. configurable: true
  20348. });
  20349. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  20350. /**
  20351. * Set the transparent sort comparison function.
  20352. * If null the sub meshes will be render in the order they were created
  20353. */
  20354. set: function (value) {
  20355. if (value) {
  20356. this._transparentSortCompareFn = value;
  20357. }
  20358. else {
  20359. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  20360. }
  20361. this._renderTransparent = this.renderTransparentSorted;
  20362. },
  20363. enumerable: true,
  20364. configurable: true
  20365. });
  20366. /**
  20367. * Render all the sub meshes contained in the group.
  20368. * @param customRenderFunction Used to override the default render behaviour of the group.
  20369. * @returns true if rendered some submeshes.
  20370. */
  20371. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  20372. if (customRenderFunction) {
  20373. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  20374. return;
  20375. }
  20376. var engine = this._scene.getEngine();
  20377. // Depth only
  20378. if (this._depthOnlySubMeshes.length !== 0) {
  20379. engine.setColorWrite(false);
  20380. this._renderAlphaTest(this._depthOnlySubMeshes);
  20381. engine.setColorWrite(true);
  20382. }
  20383. // Opaque
  20384. if (this._opaqueSubMeshes.length !== 0) {
  20385. this._renderOpaque(this._opaqueSubMeshes);
  20386. }
  20387. // Alpha test
  20388. if (this._alphaTestSubMeshes.length !== 0) {
  20389. this._renderAlphaTest(this._alphaTestSubMeshes);
  20390. }
  20391. var stencilState = engine.getStencilBuffer();
  20392. engine.setStencilBuffer(false);
  20393. // Sprites
  20394. if (renderSprites) {
  20395. this._renderSprites();
  20396. }
  20397. // Particles
  20398. if (renderParticles) {
  20399. this._renderParticles(activeMeshes);
  20400. }
  20401. if (this.onBeforeTransparentRendering) {
  20402. this.onBeforeTransparentRendering();
  20403. }
  20404. // Transparent
  20405. if (this._transparentSubMeshes.length !== 0) {
  20406. this._renderTransparent(this._transparentSubMeshes);
  20407. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  20408. }
  20409. // Set back stencil to false in case it changes before the edge renderer.
  20410. engine.setStencilBuffer(false);
  20411. // Edges
  20412. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  20413. this._edgesRenderers.data[edgesRendererIndex].render();
  20414. }
  20415. // Restore Stencil state.
  20416. engine.setStencilBuffer(stencilState);
  20417. };
  20418. /**
  20419. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  20420. * @param subMeshes The submeshes to render
  20421. */
  20422. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  20423. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  20424. };
  20425. /**
  20426. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  20427. * @param subMeshes The submeshes to render
  20428. */
  20429. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  20430. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  20431. };
  20432. /**
  20433. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  20434. * @param subMeshes The submeshes to render
  20435. */
  20436. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  20437. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  20438. };
  20439. /**
  20440. * Renders the submeshes in a specified order.
  20441. * @param subMeshes The submeshes to sort before render
  20442. * @param sortCompareFn The comparison function use to sort
  20443. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  20444. * @param transparent Specifies to activate blending if true
  20445. */
  20446. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  20447. var subIndex = 0;
  20448. var subMesh;
  20449. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  20450. for (; subIndex < subMeshes.length; subIndex++) {
  20451. subMesh = subMeshes.data[subIndex];
  20452. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  20453. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  20454. }
  20455. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  20456. if (sortCompareFn) {
  20457. sortedArray.sort(sortCompareFn);
  20458. }
  20459. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  20460. subMesh = sortedArray[subIndex];
  20461. if (transparent) {
  20462. var material = subMesh.getMaterial();
  20463. if (material && material.needDepthPrePass) {
  20464. var engine = material.getScene().getEngine();
  20465. engine.setColorWrite(false);
  20466. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  20467. subMesh.render(false);
  20468. engine.setColorWrite(true);
  20469. }
  20470. }
  20471. subMesh.render(transparent);
  20472. }
  20473. };
  20474. /**
  20475. * Renders the submeshes in the order they were dispatched (no sort applied).
  20476. * @param subMeshes The submeshes to render
  20477. */
  20478. RenderingGroup.renderUnsorted = function (subMeshes) {
  20479. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  20480. var submesh = subMeshes.data[subIndex];
  20481. submesh.render(false);
  20482. }
  20483. };
  20484. /**
  20485. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  20486. * are rendered back to front if in the same alpha index.
  20487. *
  20488. * @param a The first submesh
  20489. * @param b The second submesh
  20490. * @returns The result of the comparison
  20491. */
  20492. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  20493. // Alpha index first
  20494. if (a._alphaIndex > b._alphaIndex) {
  20495. return 1;
  20496. }
  20497. if (a._alphaIndex < b._alphaIndex) {
  20498. return -1;
  20499. }
  20500. // Then distance to camera
  20501. return RenderingGroup.backToFrontSortCompare(a, b);
  20502. };
  20503. /**
  20504. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  20505. * are rendered back to front.
  20506. *
  20507. * @param a The first submesh
  20508. * @param b The second submesh
  20509. * @returns The result of the comparison
  20510. */
  20511. RenderingGroup.backToFrontSortCompare = function (a, b) {
  20512. // Then distance to camera
  20513. if (a._distanceToCamera < b._distanceToCamera) {
  20514. return 1;
  20515. }
  20516. if (a._distanceToCamera > b._distanceToCamera) {
  20517. return -1;
  20518. }
  20519. return 0;
  20520. };
  20521. /**
  20522. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  20523. * are rendered front to back (prevent overdraw).
  20524. *
  20525. * @param a The first submesh
  20526. * @param b The second submesh
  20527. * @returns The result of the comparison
  20528. */
  20529. RenderingGroup.frontToBackSortCompare = function (a, b) {
  20530. // Then distance to camera
  20531. if (a._distanceToCamera < b._distanceToCamera) {
  20532. return -1;
  20533. }
  20534. if (a._distanceToCamera > b._distanceToCamera) {
  20535. return 1;
  20536. }
  20537. return 0;
  20538. };
  20539. /**
  20540. * Resets the different lists of submeshes to prepare a new frame.
  20541. */
  20542. RenderingGroup.prototype.prepare = function () {
  20543. this._opaqueSubMeshes.reset();
  20544. this._transparentSubMeshes.reset();
  20545. this._alphaTestSubMeshes.reset();
  20546. this._depthOnlySubMeshes.reset();
  20547. this._particleSystems.reset();
  20548. this._spriteManagers.reset();
  20549. this._edgesRenderers.reset();
  20550. };
  20551. RenderingGroup.prototype.dispose = function () {
  20552. this._opaqueSubMeshes.dispose();
  20553. this._transparentSubMeshes.dispose();
  20554. this._alphaTestSubMeshes.dispose();
  20555. this._depthOnlySubMeshes.dispose();
  20556. this._particleSystems.dispose();
  20557. this._spriteManagers.dispose();
  20558. this._edgesRenderers.dispose();
  20559. };
  20560. /**
  20561. * Inserts the submesh in its correct queue depending on its material.
  20562. * @param subMesh The submesh to dispatch
  20563. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  20564. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  20565. */
  20566. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  20567. // Get mesh and materials if not provided
  20568. if (mesh === undefined) {
  20569. mesh = subMesh.getMesh();
  20570. }
  20571. if (material === undefined) {
  20572. material = subMesh.getMaterial();
  20573. }
  20574. if (material === null || material === undefined) {
  20575. return;
  20576. }
  20577. if (material.needAlphaBlendingForMesh(mesh)) {
  20578. this._transparentSubMeshes.push(subMesh);
  20579. }
  20580. else if (material.needAlphaTesting()) {
  20581. if (material.needDepthPrePass) {
  20582. this._depthOnlySubMeshes.push(subMesh);
  20583. }
  20584. this._alphaTestSubMeshes.push(subMesh);
  20585. }
  20586. else {
  20587. if (material.needDepthPrePass) {
  20588. this._depthOnlySubMeshes.push(subMesh);
  20589. }
  20590. this._opaqueSubMeshes.push(subMesh); // Opaque
  20591. }
  20592. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined) {
  20593. this._edgesRenderers.push(mesh._edgesRenderer);
  20594. }
  20595. };
  20596. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  20597. this._spriteManagers.push(spriteManager);
  20598. };
  20599. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  20600. this._particleSystems.push(particleSystem);
  20601. };
  20602. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  20603. if (this._particleSystems.length === 0) {
  20604. return;
  20605. }
  20606. // Particles
  20607. var activeCamera = this._scene.activeCamera;
  20608. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  20609. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  20610. var particleSystem = this._particleSystems.data[particleIndex];
  20611. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  20612. continue;
  20613. }
  20614. var emitter = particleSystem.emitter;
  20615. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  20616. this._scene._activeParticles.addCount(particleSystem.render(), false);
  20617. }
  20618. }
  20619. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  20620. };
  20621. RenderingGroup.prototype._renderSprites = function () {
  20622. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  20623. return;
  20624. }
  20625. // Sprites
  20626. var activeCamera = this._scene.activeCamera;
  20627. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  20628. for (var id = 0; id < this._spriteManagers.length; id++) {
  20629. var spriteManager = this._spriteManagers.data[id];
  20630. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  20631. spriteManager.render();
  20632. }
  20633. }
  20634. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  20635. };
  20636. return RenderingGroup;
  20637. }());
  20638. BABYLON.RenderingGroup = RenderingGroup;
  20639. })(BABYLON || (BABYLON = {}));
  20640. //# sourceMappingURL=babylon.renderingGroup.js.map
  20641. var BABYLON;
  20642. (function (BABYLON) {
  20643. var ClickInfo = /** @class */ (function () {
  20644. function ClickInfo() {
  20645. this._singleClick = false;
  20646. this._doubleClick = false;
  20647. this._hasSwiped = false;
  20648. this._ignore = false;
  20649. }
  20650. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  20651. get: function () {
  20652. return this._singleClick;
  20653. },
  20654. set: function (b) {
  20655. this._singleClick = b;
  20656. },
  20657. enumerable: true,
  20658. configurable: true
  20659. });
  20660. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  20661. get: function () {
  20662. return this._doubleClick;
  20663. },
  20664. set: function (b) {
  20665. this._doubleClick = b;
  20666. },
  20667. enumerable: true,
  20668. configurable: true
  20669. });
  20670. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  20671. get: function () {
  20672. return this._hasSwiped;
  20673. },
  20674. set: function (b) {
  20675. this._hasSwiped = b;
  20676. },
  20677. enumerable: true,
  20678. configurable: true
  20679. });
  20680. Object.defineProperty(ClickInfo.prototype, "ignore", {
  20681. get: function () {
  20682. return this._ignore;
  20683. },
  20684. set: function (b) {
  20685. this._ignore = b;
  20686. },
  20687. enumerable: true,
  20688. configurable: true
  20689. });
  20690. return ClickInfo;
  20691. }());
  20692. /**
  20693. * This class is used by the onRenderingGroupObservable
  20694. */
  20695. var RenderingGroupInfo = /** @class */ (function () {
  20696. function RenderingGroupInfo() {
  20697. }
  20698. /**
  20699. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  20700. * This stage will be fired no matter what
  20701. */
  20702. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  20703. /**
  20704. * Called before opaque object are rendered.
  20705. * This stage will be fired only if there's 3D Opaque content to render
  20706. */
  20707. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  20708. /**
  20709. * Called after the opaque objects are rendered and before the transparent ones
  20710. * This stage will be fired only if there's 3D transparent content to render
  20711. */
  20712. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  20713. /**
  20714. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  20715. * This stage will be fired no matter what
  20716. */
  20717. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  20718. return RenderingGroupInfo;
  20719. }());
  20720. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  20721. /**
  20722. * Represents a scene to be rendered by the engine.
  20723. * @see http://doc.babylonjs.com/page.php?p=21911
  20724. */
  20725. var Scene = /** @class */ (function () {
  20726. /**
  20727. * @constructor
  20728. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  20729. */
  20730. function Scene(engine) {
  20731. // Members
  20732. this.autoClear = true;
  20733. this.autoClearDepthAndStencil = true;
  20734. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  20735. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  20736. this.forceWireframe = false;
  20737. this._forcePointsCloud = false;
  20738. this.forceShowBoundingBoxes = false;
  20739. this.animationsEnabled = true;
  20740. this.useConstantAnimationDeltaTime = false;
  20741. this.constantlyUpdateMeshUnderPointer = false;
  20742. this.hoverCursor = "pointer";
  20743. this.defaultCursor = "";
  20744. /**
  20745. * This is used to call preventDefault() on pointer down
  20746. * in order to block unwanted artifacts like system double clicks
  20747. */
  20748. this.preventDefaultOnPointerDown = true;
  20749. // Metadata
  20750. this.metadata = null;
  20751. /**
  20752. * An event triggered when the scene is disposed.
  20753. * @type {BABYLON.Observable}
  20754. */
  20755. this.onDisposeObservable = new BABYLON.Observable();
  20756. /**
  20757. * An event triggered before rendering the scene (right after animations and physics)
  20758. * @type {BABYLON.Observable}
  20759. */
  20760. this.onBeforeRenderObservable = new BABYLON.Observable();
  20761. /**
  20762. * An event triggered after rendering the scene
  20763. * @type {BABYLON.Observable}
  20764. */
  20765. this.onAfterRenderObservable = new BABYLON.Observable();
  20766. /**
  20767. * An event triggered before animating the scene
  20768. * @type {BABYLON.Observable}
  20769. */
  20770. this.onBeforeAnimationsObservable = new BABYLON.Observable();
  20771. /**
  20772. * An event triggered after animations processing
  20773. * @type {BABYLON.Observable}
  20774. */
  20775. this.onAfterAnimationsObservable = new BABYLON.Observable();
  20776. /**
  20777. * An event triggered before draw calls are ready to be sent
  20778. * @type {BABYLON.Observable}
  20779. */
  20780. this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  20781. /**
  20782. * An event triggered after draw calls have been sent
  20783. * @type {BABYLON.Observable}
  20784. */
  20785. this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  20786. /**
  20787. * An event triggered when physic simulation is about to be run
  20788. * @type {BABYLON.Observable}
  20789. */
  20790. this.onBeforePhysicsObservable = new BABYLON.Observable();
  20791. /**
  20792. * An event triggered when physic simulation has been done
  20793. * @type {BABYLON.Observable}
  20794. */
  20795. this.onAfterPhysicsObservable = new BABYLON.Observable();
  20796. /**
  20797. * An event triggered when the scene is ready
  20798. * @type {BABYLON.Observable}
  20799. */
  20800. this.onReadyObservable = new BABYLON.Observable();
  20801. /**
  20802. * An event triggered before rendering a camera
  20803. * @type {BABYLON.Observable}
  20804. */
  20805. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  20806. /**
  20807. * An event triggered after rendering a camera
  20808. * @type {BABYLON.Observable}
  20809. */
  20810. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  20811. /**
  20812. * An event triggered when active meshes evaluation is about to start
  20813. * @type {BABYLON.Observable}
  20814. */
  20815. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  20816. /**
  20817. * An event triggered when active meshes evaluation is done
  20818. * @type {BABYLON.Observable}
  20819. */
  20820. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  20821. /**
  20822. * An event triggered when particles rendering is about to start
  20823. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  20824. * @type {BABYLON.Observable}
  20825. */
  20826. this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  20827. /**
  20828. * An event triggered when particles rendering is done
  20829. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  20830. * @type {BABYLON.Observable}
  20831. */
  20832. this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  20833. /**
  20834. * An event triggered when sprites rendering is about to start
  20835. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  20836. * @type {BABYLON.Observable}
  20837. */
  20838. this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  20839. /**
  20840. * An event triggered when sprites rendering is done
  20841. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  20842. * @type {BABYLON.Observable}
  20843. */
  20844. this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  20845. /**
  20846. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  20847. * @type {BABYLON.Observable}
  20848. */
  20849. this.onDataLoadedObservable = new BABYLON.Observable();
  20850. /**
  20851. * An event triggered when a camera is created
  20852. * @type {BABYLON.Observable}
  20853. */
  20854. this.onNewCameraAddedObservable = new BABYLON.Observable();
  20855. /**
  20856. * An event triggered when a camera is removed
  20857. * @type {BABYLON.Observable}
  20858. */
  20859. this.onCameraRemovedObservable = new BABYLON.Observable();
  20860. /**
  20861. * An event triggered when a light is created
  20862. * @type {BABYLON.Observable}
  20863. */
  20864. this.onNewLightAddedObservable = new BABYLON.Observable();
  20865. /**
  20866. * An event triggered when a light is removed
  20867. * @type {BABYLON.Observable}
  20868. */
  20869. this.onLightRemovedObservable = new BABYLON.Observable();
  20870. /**
  20871. * An event triggered when a geometry is created
  20872. * @type {BABYLON.Observable}
  20873. */
  20874. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  20875. /**
  20876. * An event triggered when a geometry is removed
  20877. * @type {BABYLON.Observable}
  20878. */
  20879. this.onGeometryRemovedObservable = new BABYLON.Observable();
  20880. /**
  20881. * An event triggered when a transform node is created
  20882. * @type {BABYLON.Observable}
  20883. */
  20884. this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  20885. /**
  20886. * An event triggered when a transform node is removed
  20887. * @type {BABYLON.Observable}
  20888. */
  20889. this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  20890. /**
  20891. * An event triggered when a mesh is created
  20892. * @type {BABYLON.Observable}
  20893. */
  20894. this.onNewMeshAddedObservable = new BABYLON.Observable();
  20895. /**
  20896. * An event triggered when a mesh is removed
  20897. * @type {BABYLON.Observable}
  20898. */
  20899. this.onMeshRemovedObservable = new BABYLON.Observable();
  20900. /**
  20901. * An event triggered when render targets are about to be rendered
  20902. * Can happen multiple times per frame.
  20903. * @type {BABYLON.Observable}
  20904. */
  20905. this.OnBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  20906. /**
  20907. * An event triggered when render targets were rendered.
  20908. * Can happen multiple times per frame.
  20909. * @type {BABYLON.Observable}
  20910. */
  20911. this.OnAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  20912. /**
  20913. * An event triggered before calculating deterministic simulation step
  20914. * @type {BABYLON.Observable}
  20915. */
  20916. this.onBeforeStepObservable = new BABYLON.Observable();
  20917. /**
  20918. * An event triggered after calculating deterministic simulation step
  20919. * @type {BABYLON.Observable}
  20920. */
  20921. this.onAfterStepObservable = new BABYLON.Observable();
  20922. /**
  20923. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  20924. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  20925. * 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)
  20926. */
  20927. this.onRenderingGroupObservable = new BABYLON.Observable();
  20928. // Animations
  20929. this.animations = [];
  20930. /**
  20931. * 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).
  20932. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  20933. */
  20934. this.onPrePointerObservable = new BABYLON.Observable();
  20935. /**
  20936. * Observable event triggered each time an input event is received from the rendering canvas
  20937. */
  20938. this.onPointerObservable = new BABYLON.Observable();
  20939. this._meshPickProceed = false;
  20940. this._currentPickResult = null;
  20941. this._previousPickResult = null;
  20942. this._totalPointersPressed = 0;
  20943. this._doubleClickOccured = false;
  20944. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  20945. this.cameraToUseForPointers = null;
  20946. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  20947. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  20948. this._startingPointerTime = 0;
  20949. this._previousStartingPointerTime = 0;
  20950. // Deterministic lockstep
  20951. this._timeAccumulator = 0;
  20952. this._currentStepId = 0;
  20953. this._currentInternalStep = 0;
  20954. // Keyboard
  20955. /**
  20956. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  20957. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  20958. */
  20959. this.onPreKeyboardObservable = new BABYLON.Observable();
  20960. /**
  20961. * Observable event triggered each time an keyboard event is received from the hosting window
  20962. */
  20963. this.onKeyboardObservable = new BABYLON.Observable();
  20964. // Coordinate system
  20965. /**
  20966. * use right-handed coordinate system on this scene.
  20967. * @type {boolean}
  20968. */
  20969. this._useRightHandedSystem = false;
  20970. // Fog
  20971. this._fogEnabled = true;
  20972. this._fogMode = Scene.FOGMODE_NONE;
  20973. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  20974. this.fogDensity = 0.1;
  20975. this.fogStart = 0;
  20976. this.fogEnd = 1000.0;
  20977. // Lights
  20978. /**
  20979. * is shadow enabled on this scene.
  20980. * @type {boolean}
  20981. */
  20982. this._shadowsEnabled = true;
  20983. /**
  20984. * is light enabled on this scene.
  20985. * @type {boolean}
  20986. */
  20987. this._lightsEnabled = true;
  20988. /**
  20989. * All of the lights added to this scene.
  20990. * @see BABYLON.Light
  20991. * @type {BABYLON.Light[]}
  20992. */
  20993. this.lights = new Array();
  20994. // Cameras
  20995. /** All of the cameras added to this scene. */
  20996. this.cameras = new Array();
  20997. /** All of the active cameras added to this scene. */
  20998. this.activeCameras = new Array();
  20999. // Meshes
  21000. /**
  21001. * All of the tranform nodes added to this scene.
  21002. * @see BABYLON.TransformNode
  21003. * @type {BABYLON.TransformNode[]}
  21004. */
  21005. this.transformNodes = new Array();
  21006. /**
  21007. * All of the (abstract) meshes added to this scene.
  21008. * @see BABYLON.AbstractMesh
  21009. * @type {BABYLON.AbstractMesh[]}
  21010. */
  21011. this.meshes = new Array();
  21012. /**
  21013. * All of the animation groups added to this scene.
  21014. * @see BABYLON.AnimationGroup
  21015. * @type {BABYLON.AnimationGroup[]}
  21016. */
  21017. this.animationGroups = new Array();
  21018. // Geometries
  21019. this._geometries = new Array();
  21020. this.materials = new Array();
  21021. this.multiMaterials = new Array();
  21022. // Textures
  21023. this._texturesEnabled = true;
  21024. this.textures = new Array();
  21025. // Particles
  21026. this.particlesEnabled = true;
  21027. this.particleSystems = new Array();
  21028. // Sprites
  21029. this.spritesEnabled = true;
  21030. this.spriteManagers = new Array();
  21031. /**
  21032. * The list of layers (background and foreground) of the scene.
  21033. */
  21034. this.layers = new Array();
  21035. /**
  21036. * The list of effect layers (highlights/glow) contained in the scene.
  21037. */
  21038. this.effectLayers = new Array();
  21039. // Skeletons
  21040. this._skeletonsEnabled = true;
  21041. this.skeletons = new Array();
  21042. // Morph targets
  21043. this.morphTargetManagers = new Array();
  21044. // Lens flares
  21045. this.lensFlaresEnabled = true;
  21046. this.lensFlareSystems = new Array();
  21047. // Collisions
  21048. this.collisionsEnabled = true;
  21049. /** Defines the gravity applied to this scene */
  21050. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  21051. // Postprocesses
  21052. this.postProcesses = new Array();
  21053. this.postProcessesEnabled = true;
  21054. // Customs render targets
  21055. this.renderTargetsEnabled = true;
  21056. this.dumpNextRenderTargets = false;
  21057. this.customRenderTargets = new Array();
  21058. // Imported meshes
  21059. this.importedMeshesFiles = new Array();
  21060. // Probes
  21061. this.probesEnabled = true;
  21062. this.reflectionProbes = new Array();
  21063. this._actionManagers = new Array();
  21064. this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  21065. // Procedural textures
  21066. this.proceduralTexturesEnabled = true;
  21067. this._proceduralTextures = new Array();
  21068. this.soundTracks = new Array();
  21069. this._audioEnabled = true;
  21070. this._headphone = false;
  21071. // Performance counters
  21072. this._totalVertices = new BABYLON.PerfCounter();
  21073. this._activeIndices = new BABYLON.PerfCounter();
  21074. this._activeParticles = new BABYLON.PerfCounter();
  21075. this._activeBones = new BABYLON.PerfCounter();
  21076. this._animationTime = 0;
  21077. this.animationTimeScale = 1;
  21078. this._renderId = 0;
  21079. this._executeWhenReadyTimeoutId = -1;
  21080. this._intermediateRendering = false;
  21081. this._viewUpdateFlag = -1;
  21082. this._projectionUpdateFlag = -1;
  21083. this._alternateViewUpdateFlag = -1;
  21084. this._alternateProjectionUpdateFlag = -1;
  21085. this._toBeDisposed = new BABYLON.SmartArray(256);
  21086. this._activeRequests = new Array();
  21087. this._pendingData = new Array();
  21088. this._isDisposed = false;
  21089. this.dispatchAllSubMeshesOfActiveMeshes = false;
  21090. this._activeMeshes = new BABYLON.SmartArray(256);
  21091. this._processedMaterials = new BABYLON.SmartArray(256);
  21092. this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  21093. this._activeParticleSystems = new BABYLON.SmartArray(256);
  21094. this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  21095. this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  21096. this._activeAnimatables = new Array();
  21097. this._transformMatrix = BABYLON.Matrix.Zero();
  21098. this._useAlternateCameraConfiguration = false;
  21099. this._alternateRendering = false;
  21100. this.requireLightSorting = false;
  21101. this._activeMeshesFrozen = false;
  21102. this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  21103. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  21104. this._engine.scenes.push(this);
  21105. this._uid = null;
  21106. this._renderingManager = new BABYLON.RenderingManager(this);
  21107. this.postProcessManager = new BABYLON.PostProcessManager(this);
  21108. if (BABYLON.OutlineRenderer) {
  21109. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  21110. }
  21111. if (BABYLON.Tools.IsWindowObjectExist()) {
  21112. this.attachControl();
  21113. }
  21114. //simplification queue
  21115. if (BABYLON.SimplificationQueue) {
  21116. this.simplificationQueue = new BABYLON.SimplificationQueue();
  21117. }
  21118. //collision coordinator initialization. For now legacy per default.
  21119. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  21120. // Uniform Buffer
  21121. this._createUbo();
  21122. // Default Image processing definition.
  21123. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  21124. }
  21125. Object.defineProperty(Scene, "FOGMODE_NONE", {
  21126. /** The fog is deactivated */
  21127. get: function () {
  21128. return Scene._FOGMODE_NONE;
  21129. },
  21130. enumerable: true,
  21131. configurable: true
  21132. });
  21133. Object.defineProperty(Scene, "FOGMODE_EXP", {
  21134. /** The fog density is following an exponential function */
  21135. get: function () {
  21136. return Scene._FOGMODE_EXP;
  21137. },
  21138. enumerable: true,
  21139. configurable: true
  21140. });
  21141. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  21142. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  21143. get: function () {
  21144. return Scene._FOGMODE_EXP2;
  21145. },
  21146. enumerable: true,
  21147. configurable: true
  21148. });
  21149. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  21150. /** The fog density is following a linear function. */
  21151. get: function () {
  21152. return Scene._FOGMODE_LINEAR;
  21153. },
  21154. enumerable: true,
  21155. configurable: true
  21156. });
  21157. Object.defineProperty(Scene.prototype, "environmentTexture", {
  21158. /**
  21159. * Texture used in all pbr material as the reflection texture.
  21160. * As in the majority of the scene they are the same (exception for multi room and so on),
  21161. * this is easier to reference from here than from all the materials.
  21162. */
  21163. get: function () {
  21164. return this._environmentTexture;
  21165. },
  21166. /**
  21167. * Texture used in all pbr material as the reflection texture.
  21168. * As in the majority of the scene they are the same (exception for multi room and so on),
  21169. * this is easier to set here than in all the materials.
  21170. */
  21171. set: function (value) {
  21172. if (this._environmentTexture === value) {
  21173. return;
  21174. }
  21175. this._environmentTexture = value;
  21176. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  21177. },
  21178. enumerable: true,
  21179. configurable: true
  21180. });
  21181. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  21182. /**
  21183. * Default image processing configuration used either in the rendering
  21184. * Forward main pass or through the imageProcessingPostProcess if present.
  21185. * As in the majority of the scene they are the same (exception for multi camera),
  21186. * this is easier to reference from here than from all the materials and post process.
  21187. *
  21188. * No setter as we it is a shared configuration, you can set the values instead.
  21189. */
  21190. get: function () {
  21191. return this._imageProcessingConfiguration;
  21192. },
  21193. enumerable: true,
  21194. configurable: true
  21195. });
  21196. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  21197. get: function () {
  21198. return this._forcePointsCloud;
  21199. },
  21200. set: function (value) {
  21201. if (this._forcePointsCloud === value) {
  21202. return;
  21203. }
  21204. this._forcePointsCloud = value;
  21205. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  21206. },
  21207. enumerable: true,
  21208. configurable: true
  21209. });
  21210. Object.defineProperty(Scene.prototype, "onDispose", {
  21211. /** A function to be executed when this scene is disposed. */
  21212. set: function (callback) {
  21213. if (this._onDisposeObserver) {
  21214. this.onDisposeObservable.remove(this._onDisposeObserver);
  21215. }
  21216. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  21217. },
  21218. enumerable: true,
  21219. configurable: true
  21220. });
  21221. Object.defineProperty(Scene.prototype, "beforeRender", {
  21222. /** A function to be executed before rendering this scene */
  21223. set: function (callback) {
  21224. if (this._onBeforeRenderObserver) {
  21225. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  21226. }
  21227. if (callback) {
  21228. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  21229. }
  21230. },
  21231. enumerable: true,
  21232. configurable: true
  21233. });
  21234. Object.defineProperty(Scene.prototype, "afterRender", {
  21235. /** A function to be executed after rendering this scene */
  21236. set: function (callback) {
  21237. if (this._onAfterRenderObserver) {
  21238. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  21239. }
  21240. if (callback) {
  21241. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  21242. }
  21243. },
  21244. enumerable: true,
  21245. configurable: true
  21246. });
  21247. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  21248. set: function (callback) {
  21249. if (this._onBeforeCameraRenderObserver) {
  21250. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  21251. }
  21252. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  21253. },
  21254. enumerable: true,
  21255. configurable: true
  21256. });
  21257. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  21258. set: function (callback) {
  21259. if (this._onAfterCameraRenderObserver) {
  21260. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  21261. }
  21262. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  21263. },
  21264. enumerable: true,
  21265. configurable: true
  21266. });
  21267. Object.defineProperty(Scene.prototype, "gamepadManager", {
  21268. get: function () {
  21269. if (!this._gamepadManager) {
  21270. this._gamepadManager = new BABYLON.GamepadManager(this);
  21271. }
  21272. return this._gamepadManager;
  21273. },
  21274. enumerable: true,
  21275. configurable: true
  21276. });
  21277. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  21278. get: function () {
  21279. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  21280. },
  21281. enumerable: true,
  21282. configurable: true
  21283. });
  21284. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  21285. get: function () {
  21286. return this._useRightHandedSystem;
  21287. },
  21288. set: function (value) {
  21289. if (this._useRightHandedSystem === value) {
  21290. return;
  21291. }
  21292. this._useRightHandedSystem = value;
  21293. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  21294. },
  21295. enumerable: true,
  21296. configurable: true
  21297. });
  21298. Scene.prototype.setStepId = function (newStepId) {
  21299. this._currentStepId = newStepId;
  21300. };
  21301. ;
  21302. Scene.prototype.getStepId = function () {
  21303. return this._currentStepId;
  21304. };
  21305. ;
  21306. Scene.prototype.getInternalStep = function () {
  21307. return this._currentInternalStep;
  21308. };
  21309. ;
  21310. Object.defineProperty(Scene.prototype, "fogEnabled", {
  21311. get: function () {
  21312. return this._fogEnabled;
  21313. },
  21314. /**
  21315. * is fog enabled on this scene.
  21316. */
  21317. set: function (value) {
  21318. if (this._fogEnabled === value) {
  21319. return;
  21320. }
  21321. this._fogEnabled = value;
  21322. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  21323. },
  21324. enumerable: true,
  21325. configurable: true
  21326. });
  21327. Object.defineProperty(Scene.prototype, "fogMode", {
  21328. get: function () {
  21329. return this._fogMode;
  21330. },
  21331. set: function (value) {
  21332. if (this._fogMode === value) {
  21333. return;
  21334. }
  21335. this._fogMode = value;
  21336. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  21337. },
  21338. enumerable: true,
  21339. configurable: true
  21340. });
  21341. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  21342. get: function () {
  21343. return this._shadowsEnabled;
  21344. },
  21345. set: function (value) {
  21346. if (this._shadowsEnabled === value) {
  21347. return;
  21348. }
  21349. this._shadowsEnabled = value;
  21350. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  21351. },
  21352. enumerable: true,
  21353. configurable: true
  21354. });
  21355. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  21356. get: function () {
  21357. return this._lightsEnabled;
  21358. },
  21359. set: function (value) {
  21360. if (this._lightsEnabled === value) {
  21361. return;
  21362. }
  21363. this._lightsEnabled = value;
  21364. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  21365. },
  21366. enumerable: true,
  21367. configurable: true
  21368. });
  21369. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  21370. /** The default material used on meshes when no material is affected */
  21371. get: function () {
  21372. if (!this._defaultMaterial) {
  21373. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  21374. }
  21375. return this._defaultMaterial;
  21376. },
  21377. /** The default material used on meshes when no material is affected */
  21378. set: function (value) {
  21379. this._defaultMaterial = value;
  21380. },
  21381. enumerable: true,
  21382. configurable: true
  21383. });
  21384. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  21385. get: function () {
  21386. return this._texturesEnabled;
  21387. },
  21388. set: function (value) {
  21389. if (this._texturesEnabled === value) {
  21390. return;
  21391. }
  21392. this._texturesEnabled = value;
  21393. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  21394. },
  21395. enumerable: true,
  21396. configurable: true
  21397. });
  21398. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  21399. get: function () {
  21400. return this._skeletonsEnabled;
  21401. },
  21402. set: function (value) {
  21403. if (this._skeletonsEnabled === value) {
  21404. return;
  21405. }
  21406. this._skeletonsEnabled = value;
  21407. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  21408. },
  21409. enumerable: true,
  21410. configurable: true
  21411. });
  21412. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  21413. get: function () {
  21414. if (!this._postProcessRenderPipelineManager) {
  21415. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  21416. }
  21417. return this._postProcessRenderPipelineManager;
  21418. },
  21419. enumerable: true,
  21420. configurable: true
  21421. });
  21422. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  21423. get: function () {
  21424. if (!this._mainSoundTrack) {
  21425. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  21426. }
  21427. return this._mainSoundTrack;
  21428. },
  21429. enumerable: true,
  21430. configurable: true
  21431. });
  21432. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  21433. get: function () {
  21434. return this._alternateRendering;
  21435. },
  21436. enumerable: true,
  21437. configurable: true
  21438. });
  21439. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  21440. get: function () {
  21441. return this._frustumPlanes;
  21442. },
  21443. enumerable: true,
  21444. configurable: true
  21445. });
  21446. Object.defineProperty(Scene.prototype, "geometryBufferRenderer", {
  21447. /**
  21448. * Gets the current geometry buffer associated to the scene.
  21449. */
  21450. get: function () {
  21451. return this._geometryBufferRenderer;
  21452. },
  21453. /**
  21454. * Sets the current geometry buffer for the scene.
  21455. */
  21456. set: function (geometryBufferRenderer) {
  21457. if (geometryBufferRenderer && geometryBufferRenderer.isSupported) {
  21458. this._geometryBufferRenderer = geometryBufferRenderer;
  21459. }
  21460. },
  21461. enumerable: true,
  21462. configurable: true
  21463. });
  21464. Object.defineProperty(Scene.prototype, "debugLayer", {
  21465. // Properties
  21466. get: function () {
  21467. if (!this._debugLayer) {
  21468. this._debugLayer = new BABYLON.DebugLayer(this);
  21469. }
  21470. return this._debugLayer;
  21471. },
  21472. enumerable: true,
  21473. configurable: true
  21474. });
  21475. Object.defineProperty(Scene.prototype, "workerCollisions", {
  21476. get: function () {
  21477. return this._workerCollisions;
  21478. },
  21479. set: function (enabled) {
  21480. if (!BABYLON.CollisionCoordinatorLegacy) {
  21481. return;
  21482. }
  21483. enabled = (enabled && !!Worker);
  21484. this._workerCollisions = enabled;
  21485. if (this.collisionCoordinator) {
  21486. this.collisionCoordinator.destroy();
  21487. }
  21488. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  21489. this.collisionCoordinator.init(this);
  21490. },
  21491. enumerable: true,
  21492. configurable: true
  21493. });
  21494. Object.defineProperty(Scene.prototype, "selectionOctree", {
  21495. get: function () {
  21496. return this._selectionOctree;
  21497. },
  21498. enumerable: true,
  21499. configurable: true
  21500. });
  21501. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  21502. /**
  21503. * The mesh that is currently under the pointer.
  21504. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  21505. */
  21506. get: function () {
  21507. return this._pointerOverMesh;
  21508. },
  21509. enumerable: true,
  21510. configurable: true
  21511. });
  21512. Object.defineProperty(Scene.prototype, "pointerX", {
  21513. /**
  21514. * Current on-screen X position of the pointer
  21515. * @return {number} X position of the pointer
  21516. */
  21517. get: function () {
  21518. return this._pointerX;
  21519. },
  21520. enumerable: true,
  21521. configurable: true
  21522. });
  21523. Object.defineProperty(Scene.prototype, "pointerY", {
  21524. /**
  21525. * Current on-screen Y position of the pointer
  21526. * @return {number} Y position of the pointer
  21527. */
  21528. get: function () {
  21529. return this._pointerY;
  21530. },
  21531. enumerable: true,
  21532. configurable: true
  21533. });
  21534. Scene.prototype.getCachedMaterial = function () {
  21535. return this._cachedMaterial;
  21536. };
  21537. Scene.prototype.getCachedEffect = function () {
  21538. return this._cachedEffect;
  21539. };
  21540. Scene.prototype.getCachedVisibility = function () {
  21541. return this._cachedVisibility;
  21542. };
  21543. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  21544. if (visibility === void 0) { visibility = 1; }
  21545. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  21546. };
  21547. Scene.prototype.getBoundingBoxRenderer = function () {
  21548. if (!this._boundingBoxRenderer) {
  21549. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  21550. }
  21551. return this._boundingBoxRenderer;
  21552. };
  21553. Scene.prototype.getOutlineRenderer = function () {
  21554. return this._outlineRenderer;
  21555. };
  21556. Scene.prototype.getEngine = function () {
  21557. return this._engine;
  21558. };
  21559. Scene.prototype.getTotalVertices = function () {
  21560. return this._totalVertices.current;
  21561. };
  21562. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  21563. get: function () {
  21564. return this._totalVertices;
  21565. },
  21566. enumerable: true,
  21567. configurable: true
  21568. });
  21569. Scene.prototype.getActiveIndices = function () {
  21570. return this._activeIndices.current;
  21571. };
  21572. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  21573. get: function () {
  21574. return this._activeIndices;
  21575. },
  21576. enumerable: true,
  21577. configurable: true
  21578. });
  21579. Scene.prototype.getActiveParticles = function () {
  21580. return this._activeParticles.current;
  21581. };
  21582. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  21583. get: function () {
  21584. return this._activeParticles;
  21585. },
  21586. enumerable: true,
  21587. configurable: true
  21588. });
  21589. Scene.prototype.getActiveBones = function () {
  21590. return this._activeBones.current;
  21591. };
  21592. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  21593. get: function () {
  21594. return this._activeBones;
  21595. },
  21596. enumerable: true,
  21597. configurable: true
  21598. });
  21599. // Stats
  21600. Scene.prototype.getInterFramePerfCounter = function () {
  21601. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  21602. return 0;
  21603. };
  21604. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  21605. get: function () {
  21606. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  21607. return null;
  21608. },
  21609. enumerable: true,
  21610. configurable: true
  21611. });
  21612. Scene.prototype.getLastFrameDuration = function () {
  21613. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  21614. return 0;
  21615. };
  21616. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  21617. get: function () {
  21618. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  21619. return null;
  21620. },
  21621. enumerable: true,
  21622. configurable: true
  21623. });
  21624. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  21625. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  21626. return 0;
  21627. };
  21628. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  21629. get: function () {
  21630. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  21631. return null;
  21632. },
  21633. enumerable: true,
  21634. configurable: true
  21635. });
  21636. Scene.prototype.getActiveMeshes = function () {
  21637. return this._activeMeshes;
  21638. };
  21639. Scene.prototype.getRenderTargetsDuration = function () {
  21640. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  21641. return 0;
  21642. };
  21643. Scene.prototype.getRenderDuration = function () {
  21644. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  21645. return 0;
  21646. };
  21647. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  21648. get: function () {
  21649. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  21650. return null;
  21651. },
  21652. enumerable: true,
  21653. configurable: true
  21654. });
  21655. Scene.prototype.getParticlesDuration = function () {
  21656. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  21657. return 0;
  21658. };
  21659. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  21660. get: function () {
  21661. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  21662. return null;
  21663. },
  21664. enumerable: true,
  21665. configurable: true
  21666. });
  21667. Scene.prototype.getSpritesDuration = function () {
  21668. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  21669. return 0;
  21670. };
  21671. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  21672. get: function () {
  21673. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  21674. return null;
  21675. },
  21676. enumerable: true,
  21677. configurable: true
  21678. });
  21679. Scene.prototype.getAnimationRatio = function () {
  21680. return this._animationRatio;
  21681. };
  21682. Scene.prototype.getRenderId = function () {
  21683. return this._renderId;
  21684. };
  21685. Scene.prototype.incrementRenderId = function () {
  21686. this._renderId++;
  21687. };
  21688. Scene.prototype._updatePointerPosition = function (evt) {
  21689. var canvasRect = this._engine.getRenderingCanvasClientRect();
  21690. if (!canvasRect) {
  21691. return;
  21692. }
  21693. this._pointerX = evt.clientX - canvasRect.left;
  21694. this._pointerY = evt.clientY - canvasRect.top;
  21695. this._unTranslatedPointerX = this._pointerX;
  21696. this._unTranslatedPointerY = this._pointerY;
  21697. };
  21698. Scene.prototype._createUbo = function () {
  21699. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  21700. this._sceneUbo.addUniform("viewProjection", 16);
  21701. this._sceneUbo.addUniform("view", 16);
  21702. };
  21703. Scene.prototype._createAlternateUbo = function () {
  21704. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  21705. this._alternateSceneUbo.addUniform("viewProjection", 16);
  21706. this._alternateSceneUbo.addUniform("view", 16);
  21707. };
  21708. // Pointers handling
  21709. /**
  21710. * Use this method to simulate a pointer move on a mesh
  21711. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  21712. */
  21713. Scene.prototype.simulatePointerMove = function (pickResult) {
  21714. var evt = new PointerEvent("pointermove");
  21715. return this._processPointerMove(pickResult, evt);
  21716. };
  21717. Scene.prototype._processPointerMove = function (pickResult, evt) {
  21718. var canvas = this._engine.getRenderingCanvas();
  21719. if (!canvas) {
  21720. return this;
  21721. }
  21722. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  21723. this.setPointerOverSprite(null);
  21724. this.setPointerOverMesh(pickResult.pickedMesh);
  21725. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  21726. if (this._pointerOverMesh.actionManager.hoverCursor) {
  21727. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  21728. }
  21729. else {
  21730. canvas.style.cursor = this.hoverCursor;
  21731. }
  21732. }
  21733. else {
  21734. canvas.style.cursor = this.defaultCursor;
  21735. }
  21736. }
  21737. else {
  21738. this.setPointerOverMesh(null);
  21739. // Sprites
  21740. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  21741. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  21742. this.setPointerOverSprite(pickResult.pickedSprite);
  21743. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  21744. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  21745. }
  21746. else {
  21747. canvas.style.cursor = this.hoverCursor;
  21748. }
  21749. }
  21750. else {
  21751. this.setPointerOverSprite(null);
  21752. // Restore pointer
  21753. canvas.style.cursor = this.defaultCursor;
  21754. }
  21755. }
  21756. if (pickResult) {
  21757. if (this.onPointerMove) {
  21758. this.onPointerMove(evt, pickResult);
  21759. }
  21760. if (this.onPointerObservable.hasObservers()) {
  21761. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  21762. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  21763. this.onPointerObservable.notifyObservers(pi, type);
  21764. }
  21765. }
  21766. return this;
  21767. };
  21768. /**
  21769. * Use this method to simulate a pointer down on a mesh
  21770. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  21771. */
  21772. Scene.prototype.simulatePointerDown = function (pickResult) {
  21773. var evt = new PointerEvent("pointerdown");
  21774. return this._processPointerDown(pickResult, evt);
  21775. };
  21776. Scene.prototype._processPointerDown = function (pickResult, evt) {
  21777. var _this = this;
  21778. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  21779. this._pickedDownMesh = pickResult.pickedMesh;
  21780. var actionManager = pickResult.pickedMesh.actionManager;
  21781. if (actionManager) {
  21782. if (actionManager.hasPickTriggers) {
  21783. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  21784. switch (evt.button) {
  21785. case 0:
  21786. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  21787. break;
  21788. case 1:
  21789. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  21790. break;
  21791. case 2:
  21792. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  21793. break;
  21794. }
  21795. }
  21796. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  21797. window.setTimeout(function () {
  21798. 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);
  21799. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  21800. if (_this._totalPointersPressed !== 0 &&
  21801. ((new Date().getTime() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  21802. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  21803. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  21804. _this._startingPointerTime = 0;
  21805. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  21806. }
  21807. }
  21808. }, Scene.LongPressDelay);
  21809. }
  21810. }
  21811. }
  21812. if (pickResult) {
  21813. if (this.onPointerDown) {
  21814. this.onPointerDown(evt, pickResult);
  21815. }
  21816. if (this.onPointerObservable.hasObservers()) {
  21817. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  21818. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  21819. this.onPointerObservable.notifyObservers(pi, type);
  21820. }
  21821. }
  21822. return this;
  21823. };
  21824. /**
  21825. * Use this method to simulate a pointer up on a mesh
  21826. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  21827. */
  21828. Scene.prototype.simulatePointerUp = function (pickResult) {
  21829. var evt = new PointerEvent("pointerup");
  21830. var clickInfo = new ClickInfo();
  21831. clickInfo.singleClick = true;
  21832. clickInfo.ignore = true;
  21833. return this._processPointerUp(pickResult, evt, clickInfo);
  21834. };
  21835. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  21836. if (pickResult && pickResult && pickResult.pickedMesh) {
  21837. this._pickedUpMesh = pickResult.pickedMesh;
  21838. if (this._pickedDownMesh === this._pickedUpMesh) {
  21839. if (this.onPointerPick) {
  21840. this.onPointerPick(evt, pickResult);
  21841. }
  21842. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  21843. var type = BABYLON.PointerEventTypes.POINTERPICK;
  21844. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  21845. this.onPointerObservable.notifyObservers(pi, type);
  21846. }
  21847. }
  21848. if (pickResult.pickedMesh.actionManager) {
  21849. if (clickInfo.ignore) {
  21850. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  21851. }
  21852. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  21853. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  21854. }
  21855. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  21856. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  21857. }
  21858. }
  21859. }
  21860. if (this._pickedDownMesh &&
  21861. this._pickedDownMesh.actionManager &&
  21862. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  21863. this._pickedDownMesh !== this._pickedUpMesh) {
  21864. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  21865. }
  21866. if (this.onPointerUp) {
  21867. this.onPointerUp(evt, pickResult);
  21868. }
  21869. if (this.onPointerObservable.hasObservers()) {
  21870. if (!clickInfo.ignore) {
  21871. if (!clickInfo.hasSwiped) {
  21872. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  21873. var type = BABYLON.PointerEventTypes.POINTERTAP;
  21874. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  21875. this.onPointerObservable.notifyObservers(pi, type);
  21876. }
  21877. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  21878. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  21879. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  21880. this.onPointerObservable.notifyObservers(pi, type);
  21881. }
  21882. }
  21883. }
  21884. else {
  21885. var type = BABYLON.PointerEventTypes.POINTERUP;
  21886. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  21887. this.onPointerObservable.notifyObservers(pi, type);
  21888. }
  21889. }
  21890. return this;
  21891. };
  21892. /**
  21893. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  21894. * @param attachUp defines if you want to attach events to pointerup
  21895. * @param attachDown defines if you want to attach events to pointerdown
  21896. * @param attachMove defines if you want to attach events to pointermove
  21897. */
  21898. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  21899. var _this = this;
  21900. if (attachUp === void 0) { attachUp = true; }
  21901. if (attachDown === void 0) { attachDown = true; }
  21902. if (attachMove === void 0) { attachMove = true; }
  21903. this._initActionManager = function (act, clickInfo) {
  21904. if (!_this._meshPickProceed) {
  21905. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  21906. _this._currentPickResult = pickResult;
  21907. if (pickResult) {
  21908. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  21909. }
  21910. _this._meshPickProceed = true;
  21911. }
  21912. return act;
  21913. };
  21914. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  21915. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  21916. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  21917. btn !== _this._previousButtonPressed) {
  21918. _this._doubleClickOccured = false;
  21919. clickInfo.singleClick = true;
  21920. clickInfo.ignore = false;
  21921. cb(clickInfo, _this._currentPickResult);
  21922. }
  21923. };
  21924. this._initClickEvent = function (obs1, obs2, evt, cb) {
  21925. var clickInfo = new ClickInfo();
  21926. _this._currentPickResult = null;
  21927. var act = null;
  21928. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  21929. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  21930. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  21931. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  21932. act = _this._initActionManager(act, clickInfo);
  21933. if (act)
  21934. checkPicking = act.hasPickTriggers;
  21935. }
  21936. if (checkPicking) {
  21937. var btn = evt.button;
  21938. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  21939. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  21940. if (!clickInfo.hasSwiped) {
  21941. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  21942. if (!checkSingleClickImmediately) {
  21943. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  21944. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  21945. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  21946. act = _this._initActionManager(act, clickInfo);
  21947. if (act)
  21948. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  21949. }
  21950. }
  21951. if (checkSingleClickImmediately) {
  21952. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  21953. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  21954. btn !== _this._previousButtonPressed) {
  21955. clickInfo.singleClick = true;
  21956. cb(clickInfo, _this._currentPickResult);
  21957. }
  21958. }
  21959. else {
  21960. // wait that no double click has been raised during the double click delay
  21961. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  21962. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  21963. }
  21964. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  21965. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  21966. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  21967. act = _this._initActionManager(act, clickInfo);
  21968. if (act)
  21969. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  21970. }
  21971. if (checkDoubleClick) {
  21972. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  21973. if (btn === _this._previousButtonPressed &&
  21974. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  21975. !_this._doubleClickOccured) {
  21976. // pointer has not moved for 2 clicks, it's a double click
  21977. if (!clickInfo.hasSwiped &&
  21978. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  21979. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  21980. _this._previousStartingPointerTime = 0;
  21981. _this._doubleClickOccured = true;
  21982. clickInfo.doubleClick = true;
  21983. clickInfo.ignore = false;
  21984. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  21985. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  21986. }
  21987. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  21988. cb(clickInfo, _this._currentPickResult);
  21989. }
  21990. else {
  21991. _this._doubleClickOccured = false;
  21992. _this._previousStartingPointerTime = _this._startingPointerTime;
  21993. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  21994. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  21995. _this._previousButtonPressed = btn;
  21996. if (Scene.ExclusiveDoubleClickMode) {
  21997. if (_this._previousDelayedSimpleClickTimeout) {
  21998. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  21999. }
  22000. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  22001. cb(clickInfo, _this._previousPickResult);
  22002. }
  22003. else {
  22004. cb(clickInfo, _this._currentPickResult);
  22005. }
  22006. }
  22007. }
  22008. else {
  22009. _this._doubleClickOccured = false;
  22010. _this._previousStartingPointerTime = _this._startingPointerTime;
  22011. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  22012. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  22013. _this._previousButtonPressed = btn;
  22014. }
  22015. }
  22016. }
  22017. }
  22018. clickInfo.ignore = true;
  22019. cb(clickInfo, _this._currentPickResult);
  22020. };
  22021. this._spritePredicate = function (sprite) {
  22022. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  22023. };
  22024. this._onPointerMove = function (evt) {
  22025. _this._updatePointerPosition(evt);
  22026. // PreObservable support
  22027. if (_this.onPrePointerObservable.hasObservers()) {
  22028. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  22029. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22030. _this.onPrePointerObservable.notifyObservers(pi, type);
  22031. if (pi.skipOnPointerObservable) {
  22032. return;
  22033. }
  22034. }
  22035. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  22036. return;
  22037. }
  22038. if (!_this.pointerMovePredicate) {
  22039. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  22040. }
  22041. // Meshes
  22042. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  22043. _this._processPointerMove(pickResult, evt);
  22044. };
  22045. this._onPointerDown = function (evt) {
  22046. _this._totalPointersPressed++;
  22047. _this._pickedDownMesh = null;
  22048. _this._meshPickProceed = false;
  22049. _this._updatePointerPosition(evt);
  22050. if (_this.preventDefaultOnPointerDown && canvas) {
  22051. evt.preventDefault();
  22052. canvas.focus();
  22053. }
  22054. // PreObservable support
  22055. if (_this.onPrePointerObservable.hasObservers()) {
  22056. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  22057. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22058. _this.onPrePointerObservable.notifyObservers(pi, type);
  22059. if (pi.skipOnPointerObservable) {
  22060. return;
  22061. }
  22062. }
  22063. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  22064. return;
  22065. }
  22066. _this._startingPointerPosition.x = _this._pointerX;
  22067. _this._startingPointerPosition.y = _this._pointerY;
  22068. _this._startingPointerTime = new Date().getTime();
  22069. if (!_this.pointerDownPredicate) {
  22070. _this.pointerDownPredicate = function (mesh) {
  22071. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  22072. };
  22073. }
  22074. // Meshes
  22075. _this._pickedDownMesh = null;
  22076. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  22077. _this._processPointerDown(pickResult, evt);
  22078. // Sprites
  22079. _this._pickedDownSprite = null;
  22080. if (_this.spriteManagers.length > 0) {
  22081. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  22082. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  22083. if (pickResult.pickedSprite.actionManager) {
  22084. _this._pickedDownSprite = pickResult.pickedSprite;
  22085. switch (evt.button) {
  22086. case 0:
  22087. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22088. break;
  22089. case 1:
  22090. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22091. break;
  22092. case 2:
  22093. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22094. break;
  22095. }
  22096. if (pickResult.pickedSprite.actionManager) {
  22097. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22098. }
  22099. }
  22100. }
  22101. }
  22102. };
  22103. this._onPointerUp = function (evt) {
  22104. if (_this._totalPointersPressed === 0) {
  22105. return; // So we need to test it the pointer down was pressed before.
  22106. }
  22107. _this._totalPointersPressed--;
  22108. _this._pickedUpMesh = null;
  22109. _this._meshPickProceed = false;
  22110. _this._updatePointerPosition(evt);
  22111. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  22112. // PreObservable support
  22113. if (_this.onPrePointerObservable.hasObservers()) {
  22114. if (!clickInfo.ignore) {
  22115. if (!clickInfo.hasSwiped) {
  22116. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  22117. var type = BABYLON.PointerEventTypes.POINTERTAP;
  22118. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22119. _this.onPrePointerObservable.notifyObservers(pi, type);
  22120. if (pi.skipOnPointerObservable) {
  22121. return;
  22122. }
  22123. }
  22124. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  22125. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  22126. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22127. _this.onPrePointerObservable.notifyObservers(pi, type);
  22128. if (pi.skipOnPointerObservable) {
  22129. return;
  22130. }
  22131. }
  22132. }
  22133. }
  22134. else {
  22135. var type = BABYLON.PointerEventTypes.POINTERUP;
  22136. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22137. _this.onPrePointerObservable.notifyObservers(pi, type);
  22138. if (pi.skipOnPointerObservable) {
  22139. return;
  22140. }
  22141. }
  22142. }
  22143. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  22144. return;
  22145. }
  22146. if (!_this.pointerUpPredicate) {
  22147. _this.pointerUpPredicate = function (mesh) {
  22148. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  22149. };
  22150. }
  22151. // Meshes
  22152. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  22153. _this._initActionManager(null, clickInfo);
  22154. }
  22155. if (!pickResult) {
  22156. pickResult = _this._currentPickResult;
  22157. }
  22158. _this._processPointerUp(pickResult, evt, clickInfo);
  22159. // Sprites
  22160. if (_this.spriteManagers.length > 0) {
  22161. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  22162. if (spritePickResult) {
  22163. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  22164. if (spritePickResult.pickedSprite.actionManager) {
  22165. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  22166. if (spritePickResult.pickedSprite.actionManager) {
  22167. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  22168. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  22169. }
  22170. }
  22171. }
  22172. }
  22173. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  22174. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  22175. }
  22176. }
  22177. }
  22178. _this._previousPickResult = _this._currentPickResult;
  22179. });
  22180. };
  22181. this._onKeyDown = function (evt) {
  22182. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  22183. if (_this.onPreKeyboardObservable.hasObservers()) {
  22184. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  22185. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  22186. if (pi.skipOnPointerObservable) {
  22187. return;
  22188. }
  22189. }
  22190. if (_this.onKeyboardObservable.hasObservers()) {
  22191. var pi = new BABYLON.KeyboardInfo(type, evt);
  22192. _this.onKeyboardObservable.notifyObservers(pi, type);
  22193. }
  22194. if (_this.actionManager) {
  22195. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  22196. }
  22197. };
  22198. this._onKeyUp = function (evt) {
  22199. var type = BABYLON.KeyboardEventTypes.KEYUP;
  22200. if (_this.onPreKeyboardObservable.hasObservers()) {
  22201. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  22202. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  22203. if (pi.skipOnPointerObservable) {
  22204. return;
  22205. }
  22206. }
  22207. if (_this.onKeyboardObservable.hasObservers()) {
  22208. var pi = new BABYLON.KeyboardInfo(type, evt);
  22209. _this.onKeyboardObservable.notifyObservers(pi, type);
  22210. }
  22211. if (_this.actionManager) {
  22212. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  22213. }
  22214. };
  22215. var engine = this.getEngine();
  22216. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  22217. if (!canvas) {
  22218. return;
  22219. }
  22220. canvas.addEventListener("keydown", _this._onKeyDown, false);
  22221. canvas.addEventListener("keyup", _this._onKeyUp, false);
  22222. });
  22223. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  22224. if (!canvas) {
  22225. return;
  22226. }
  22227. canvas.removeEventListener("keydown", _this._onKeyDown);
  22228. canvas.removeEventListener("keyup", _this._onKeyUp);
  22229. });
  22230. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  22231. var canvas = this._engine.getRenderingCanvas();
  22232. if (!canvas) {
  22233. return;
  22234. }
  22235. if (attachMove) {
  22236. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  22237. // Wheel
  22238. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  22239. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  22240. }
  22241. if (attachDown) {
  22242. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  22243. }
  22244. if (attachUp) {
  22245. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  22246. }
  22247. canvas.tabIndex = 1;
  22248. };
  22249. Scene.prototype.detachControl = function () {
  22250. var engine = this.getEngine();
  22251. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  22252. var canvas = engine.getRenderingCanvas();
  22253. if (!canvas) {
  22254. return;
  22255. }
  22256. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  22257. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  22258. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  22259. if (this._onCanvasBlurObserver) {
  22260. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  22261. }
  22262. if (this._onCanvasFocusObserver) {
  22263. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  22264. }
  22265. // Wheel
  22266. canvas.removeEventListener('mousewheel', this._onPointerMove);
  22267. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  22268. // Keyboard
  22269. canvas.removeEventListener("keydown", this._onKeyDown);
  22270. canvas.removeEventListener("keyup", this._onKeyUp);
  22271. // Observables
  22272. this.onKeyboardObservable.clear();
  22273. this.onPreKeyboardObservable.clear();
  22274. this.onPointerObservable.clear();
  22275. this.onPrePointerObservable.clear();
  22276. };
  22277. /**
  22278. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  22279. * Delay loaded resources are not taking in account
  22280. * @return true if all required resources are ready
  22281. */
  22282. Scene.prototype.isReady = function () {
  22283. if (this._isDisposed) {
  22284. return false;
  22285. }
  22286. if (this._pendingData.length > 0) {
  22287. return false;
  22288. }
  22289. var index;
  22290. var engine = this.getEngine();
  22291. // Geometries
  22292. for (index = 0; index < this._geometries.length; index++) {
  22293. var geometry = this._geometries[index];
  22294. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  22295. return false;
  22296. }
  22297. }
  22298. // Meshes
  22299. for (index = 0; index < this.meshes.length; index++) {
  22300. var mesh = this.meshes[index];
  22301. if (!mesh.isEnabled()) {
  22302. continue;
  22303. }
  22304. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  22305. continue;
  22306. }
  22307. if (!mesh.isReady()) {
  22308. return false;
  22309. }
  22310. // Effect layers
  22311. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  22312. for (var _i = 0, _a = this.effectLayers; _i < _a.length; _i++) {
  22313. var layer = _a[_i];
  22314. if (!layer.hasMesh(mesh)) {
  22315. continue;
  22316. }
  22317. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  22318. var subMesh = _c[_b];
  22319. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  22320. return false;
  22321. }
  22322. }
  22323. }
  22324. }
  22325. return true;
  22326. };
  22327. Scene.prototype.resetCachedMaterial = function () {
  22328. this._cachedMaterial = null;
  22329. this._cachedEffect = null;
  22330. this._cachedVisibility = null;
  22331. };
  22332. Scene.prototype.registerBeforeRender = function (func) {
  22333. this.onBeforeRenderObservable.add(func);
  22334. };
  22335. Scene.prototype.unregisterBeforeRender = function (func) {
  22336. this.onBeforeRenderObservable.removeCallback(func);
  22337. };
  22338. Scene.prototype.registerAfterRender = function (func) {
  22339. this.onAfterRenderObservable.add(func);
  22340. };
  22341. Scene.prototype.unregisterAfterRender = function (func) {
  22342. this.onAfterRenderObservable.removeCallback(func);
  22343. };
  22344. Scene.prototype._executeOnceBeforeRender = function (func) {
  22345. var _this = this;
  22346. var execFunc = function () {
  22347. func();
  22348. setTimeout(function () {
  22349. _this.unregisterBeforeRender(execFunc);
  22350. });
  22351. };
  22352. this.registerBeforeRender(execFunc);
  22353. };
  22354. /**
  22355. * The provided function will run before render once and will be disposed afterwards.
  22356. * A timeout delay can be provided so that the function will be executed in N ms.
  22357. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  22358. * @param func The function to be executed.
  22359. * @param timeout optional delay in ms
  22360. */
  22361. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  22362. var _this = this;
  22363. if (timeout !== undefined) {
  22364. setTimeout(function () {
  22365. _this._executeOnceBeforeRender(func);
  22366. }, timeout);
  22367. }
  22368. else {
  22369. this._executeOnceBeforeRender(func);
  22370. }
  22371. };
  22372. Scene.prototype._addPendingData = function (data) {
  22373. this._pendingData.push(data);
  22374. };
  22375. Scene.prototype._removePendingData = function (data) {
  22376. var wasLoading = this.isLoading;
  22377. var index = this._pendingData.indexOf(data);
  22378. if (index !== -1) {
  22379. this._pendingData.splice(index, 1);
  22380. }
  22381. if (wasLoading && !this.isLoading) {
  22382. this.onDataLoadedObservable.notifyObservers(this);
  22383. }
  22384. };
  22385. Scene.prototype.getWaitingItemsCount = function () {
  22386. return this._pendingData.length;
  22387. };
  22388. Object.defineProperty(Scene.prototype, "isLoading", {
  22389. get: function () {
  22390. return this._pendingData.length > 0;
  22391. },
  22392. enumerable: true,
  22393. configurable: true
  22394. });
  22395. /**
  22396. * Registers a function to be executed when the scene is ready.
  22397. * @param {Function} func - the function to be executed.
  22398. */
  22399. Scene.prototype.executeWhenReady = function (func) {
  22400. var _this = this;
  22401. this.onReadyObservable.add(func);
  22402. if (this._executeWhenReadyTimeoutId !== -1) {
  22403. return;
  22404. }
  22405. this._executeWhenReadyTimeoutId = setTimeout(function () {
  22406. _this._checkIsReady();
  22407. }, 150);
  22408. };
  22409. /**
  22410. * Returns a promise that resolves when the scene is ready.
  22411. * @returns A promise that resolves when the scene is ready.
  22412. */
  22413. Scene.prototype.whenReadyAsync = function () {
  22414. var _this = this;
  22415. return new Promise(function (resolve) {
  22416. _this.executeWhenReady(function () {
  22417. resolve();
  22418. });
  22419. });
  22420. };
  22421. Scene.prototype._checkIsReady = function () {
  22422. var _this = this;
  22423. if (this.isReady()) {
  22424. this.onReadyObservable.notifyObservers(this);
  22425. this.onReadyObservable.clear();
  22426. this._executeWhenReadyTimeoutId = -1;
  22427. return;
  22428. }
  22429. this._executeWhenReadyTimeoutId = setTimeout(function () {
  22430. _this._checkIsReady();
  22431. }, 150);
  22432. };
  22433. // Animations
  22434. /**
  22435. * Will start the animation sequence of a given target
  22436. * @param target - the target
  22437. * @param {number} from - from which frame should animation start
  22438. * @param {number} to - till which frame should animation run.
  22439. * @param {boolean} [loop] - should the animation loop
  22440. * @param {number} [speedRatio] - the speed in which to run the animation
  22441. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  22442. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  22443. * Returns {BABYLON.Animatable} the animatable object created for this animation
  22444. * See BABYLON.Animatable
  22445. */
  22446. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  22447. if (speedRatio === void 0) { speedRatio = 1.0; }
  22448. if (from > to && speedRatio > 0) {
  22449. speedRatio *= -1;
  22450. }
  22451. this.stopAnimation(target);
  22452. if (!animatable) {
  22453. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  22454. }
  22455. // Local animations
  22456. if (target.animations) {
  22457. animatable.appendAnimations(target, target.animations);
  22458. }
  22459. // Children animations
  22460. if (target.getAnimatables) {
  22461. var animatables = target.getAnimatables();
  22462. for (var index = 0; index < animatables.length; index++) {
  22463. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  22464. }
  22465. }
  22466. animatable.reset();
  22467. return animatable;
  22468. };
  22469. /**
  22470. * Begin a new animation on a given node
  22471. * @param {BABYLON.Node} node defines the root node where the animation will take place
  22472. * @param {BABYLON.Animation[]} defines the list of animations to start
  22473. * @param {number} from defines the initial value
  22474. * @param {number} to defines the final value
  22475. * @param {boolean} loop defines if you want animation to loop (off by default)
  22476. * @param {number} speedRatio defines the speed ratio to apply to all animations
  22477. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  22478. * @returns the list of created animatables
  22479. */
  22480. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  22481. if (speedRatio === undefined) {
  22482. speedRatio = 1.0;
  22483. }
  22484. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  22485. return animatable;
  22486. };
  22487. /**
  22488. * Begin a new animation on a given node and its hierarchy
  22489. * @param {BABYLON.Node} node defines the root node where the animation will take place
  22490. * @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.
  22491. * @param {BABYLON.Animation[]} defines the list of animations to start
  22492. * @param {number} from defines the initial value
  22493. * @param {number} to defines the final value
  22494. * @param {boolean} loop defines if you want animation to loop (off by default)
  22495. * @param {number} speedRatio defines the speed ratio to apply to all animations
  22496. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  22497. * @returns the list of animatables created for all nodes
  22498. */
  22499. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  22500. var children = target.getDescendants(directDescendantsOnly);
  22501. var result = [];
  22502. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  22503. var child = children_1[_i];
  22504. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  22505. }
  22506. return result;
  22507. };
  22508. Scene.prototype.getAnimatableByTarget = function (target) {
  22509. for (var index = 0; index < this._activeAnimatables.length; index++) {
  22510. if (this._activeAnimatables[index].target === target) {
  22511. return this._activeAnimatables[index];
  22512. }
  22513. }
  22514. return null;
  22515. };
  22516. Object.defineProperty(Scene.prototype, "animatables", {
  22517. get: function () {
  22518. return this._activeAnimatables;
  22519. },
  22520. enumerable: true,
  22521. configurable: true
  22522. });
  22523. /**
  22524. * Will stop the animation of the given target
  22525. * @param target - the target
  22526. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  22527. * @see beginAnimation
  22528. */
  22529. Scene.prototype.stopAnimation = function (target, animationName) {
  22530. var animatable = this.getAnimatableByTarget(target);
  22531. if (animatable) {
  22532. animatable.stop(animationName);
  22533. }
  22534. };
  22535. /**
  22536. * Stops and removes all animations that have been applied to the scene
  22537. */
  22538. Scene.prototype.stopAllAnimations = function () {
  22539. if (this._activeAnimatables) {
  22540. for (var i = 0; i < this._activeAnimatables.length; i++) {
  22541. this._activeAnimatables[i].stop();
  22542. }
  22543. this._activeAnimatables = [];
  22544. }
  22545. };
  22546. Scene.prototype._animate = function () {
  22547. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  22548. return;
  22549. }
  22550. // Getting time
  22551. var now = BABYLON.Tools.Now;
  22552. if (!this._animationTimeLast) {
  22553. if (this._pendingData.length > 0) {
  22554. return;
  22555. }
  22556. this._animationTimeLast = now;
  22557. }
  22558. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  22559. this._animationTime += deltaTime;
  22560. this._animationTimeLast = now;
  22561. for (var index = 0; index < this._activeAnimatables.length; index++) {
  22562. this._activeAnimatables[index]._animate(this._animationTime);
  22563. }
  22564. };
  22565. // Matrix
  22566. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  22567. this._useAlternateCameraConfiguration = active;
  22568. };
  22569. Scene.prototype.getViewMatrix = function () {
  22570. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  22571. };
  22572. Scene.prototype.getProjectionMatrix = function () {
  22573. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  22574. };
  22575. Scene.prototype.getTransformMatrix = function () {
  22576. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  22577. };
  22578. Scene.prototype.setTransformMatrix = function (view, projection) {
  22579. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  22580. return;
  22581. }
  22582. this._viewUpdateFlag = view.updateFlag;
  22583. this._projectionUpdateFlag = projection.updateFlag;
  22584. this._viewMatrix = view;
  22585. this._projectionMatrix = projection;
  22586. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  22587. // Update frustum
  22588. if (!this._frustumPlanes) {
  22589. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  22590. }
  22591. else {
  22592. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  22593. }
  22594. if (this.activeCamera && this.activeCamera._alternateCamera) {
  22595. var otherCamera = this.activeCamera._alternateCamera;
  22596. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  22597. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  22598. }
  22599. if (this._sceneUbo.useUbo) {
  22600. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  22601. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  22602. this._sceneUbo.update();
  22603. }
  22604. };
  22605. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  22606. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  22607. return;
  22608. }
  22609. this._alternateViewUpdateFlag = view.updateFlag;
  22610. this._alternateProjectionUpdateFlag = projection.updateFlag;
  22611. this._alternateViewMatrix = view;
  22612. this._alternateProjectionMatrix = projection;
  22613. if (!this._alternateTransformMatrix) {
  22614. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  22615. }
  22616. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  22617. if (!this._alternateSceneUbo) {
  22618. this._createAlternateUbo();
  22619. }
  22620. if (this._alternateSceneUbo.useUbo) {
  22621. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  22622. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  22623. this._alternateSceneUbo.update();
  22624. }
  22625. };
  22626. Scene.prototype.getSceneUniformBuffer = function () {
  22627. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  22628. };
  22629. // Methods
  22630. Scene.prototype.getUniqueId = function () {
  22631. var result = Scene._uniqueIdCounter;
  22632. Scene._uniqueIdCounter++;
  22633. return result;
  22634. };
  22635. Scene.prototype.addMesh = function (newMesh) {
  22636. this.meshes.push(newMesh);
  22637. //notify the collision coordinator
  22638. if (this.collisionCoordinator) {
  22639. this.collisionCoordinator.onMeshAdded(newMesh);
  22640. }
  22641. newMesh._resyncLightSources();
  22642. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  22643. };
  22644. Scene.prototype.removeMesh = function (toRemove) {
  22645. var index = this.meshes.indexOf(toRemove);
  22646. if (index !== -1) {
  22647. // Remove from the scene if mesh found
  22648. this.meshes.splice(index, 1);
  22649. }
  22650. this.onMeshRemovedObservable.notifyObservers(toRemove);
  22651. return index;
  22652. };
  22653. Scene.prototype.addTransformNode = function (newTransformNode) {
  22654. this.transformNodes.push(newTransformNode);
  22655. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  22656. };
  22657. Scene.prototype.removeTransformNode = function (toRemove) {
  22658. var index = this.transformNodes.indexOf(toRemove);
  22659. if (index !== -1) {
  22660. // Remove from the scene if found
  22661. this.transformNodes.splice(index, 1);
  22662. }
  22663. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  22664. return index;
  22665. };
  22666. Scene.prototype.removeSkeleton = function (toRemove) {
  22667. var index = this.skeletons.indexOf(toRemove);
  22668. if (index !== -1) {
  22669. // Remove from the scene if found
  22670. this.skeletons.splice(index, 1);
  22671. }
  22672. return index;
  22673. };
  22674. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  22675. var index = this.morphTargetManagers.indexOf(toRemove);
  22676. if (index !== -1) {
  22677. // Remove from the scene if found
  22678. this.morphTargetManagers.splice(index, 1);
  22679. }
  22680. return index;
  22681. };
  22682. Scene.prototype.removeLight = function (toRemove) {
  22683. var index = this.lights.indexOf(toRemove);
  22684. if (index !== -1) {
  22685. // Remove from meshes
  22686. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  22687. var mesh = _a[_i];
  22688. mesh._removeLightSource(toRemove);
  22689. }
  22690. // Remove from the scene if mesh found
  22691. this.lights.splice(index, 1);
  22692. this.sortLightsByPriority();
  22693. }
  22694. this.onLightRemovedObservable.notifyObservers(toRemove);
  22695. return index;
  22696. };
  22697. Scene.prototype.removeCamera = function (toRemove) {
  22698. var index = this.cameras.indexOf(toRemove);
  22699. if (index !== -1) {
  22700. // Remove from the scene if mesh found
  22701. this.cameras.splice(index, 1);
  22702. }
  22703. // Remove from activeCameras
  22704. var index2 = this.activeCameras.indexOf(toRemove);
  22705. if (index2 !== -1) {
  22706. // Remove from the scene if mesh found
  22707. this.activeCameras.splice(index2, 1);
  22708. }
  22709. // Reset the activeCamera
  22710. if (this.activeCamera === toRemove) {
  22711. if (this.cameras.length > 0) {
  22712. this.activeCamera = this.cameras[0];
  22713. }
  22714. else {
  22715. this.activeCamera = null;
  22716. }
  22717. }
  22718. this.onCameraRemovedObservable.notifyObservers(toRemove);
  22719. return index;
  22720. };
  22721. Scene.prototype.removeParticleSystem = function (toRemove) {
  22722. var index = this.particleSystems.indexOf(toRemove);
  22723. if (index !== -1) {
  22724. this.particleSystems.splice(index, 1);
  22725. }
  22726. return index;
  22727. };
  22728. ;
  22729. Scene.prototype.removeAnimation = function (toRemove) {
  22730. var index = this.animations.indexOf(toRemove);
  22731. if (index !== -1) {
  22732. this.animations.splice(index, 1);
  22733. }
  22734. return index;
  22735. };
  22736. ;
  22737. Scene.prototype.removeMultiMaterial = function (toRemove) {
  22738. var index = this.multiMaterials.indexOf(toRemove);
  22739. if (index !== -1) {
  22740. this.multiMaterials.splice(index, 1);
  22741. }
  22742. return index;
  22743. };
  22744. ;
  22745. Scene.prototype.removeMaterial = function (toRemove) {
  22746. var index = this.materials.indexOf(toRemove);
  22747. if (index !== -1) {
  22748. this.materials.splice(index, 1);
  22749. }
  22750. return index;
  22751. };
  22752. ;
  22753. Scene.prototype.removeLensFlareSystem = function (toRemove) {
  22754. var index = this.lensFlareSystems.indexOf(toRemove);
  22755. if (index !== -1) {
  22756. this.lensFlareSystems.splice(index, 1);
  22757. }
  22758. return index;
  22759. };
  22760. ;
  22761. Scene.prototype.removeActionManager = function (toRemove) {
  22762. var index = this._actionManagers.indexOf(toRemove);
  22763. if (index !== -1) {
  22764. this._actionManagers.splice(index, 1);
  22765. }
  22766. return index;
  22767. };
  22768. ;
  22769. Scene.prototype.addLight = function (newLight) {
  22770. this.lights.push(newLight);
  22771. this.sortLightsByPriority();
  22772. // Add light to all meshes (To support if the light is removed and then readded)
  22773. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  22774. var mesh = _a[_i];
  22775. if (mesh._lightSources.indexOf(newLight) === -1) {
  22776. mesh._lightSources.push(newLight);
  22777. mesh._resyncLightSources();
  22778. }
  22779. }
  22780. this.onNewLightAddedObservable.notifyObservers(newLight);
  22781. };
  22782. Scene.prototype.sortLightsByPriority = function () {
  22783. if (this.requireLightSorting) {
  22784. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  22785. }
  22786. };
  22787. Scene.prototype.addCamera = function (newCamera) {
  22788. this.cameras.push(newCamera);
  22789. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  22790. };
  22791. Scene.prototype.addSkeleton = function (newSkeleton) {
  22792. this.skeletons.push(newSkeleton);
  22793. };
  22794. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  22795. this.particleSystems.push(newParticleSystem);
  22796. };
  22797. Scene.prototype.addAnimation = function (newAnimation) {
  22798. this.animations.push(newAnimation);
  22799. };
  22800. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  22801. this.multiMaterials.push(newMultiMaterial);
  22802. };
  22803. Scene.prototype.addMaterial = function (newMaterial) {
  22804. this.materials.push(newMaterial);
  22805. };
  22806. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  22807. this.morphTargetManagers.push(newMorphTargetManager);
  22808. };
  22809. Scene.prototype.addGeometry = function (newGeometrie) {
  22810. this._geometries.push(newGeometrie);
  22811. };
  22812. Scene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  22813. this.lensFlareSystems.push(newLensFlareSystem);
  22814. };
  22815. Scene.prototype.addActionManager = function (newActionManager) {
  22816. this._actionManagers.push(newActionManager);
  22817. };
  22818. /**
  22819. * Switch active camera
  22820. * @param {Camera} newCamera - new active camera
  22821. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  22822. */
  22823. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  22824. if (attachControl === void 0) { attachControl = true; }
  22825. var canvas = this._engine.getRenderingCanvas();
  22826. if (!canvas) {
  22827. return;
  22828. }
  22829. if (this.activeCamera) {
  22830. this.activeCamera.detachControl(canvas);
  22831. }
  22832. this.activeCamera = newCamera;
  22833. if (attachControl) {
  22834. newCamera.attachControl(canvas);
  22835. }
  22836. };
  22837. /**
  22838. * sets the active camera of the scene using its ID
  22839. * @param {string} id - the camera's ID
  22840. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  22841. * @see activeCamera
  22842. */
  22843. Scene.prototype.setActiveCameraByID = function (id) {
  22844. var camera = this.getCameraByID(id);
  22845. if (camera) {
  22846. this.activeCamera = camera;
  22847. return camera;
  22848. }
  22849. return null;
  22850. };
  22851. /**
  22852. * sets the active camera of the scene using its name
  22853. * @param {string} name - the camera's name
  22854. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  22855. * @see activeCamera
  22856. */
  22857. Scene.prototype.setActiveCameraByName = function (name) {
  22858. var camera = this.getCameraByName(name);
  22859. if (camera) {
  22860. this.activeCamera = camera;
  22861. return camera;
  22862. }
  22863. return null;
  22864. };
  22865. /**
  22866. * get an animation group using its name
  22867. * @param {string} the material's name
  22868. * @return {BABYLON.AnimationGroup|null} the animation group or null if none found.
  22869. */
  22870. Scene.prototype.getAnimationGroupByName = function (name) {
  22871. for (var index = 0; index < this.animationGroups.length; index++) {
  22872. if (this.animationGroups[index].name === name) {
  22873. return this.animationGroups[index];
  22874. }
  22875. }
  22876. return null;
  22877. };
  22878. /**
  22879. * get a material using its id
  22880. * @param {string} the material's ID
  22881. * @return {BABYLON.Material|null} the material or null if none found.
  22882. */
  22883. Scene.prototype.getMaterialByID = function (id) {
  22884. for (var index = 0; index < this.materials.length; index++) {
  22885. if (this.materials[index].id === id) {
  22886. return this.materials[index];
  22887. }
  22888. }
  22889. return null;
  22890. };
  22891. /**
  22892. * get a material using its name
  22893. * @param {string} the material's name
  22894. * @return {BABYLON.Material|null} the material or null if none found.
  22895. */
  22896. Scene.prototype.getMaterialByName = function (name) {
  22897. for (var index = 0; index < this.materials.length; index++) {
  22898. if (this.materials[index].name === name) {
  22899. return this.materials[index];
  22900. }
  22901. }
  22902. return null;
  22903. };
  22904. Scene.prototype.getLensFlareSystemByName = function (name) {
  22905. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  22906. if (this.lensFlareSystems[index].name === name) {
  22907. return this.lensFlareSystems[index];
  22908. }
  22909. }
  22910. return null;
  22911. };
  22912. Scene.prototype.getLensFlareSystemByID = function (id) {
  22913. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  22914. if (this.lensFlareSystems[index].id === id) {
  22915. return this.lensFlareSystems[index];
  22916. }
  22917. }
  22918. return null;
  22919. };
  22920. Scene.prototype.getCameraByID = function (id) {
  22921. for (var index = 0; index < this.cameras.length; index++) {
  22922. if (this.cameras[index].id === id) {
  22923. return this.cameras[index];
  22924. }
  22925. }
  22926. return null;
  22927. };
  22928. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  22929. for (var index = 0; index < this.cameras.length; index++) {
  22930. if (this.cameras[index].uniqueId === uniqueId) {
  22931. return this.cameras[index];
  22932. }
  22933. }
  22934. return null;
  22935. };
  22936. /**
  22937. * get a camera using its name
  22938. * @param {string} the camera's name
  22939. * @return {BABYLON.Camera|null} the camera or null if none found.
  22940. */
  22941. Scene.prototype.getCameraByName = function (name) {
  22942. for (var index = 0; index < this.cameras.length; index++) {
  22943. if (this.cameras[index].name === name) {
  22944. return this.cameras[index];
  22945. }
  22946. }
  22947. return null;
  22948. };
  22949. /**
  22950. * get a bone using its id
  22951. * @param {string} the bone's id
  22952. * @return {BABYLON.Bone|null} the bone or null if not found
  22953. */
  22954. Scene.prototype.getBoneByID = function (id) {
  22955. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  22956. var skeleton = this.skeletons[skeletonIndex];
  22957. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  22958. if (skeleton.bones[boneIndex].id === id) {
  22959. return skeleton.bones[boneIndex];
  22960. }
  22961. }
  22962. }
  22963. return null;
  22964. };
  22965. /**
  22966. * get a bone using its id
  22967. * @param {string} the bone's name
  22968. * @return {BABYLON.Bone|null} the bone or null if not found
  22969. */
  22970. Scene.prototype.getBoneByName = function (name) {
  22971. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  22972. var skeleton = this.skeletons[skeletonIndex];
  22973. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  22974. if (skeleton.bones[boneIndex].name === name) {
  22975. return skeleton.bones[boneIndex];
  22976. }
  22977. }
  22978. }
  22979. return null;
  22980. };
  22981. /**
  22982. * get a light node using its name
  22983. * @param {string} the light's name
  22984. * @return {BABYLON.Light|null} the light or null if none found.
  22985. */
  22986. Scene.prototype.getLightByName = function (name) {
  22987. for (var index = 0; index < this.lights.length; index++) {
  22988. if (this.lights[index].name === name) {
  22989. return this.lights[index];
  22990. }
  22991. }
  22992. return null;
  22993. };
  22994. /**
  22995. * get a light node using its ID
  22996. * @param {string} the light's id
  22997. * @return {BABYLON.Light|null} the light or null if none found.
  22998. */
  22999. Scene.prototype.getLightByID = function (id) {
  23000. for (var index = 0; index < this.lights.length; index++) {
  23001. if (this.lights[index].id === id) {
  23002. return this.lights[index];
  23003. }
  23004. }
  23005. return null;
  23006. };
  23007. /**
  23008. * get a light node using its scene-generated unique ID
  23009. * @param {number} the light's unique id
  23010. * @return {BABYLON.Light|null} the light or null if none found.
  23011. */
  23012. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  23013. for (var index = 0; index < this.lights.length; index++) {
  23014. if (this.lights[index].uniqueId === uniqueId) {
  23015. return this.lights[index];
  23016. }
  23017. }
  23018. return null;
  23019. };
  23020. /**
  23021. * get a particle system by id
  23022. * @param id {number} the particle system id
  23023. * @return {BABYLON.IParticleSystem|null} the corresponding system or null if none found.
  23024. */
  23025. Scene.prototype.getParticleSystemByID = function (id) {
  23026. for (var index = 0; index < this.particleSystems.length; index++) {
  23027. if (this.particleSystems[index].id === id) {
  23028. return this.particleSystems[index];
  23029. }
  23030. }
  23031. return null;
  23032. };
  23033. /**
  23034. * get a geometry using its ID
  23035. * @param {string} the geometry's id
  23036. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  23037. */
  23038. Scene.prototype.getGeometryByID = function (id) {
  23039. for (var index = 0; index < this._geometries.length; index++) {
  23040. if (this._geometries[index].id === id) {
  23041. return this._geometries[index];
  23042. }
  23043. }
  23044. return null;
  23045. };
  23046. /**
  23047. * add a new geometry to this scene.
  23048. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  23049. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  23050. * @return {boolean} was the geometry added or not
  23051. */
  23052. Scene.prototype.pushGeometry = function (geometry, force) {
  23053. if (!force && this.getGeometryByID(geometry.id)) {
  23054. return false;
  23055. }
  23056. this._geometries.push(geometry);
  23057. //notify the collision coordinator
  23058. if (this.collisionCoordinator) {
  23059. this.collisionCoordinator.onGeometryAdded(geometry);
  23060. }
  23061. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  23062. return true;
  23063. };
  23064. /**
  23065. * Removes an existing geometry
  23066. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  23067. * @return {boolean} was the geometry removed or not
  23068. */
  23069. Scene.prototype.removeGeometry = function (geometry) {
  23070. var index = this._geometries.indexOf(geometry);
  23071. if (index > -1) {
  23072. this._geometries.splice(index, 1);
  23073. //notify the collision coordinator
  23074. if (this.collisionCoordinator) {
  23075. this.collisionCoordinator.onGeometryDeleted(geometry);
  23076. }
  23077. this.onGeometryRemovedObservable.notifyObservers(geometry);
  23078. return true;
  23079. }
  23080. return false;
  23081. };
  23082. Scene.prototype.getGeometries = function () {
  23083. return this._geometries;
  23084. };
  23085. /**
  23086. * Get the first added mesh found of a given ID
  23087. * @param {string} id - the id to search for
  23088. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  23089. */
  23090. Scene.prototype.getMeshByID = function (id) {
  23091. for (var index = 0; index < this.meshes.length; index++) {
  23092. if (this.meshes[index].id === id) {
  23093. return this.meshes[index];
  23094. }
  23095. }
  23096. return null;
  23097. };
  23098. Scene.prototype.getMeshesByID = function (id) {
  23099. return this.meshes.filter(function (m) {
  23100. return m.id === id;
  23101. });
  23102. };
  23103. /**
  23104. * Get the first added transform node found of a given ID
  23105. * @param {string} id - the id to search for
  23106. * @return {BABYLON.TransformNode|null} the transform node found or null if not found at all.
  23107. */
  23108. Scene.prototype.getTransformNodeByID = function (id) {
  23109. for (var index = 0; index < this.transformNodes.length; index++) {
  23110. if (this.transformNodes[index].id === id) {
  23111. return this.transformNodes[index];
  23112. }
  23113. }
  23114. return null;
  23115. };
  23116. Scene.prototype.getTransformNodesByID = function (id) {
  23117. return this.transformNodes.filter(function (m) {
  23118. return m.id === id;
  23119. });
  23120. };
  23121. /**
  23122. * Get a mesh with its auto-generated unique id
  23123. * @param {number} uniqueId - the unique id to search for
  23124. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  23125. */
  23126. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  23127. for (var index = 0; index < this.meshes.length; index++) {
  23128. if (this.meshes[index].uniqueId === uniqueId) {
  23129. return this.meshes[index];
  23130. }
  23131. }
  23132. return null;
  23133. };
  23134. /**
  23135. * Get a the last added mesh found of a given ID
  23136. * @param {string} id - the id to search for
  23137. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  23138. */
  23139. Scene.prototype.getLastMeshByID = function (id) {
  23140. for (var index = this.meshes.length - 1; index >= 0; index--) {
  23141. if (this.meshes[index].id === id) {
  23142. return this.meshes[index];
  23143. }
  23144. }
  23145. return null;
  23146. };
  23147. /**
  23148. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  23149. * @param {string} id - the id to search for
  23150. * @return {BABYLON.Node|null} the node found or null if not found at all.
  23151. */
  23152. Scene.prototype.getLastEntryByID = function (id) {
  23153. var index;
  23154. for (index = this.meshes.length - 1; index >= 0; index--) {
  23155. if (this.meshes[index].id === id) {
  23156. return this.meshes[index];
  23157. }
  23158. }
  23159. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  23160. if (this.transformNodes[index].id === id) {
  23161. return this.transformNodes[index];
  23162. }
  23163. }
  23164. for (index = this.cameras.length - 1; index >= 0; index--) {
  23165. if (this.cameras[index].id === id) {
  23166. return this.cameras[index];
  23167. }
  23168. }
  23169. for (index = this.lights.length - 1; index >= 0; index--) {
  23170. if (this.lights[index].id === id) {
  23171. return this.lights[index];
  23172. }
  23173. }
  23174. return null;
  23175. };
  23176. Scene.prototype.getNodeByID = function (id) {
  23177. var mesh = this.getMeshByID(id);
  23178. if (mesh) {
  23179. return mesh;
  23180. }
  23181. var light = this.getLightByID(id);
  23182. if (light) {
  23183. return light;
  23184. }
  23185. var camera = this.getCameraByID(id);
  23186. if (camera) {
  23187. return camera;
  23188. }
  23189. var bone = this.getBoneByID(id);
  23190. return bone;
  23191. };
  23192. Scene.prototype.getNodeByName = function (name) {
  23193. var mesh = this.getMeshByName(name);
  23194. if (mesh) {
  23195. return mesh;
  23196. }
  23197. var light = this.getLightByName(name);
  23198. if (light) {
  23199. return light;
  23200. }
  23201. var camera = this.getCameraByName(name);
  23202. if (camera) {
  23203. return camera;
  23204. }
  23205. var bone = this.getBoneByName(name);
  23206. return bone;
  23207. };
  23208. Scene.prototype.getMeshByName = function (name) {
  23209. for (var index = 0; index < this.meshes.length; index++) {
  23210. if (this.meshes[index].name === name) {
  23211. return this.meshes[index];
  23212. }
  23213. }
  23214. return null;
  23215. };
  23216. Scene.prototype.getTransformNodeByName = function (name) {
  23217. for (var index = 0; index < this.transformNodes.length; index++) {
  23218. if (this.transformNodes[index].name === name) {
  23219. return this.transformNodes[index];
  23220. }
  23221. }
  23222. return null;
  23223. };
  23224. Scene.prototype.getSoundByName = function (name) {
  23225. var index;
  23226. if (BABYLON.AudioEngine) {
  23227. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  23228. if (this.mainSoundTrack.soundCollection[index].name === name) {
  23229. return this.mainSoundTrack.soundCollection[index];
  23230. }
  23231. }
  23232. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  23233. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  23234. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  23235. return this.soundTracks[sdIndex].soundCollection[index];
  23236. }
  23237. }
  23238. }
  23239. }
  23240. return null;
  23241. };
  23242. Scene.prototype.getLastSkeletonByID = function (id) {
  23243. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  23244. if (this.skeletons[index].id === id) {
  23245. return this.skeletons[index];
  23246. }
  23247. }
  23248. return null;
  23249. };
  23250. Scene.prototype.getSkeletonById = function (id) {
  23251. for (var index = 0; index < this.skeletons.length; index++) {
  23252. if (this.skeletons[index].id === id) {
  23253. return this.skeletons[index];
  23254. }
  23255. }
  23256. return null;
  23257. };
  23258. Scene.prototype.getSkeletonByName = function (name) {
  23259. for (var index = 0; index < this.skeletons.length; index++) {
  23260. if (this.skeletons[index].name === name) {
  23261. return this.skeletons[index];
  23262. }
  23263. }
  23264. return null;
  23265. };
  23266. Scene.prototype.getMorphTargetManagerById = function (id) {
  23267. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  23268. if (this.morphTargetManagers[index].uniqueId === id) {
  23269. return this.morphTargetManagers[index];
  23270. }
  23271. }
  23272. return null;
  23273. };
  23274. Scene.prototype.isActiveMesh = function (mesh) {
  23275. return (this._activeMeshes.indexOf(mesh) !== -1);
  23276. };
  23277. /**
  23278. * Return a the first highlight layer of the scene with a given name.
  23279. * @param name The name of the highlight layer to look for.
  23280. * @return The highlight layer if found otherwise null.
  23281. */
  23282. Scene.prototype.getHighlightLayerByName = function (name) {
  23283. for (var index = 0; index < this.effectLayers.length; index++) {
  23284. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.HighlightLayer.EffectName) {
  23285. return this.effectLayers[index];
  23286. }
  23287. }
  23288. return null;
  23289. };
  23290. /**
  23291. * Return a the first highlight layer of the scene with a given name.
  23292. * @param name The name of the highlight layer to look for.
  23293. * @return The highlight layer if found otherwise null.
  23294. */
  23295. Scene.prototype.getGlowLayerByName = function (name) {
  23296. for (var index = 0; index < this.effectLayers.length; index++) {
  23297. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.GlowLayer.EffectName) {
  23298. return this.effectLayers[index];
  23299. }
  23300. }
  23301. return null;
  23302. };
  23303. Object.defineProperty(Scene.prototype, "uid", {
  23304. /**
  23305. * Return a unique id as a string which can serve as an identifier for the scene
  23306. */
  23307. get: function () {
  23308. if (!this._uid) {
  23309. this._uid = BABYLON.Tools.RandomId();
  23310. }
  23311. return this._uid;
  23312. },
  23313. enumerable: true,
  23314. configurable: true
  23315. });
  23316. /**
  23317. * Add an externaly attached data from its key.
  23318. * This method call will fail and return false, if such key already exists.
  23319. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  23320. * @param key the unique key that identifies the data
  23321. * @param data the data object to associate to the key for this Engine instance
  23322. * @return true if no such key were already present and the data was added successfully, false otherwise
  23323. */
  23324. Scene.prototype.addExternalData = function (key, data) {
  23325. if (!this._externalData) {
  23326. this._externalData = new BABYLON.StringDictionary();
  23327. }
  23328. return this._externalData.add(key, data);
  23329. };
  23330. /**
  23331. * Get an externaly attached data from its key
  23332. * @param key the unique key that identifies the data
  23333. * @return the associated data, if present (can be null), or undefined if not present
  23334. */
  23335. Scene.prototype.getExternalData = function (key) {
  23336. if (!this._externalData) {
  23337. return null;
  23338. }
  23339. return this._externalData.get(key);
  23340. };
  23341. /**
  23342. * Get an externaly attached data from its key, create it using a factory if it's not already present
  23343. * @param key the unique key that identifies the data
  23344. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  23345. * @return the associated data, can be null if the factory returned null.
  23346. */
  23347. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  23348. if (!this._externalData) {
  23349. this._externalData = new BABYLON.StringDictionary();
  23350. }
  23351. return this._externalData.getOrAddWithFactory(key, factory);
  23352. };
  23353. /**
  23354. * Remove an externaly attached data from the Engine instance
  23355. * @param key the unique key that identifies the data
  23356. * @return true if the data was successfully removed, false if it doesn't exist
  23357. */
  23358. Scene.prototype.removeExternalData = function (key) {
  23359. return this._externalData.remove(key);
  23360. };
  23361. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  23362. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  23363. if (mesh.showSubMeshesBoundingBox) {
  23364. var boundingInfo = subMesh.getBoundingInfo();
  23365. if (boundingInfo !== null && boundingInfo !== undefined) {
  23366. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  23367. }
  23368. }
  23369. var material = subMesh.getMaterial();
  23370. if (material !== null && material !== undefined) {
  23371. // Render targets
  23372. if (material.getRenderTargetTextures !== undefined) {
  23373. if (this._processedMaterials.indexOf(material) === -1) {
  23374. this._processedMaterials.push(material);
  23375. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  23376. }
  23377. }
  23378. // Dispatch
  23379. this._activeIndices.addCount(subMesh.indexCount, false);
  23380. this._renderingManager.dispatch(subMesh, mesh, material);
  23381. }
  23382. }
  23383. };
  23384. Scene.prototype._isInIntermediateRendering = function () {
  23385. return this._intermediateRendering;
  23386. };
  23387. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  23388. this._activeMeshCandidateProvider = provider;
  23389. };
  23390. Scene.prototype.getActiveMeshCandidateProvider = function () {
  23391. return this._activeMeshCandidateProvider;
  23392. };
  23393. /**
  23394. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  23395. */
  23396. Scene.prototype.freezeActiveMeshes = function () {
  23397. this._evaluateActiveMeshes();
  23398. this._activeMeshesFrozen = true;
  23399. return this;
  23400. };
  23401. /**
  23402. * Use this function to restart evaluating active meshes on every frame
  23403. */
  23404. Scene.prototype.unfreezeActiveMeshes = function () {
  23405. this._activeMeshesFrozen = false;
  23406. return this;
  23407. };
  23408. Scene.prototype._evaluateActiveMeshes = function () {
  23409. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  23410. return;
  23411. }
  23412. if (!this.activeCamera) {
  23413. return;
  23414. }
  23415. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  23416. this.activeCamera._activeMeshes.reset();
  23417. this._activeMeshes.reset();
  23418. this._renderingManager.reset();
  23419. this._processedMaterials.reset();
  23420. this._activeParticleSystems.reset();
  23421. this._activeSkeletons.reset();
  23422. this._softwareSkinnedMeshes.reset();
  23423. if (this._boundingBoxRenderer) {
  23424. this._boundingBoxRenderer.reset();
  23425. }
  23426. // Meshes
  23427. var meshes;
  23428. var len;
  23429. var checkIsEnabled = true;
  23430. // Determine mesh candidates
  23431. if (this._activeMeshCandidateProvider !== undefined) {
  23432. // Use _activeMeshCandidateProvider
  23433. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  23434. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  23435. if (meshes !== undefined) {
  23436. len = meshes.length;
  23437. }
  23438. else {
  23439. len = 0;
  23440. }
  23441. }
  23442. else if (this._selectionOctree !== undefined) {
  23443. // Octree
  23444. var selection = this._selectionOctree.select(this._frustumPlanes);
  23445. meshes = selection.data;
  23446. len = selection.length;
  23447. }
  23448. else {
  23449. // Full scene traversal
  23450. len = this.meshes.length;
  23451. meshes = this.meshes;
  23452. }
  23453. // Check each mesh
  23454. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  23455. mesh = meshes[meshIndex];
  23456. if (mesh.isBlocked) {
  23457. continue;
  23458. }
  23459. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  23460. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  23461. continue;
  23462. }
  23463. mesh.computeWorldMatrix();
  23464. // Intersections
  23465. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  23466. this._meshesForIntersections.pushNoDuplicate(mesh);
  23467. }
  23468. // Switch to current LOD
  23469. meshLOD = mesh.getLOD(this.activeCamera);
  23470. if (meshLOD === undefined || meshLOD === null) {
  23471. continue;
  23472. }
  23473. mesh._preActivate();
  23474. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  23475. this._activeMeshes.push(mesh);
  23476. this.activeCamera._activeMeshes.push(mesh);
  23477. mesh._activate(this._renderId);
  23478. if (meshLOD !== mesh) {
  23479. meshLOD._activate(this._renderId);
  23480. }
  23481. this._activeMesh(mesh, meshLOD);
  23482. }
  23483. }
  23484. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  23485. // Particle systems
  23486. if (this.particlesEnabled) {
  23487. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  23488. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  23489. var particleSystem = this.particleSystems[particleIndex];
  23490. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  23491. continue;
  23492. }
  23493. var emitter = particleSystem.emitter;
  23494. if (!emitter.position || emitter.isEnabled()) {
  23495. this._activeParticleSystems.push(particleSystem);
  23496. particleSystem.animate();
  23497. this._renderingManager.dispatchParticles(particleSystem);
  23498. }
  23499. }
  23500. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  23501. }
  23502. };
  23503. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  23504. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  23505. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  23506. mesh.skeleton.prepare();
  23507. }
  23508. if (!mesh.computeBonesUsingShaders) {
  23509. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  23510. }
  23511. }
  23512. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  23513. var boundingInfo = sourceMesh.getBoundingInfo();
  23514. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  23515. }
  23516. if (mesh !== undefined && mesh !== null
  23517. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  23518. // Submeshes Octrees
  23519. var len;
  23520. var subMeshes;
  23521. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  23522. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  23523. len = intersections.length;
  23524. subMeshes = intersections.data;
  23525. }
  23526. else {
  23527. subMeshes = mesh.subMeshes;
  23528. len = subMeshes.length;
  23529. }
  23530. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  23531. subMesh = subMeshes[subIndex];
  23532. this._evaluateSubMesh(subMesh, mesh);
  23533. }
  23534. }
  23535. };
  23536. Scene.prototype.updateTransformMatrix = function (force) {
  23537. if (!this.activeCamera) {
  23538. return;
  23539. }
  23540. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  23541. };
  23542. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  23543. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  23544. };
  23545. Scene.prototype._renderForCamera = function (camera) {
  23546. if (camera && camera._skipRendering) {
  23547. return;
  23548. }
  23549. var engine = this._engine;
  23550. this.activeCamera = camera;
  23551. if (!this.activeCamera)
  23552. throw new Error("Active camera not set");
  23553. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  23554. // Viewport
  23555. engine.setViewport(this.activeCamera.viewport);
  23556. // Camera
  23557. this.resetCachedMaterial();
  23558. this._renderId++;
  23559. this.activeCamera.update();
  23560. this.updateTransformMatrix();
  23561. if (camera._alternateCamera) {
  23562. this.updateAlternateTransformMatrix(camera._alternateCamera);
  23563. this._alternateRendering = true;
  23564. }
  23565. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  23566. // Meshes
  23567. this._evaluateActiveMeshes();
  23568. // Software skinning
  23569. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  23570. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  23571. mesh.applySkeleton(mesh.skeleton);
  23572. }
  23573. // Render targets
  23574. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  23575. var needsRestoreFrameBuffer = false;
  23576. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  23577. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  23578. }
  23579. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  23580. this._intermediateRendering = true;
  23581. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  23582. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  23583. var renderTarget = this._renderTargets.data[renderIndex];
  23584. if (renderTarget._shouldRender()) {
  23585. this._renderId++;
  23586. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  23587. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  23588. }
  23589. }
  23590. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  23591. this._intermediateRendering = false;
  23592. this._renderId++;
  23593. needsRestoreFrameBuffer = true; // Restore back buffer
  23594. }
  23595. // Render EffecttLayer Texture
  23596. var stencilState = this._engine.getStencilBuffer();
  23597. var renderEffects = false;
  23598. var needStencil = false;
  23599. if (this.renderTargetsEnabled && this.effectLayers && this.effectLayers.length > 0) {
  23600. this._intermediateRendering = true;
  23601. for (var i = 0; i < this.effectLayers.length; i++) {
  23602. var effectLayer = this.effectLayers[i];
  23603. if (effectLayer.shouldRender() &&
  23604. (!effectLayer.camera ||
  23605. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  23606. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  23607. renderEffects = true;
  23608. needStencil = needStencil || effectLayer.needStencil();
  23609. var renderTarget = effectLayer._mainTexture;
  23610. if (renderTarget._shouldRender()) {
  23611. this._renderId++;
  23612. renderTarget.render(false, false);
  23613. needsRestoreFrameBuffer = true;
  23614. }
  23615. }
  23616. }
  23617. this._intermediateRendering = false;
  23618. this._renderId++;
  23619. }
  23620. if (needsRestoreFrameBuffer) {
  23621. engine.restoreDefaultFramebuffer(); // Restore back buffer
  23622. }
  23623. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  23624. // Prepare Frame
  23625. this.postProcessManager._prepareFrame();
  23626. // Backgrounds
  23627. var layerIndex;
  23628. var layer;
  23629. if (this.layers.length) {
  23630. engine.setDepthBuffer(false);
  23631. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  23632. layer = this.layers[layerIndex];
  23633. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  23634. layer.render();
  23635. }
  23636. }
  23637. engine.setDepthBuffer(true);
  23638. }
  23639. // Activate effect Layer stencil
  23640. if (needStencil) {
  23641. this._engine.setStencilBuffer(true);
  23642. }
  23643. // Render
  23644. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  23645. this._renderingManager.render(null, null, true, true);
  23646. this.onAfterDrawPhaseObservable.notifyObservers(this);
  23647. // Restore effect Layer stencil
  23648. if (needStencil) {
  23649. this._engine.setStencilBuffer(stencilState);
  23650. }
  23651. // Bounding boxes
  23652. if (this._boundingBoxRenderer) {
  23653. this._boundingBoxRenderer.render();
  23654. }
  23655. // Lens flares
  23656. if (this.lensFlaresEnabled) {
  23657. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  23658. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  23659. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  23660. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  23661. lensFlareSystem.render();
  23662. }
  23663. }
  23664. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  23665. }
  23666. // Foregrounds
  23667. if (this.layers.length) {
  23668. engine.setDepthBuffer(false);
  23669. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  23670. layer = this.layers[layerIndex];
  23671. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  23672. layer.render();
  23673. }
  23674. }
  23675. engine.setDepthBuffer(true);
  23676. }
  23677. // Effect Layer
  23678. if (renderEffects) {
  23679. engine.setDepthBuffer(false);
  23680. for (var i = 0; i < this.effectLayers.length; i++) {
  23681. if (this.effectLayers[i].shouldRender()) {
  23682. this.effectLayers[i].render();
  23683. }
  23684. }
  23685. engine.setDepthBuffer(true);
  23686. }
  23687. // Finalize frame
  23688. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  23689. // Reset some special arrays
  23690. this._renderTargets.reset();
  23691. this._alternateRendering = false;
  23692. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  23693. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  23694. };
  23695. Scene.prototype._processSubCameras = function (camera) {
  23696. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  23697. this._renderForCamera(camera);
  23698. return;
  23699. }
  23700. // Update camera
  23701. if (this.activeCamera) {
  23702. this.activeCamera.update();
  23703. }
  23704. // rig cameras
  23705. for (var index = 0; index < camera._rigCameras.length; index++) {
  23706. this._renderForCamera(camera._rigCameras[index]);
  23707. }
  23708. this.activeCamera = camera;
  23709. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  23710. };
  23711. Scene.prototype._checkIntersections = function () {
  23712. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  23713. var sourceMesh = this._meshesForIntersections.data[index];
  23714. if (!sourceMesh.actionManager) {
  23715. continue;
  23716. }
  23717. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  23718. var action = sourceMesh.actionManager.actions[actionIndex];
  23719. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  23720. var parameters = action.getTriggerParameter();
  23721. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  23722. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  23723. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  23724. if (areIntersecting && currentIntersectionInProgress === -1) {
  23725. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  23726. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  23727. sourceMesh._intersectionsInProgress.push(otherMesh);
  23728. }
  23729. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  23730. sourceMesh._intersectionsInProgress.push(otherMesh);
  23731. }
  23732. }
  23733. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  23734. //They intersected, and now they don't.
  23735. //is this trigger an exit trigger? execute an event.
  23736. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  23737. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  23738. }
  23739. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  23740. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  23741. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  23742. }
  23743. }
  23744. }
  23745. }
  23746. }
  23747. };
  23748. Scene.prototype.render = function () {
  23749. if (this.isDisposed) {
  23750. return;
  23751. }
  23752. this._activeParticles.fetchNewFrame();
  23753. this._totalVertices.fetchNewFrame();
  23754. this._activeIndices.fetchNewFrame();
  23755. this._activeBones.fetchNewFrame();
  23756. this._meshesForIntersections.reset();
  23757. this.resetCachedMaterial();
  23758. this.onBeforeAnimationsObservable.notifyObservers(this);
  23759. // Actions
  23760. if (this.actionManager) {
  23761. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  23762. }
  23763. //Simplification Queue
  23764. if (this.simplificationQueue && !this.simplificationQueue.running) {
  23765. this.simplificationQueue.executeNext();
  23766. }
  23767. if (this._engine.isDeterministicLockStep()) {
  23768. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  23769. var defaultFPS = (60.0 / 1000.0);
  23770. var defaultFrameTime = 1000 / 60; // frame time in MS
  23771. if (this._physicsEngine) {
  23772. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  23773. }
  23774. var stepsTaken = 0;
  23775. var maxSubSteps = this._engine.getLockstepMaxSteps();
  23776. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  23777. internalSteps = Math.min(internalSteps, maxSubSteps);
  23778. do {
  23779. this.onBeforeStepObservable.notifyObservers(this);
  23780. // Animations
  23781. this._animationRatio = defaultFrameTime * defaultFPS;
  23782. this._animate();
  23783. this.onAfterAnimationsObservable.notifyObservers(this);
  23784. // Physics
  23785. if (this._physicsEngine) {
  23786. this.onBeforePhysicsObservable.notifyObservers(this);
  23787. this._physicsEngine._step(defaultFrameTime / 1000);
  23788. this.onAfterPhysicsObservable.notifyObservers(this);
  23789. }
  23790. this.onAfterStepObservable.notifyObservers(this);
  23791. this._currentStepId++;
  23792. stepsTaken++;
  23793. deltaTime -= defaultFrameTime;
  23794. } while (deltaTime > 0 && stepsTaken < internalSteps);
  23795. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  23796. }
  23797. else {
  23798. // Animations
  23799. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  23800. this._animationRatio = deltaTime * (60.0 / 1000.0);
  23801. this._animate();
  23802. this.onAfterAnimationsObservable.notifyObservers(this);
  23803. // Physics
  23804. if (this._physicsEngine) {
  23805. this.onBeforePhysicsObservable.notifyObservers(this);
  23806. this._physicsEngine._step(deltaTime / 1000.0);
  23807. this.onAfterPhysicsObservable.notifyObservers(this);
  23808. }
  23809. }
  23810. // update gamepad manager
  23811. if (this._gamepadManager && this._gamepadManager._isMonitoring) {
  23812. this._gamepadManager._checkGamepadsStatus();
  23813. }
  23814. // Before render
  23815. this.onBeforeRenderObservable.notifyObservers(this);
  23816. // Customs render targets
  23817. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  23818. var engine = this.getEngine();
  23819. var currentActiveCamera = this.activeCamera;
  23820. if (this.renderTargetsEnabled) {
  23821. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  23822. this._intermediateRendering = true;
  23823. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  23824. var renderTarget = this.customRenderTargets[customIndex];
  23825. if (renderTarget._shouldRender()) {
  23826. this._renderId++;
  23827. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  23828. if (!this.activeCamera)
  23829. throw new Error("Active camera not set");
  23830. // Viewport
  23831. engine.setViewport(this.activeCamera.viewport);
  23832. // Camera
  23833. this.updateTransformMatrix();
  23834. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  23835. }
  23836. }
  23837. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  23838. this._intermediateRendering = false;
  23839. this._renderId++;
  23840. }
  23841. // Restore back buffer
  23842. if (this.customRenderTargets.length > 0) {
  23843. engine.restoreDefaultFramebuffer();
  23844. }
  23845. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  23846. this.activeCamera = currentActiveCamera;
  23847. // Procedural textures
  23848. if (this.proceduralTexturesEnabled) {
  23849. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  23850. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  23851. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  23852. if (proceduralTexture._shouldRender()) {
  23853. proceduralTexture.render();
  23854. }
  23855. }
  23856. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  23857. }
  23858. // Clear
  23859. if (this.autoClearDepthAndStencil || this.autoClear) {
  23860. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  23861. }
  23862. // Shadows
  23863. if (this.shadowsEnabled) {
  23864. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  23865. var light = this.lights[lightIndex];
  23866. var shadowGenerator = light.getShadowGenerator();
  23867. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  23868. var shadowMap = (shadowGenerator.getShadowMap());
  23869. if (this.textures.indexOf(shadowMap) !== -1) {
  23870. this._renderTargets.push(shadowMap);
  23871. }
  23872. }
  23873. }
  23874. }
  23875. // Depth renderer
  23876. if (this._depthRenderer) {
  23877. this._renderTargets.push(this._depthRenderer.getDepthMap());
  23878. }
  23879. // Geometry renderer
  23880. if (this._geometryBufferRenderer) {
  23881. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  23882. }
  23883. // RenderPipeline
  23884. if (this._postProcessRenderPipelineManager) {
  23885. this._postProcessRenderPipelineManager.update();
  23886. }
  23887. // Multi-cameras?
  23888. if (this.activeCameras.length > 0) {
  23889. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  23890. if (cameraIndex > 0) {
  23891. this._engine.clear(null, false, true, true);
  23892. }
  23893. this._processSubCameras(this.activeCameras[cameraIndex]);
  23894. }
  23895. }
  23896. else {
  23897. if (!this.activeCamera) {
  23898. throw new Error("No camera defined");
  23899. }
  23900. this._processSubCameras(this.activeCamera);
  23901. }
  23902. // Intersection checks
  23903. this._checkIntersections();
  23904. // Update the audio listener attached to the camera
  23905. if (BABYLON.AudioEngine) {
  23906. this._updateAudioParameters();
  23907. }
  23908. // After render
  23909. if (this.afterRender) {
  23910. this.afterRender();
  23911. }
  23912. this.onAfterRenderObservable.notifyObservers(this);
  23913. // Cleaning
  23914. for (var index = 0; index < this._toBeDisposed.length; index++) {
  23915. var data = this._toBeDisposed.data[index];
  23916. if (data) {
  23917. data.dispose();
  23918. }
  23919. this._toBeDisposed[index] = null;
  23920. }
  23921. this._toBeDisposed.reset();
  23922. if (this.dumpNextRenderTargets) {
  23923. this.dumpNextRenderTargets = false;
  23924. }
  23925. this._activeBones.addCount(0, true);
  23926. this._activeIndices.addCount(0, true);
  23927. this._activeParticles.addCount(0, true);
  23928. };
  23929. Scene.prototype._updateAudioParameters = function () {
  23930. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  23931. return;
  23932. }
  23933. var listeningCamera;
  23934. var audioEngine = BABYLON.Engine.audioEngine;
  23935. if (this.activeCameras.length > 0) {
  23936. listeningCamera = this.activeCameras[0];
  23937. }
  23938. else {
  23939. listeningCamera = this.activeCamera;
  23940. }
  23941. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  23942. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  23943. // for VR cameras
  23944. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  23945. listeningCamera = listeningCamera.rigCameras[0];
  23946. }
  23947. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  23948. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  23949. cameraDirection.normalize();
  23950. // To avoid some errors on GearVR
  23951. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  23952. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  23953. }
  23954. var i;
  23955. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  23956. var sound = this.mainSoundTrack.soundCollection[i];
  23957. if (sound.useCustomAttenuation) {
  23958. sound.updateDistanceFromListener();
  23959. }
  23960. }
  23961. for (i = 0; i < this.soundTracks.length; i++) {
  23962. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  23963. sound = this.soundTracks[i].soundCollection[j];
  23964. if (sound.useCustomAttenuation) {
  23965. sound.updateDistanceFromListener();
  23966. }
  23967. }
  23968. }
  23969. }
  23970. };
  23971. Object.defineProperty(Scene.prototype, "audioEnabled", {
  23972. // Audio
  23973. get: function () {
  23974. return this._audioEnabled;
  23975. },
  23976. set: function (value) {
  23977. this._audioEnabled = value;
  23978. if (BABYLON.AudioEngine) {
  23979. if (this._audioEnabled) {
  23980. this._enableAudio();
  23981. }
  23982. else {
  23983. this._disableAudio();
  23984. }
  23985. }
  23986. },
  23987. enumerable: true,
  23988. configurable: true
  23989. });
  23990. Scene.prototype._disableAudio = function () {
  23991. var i;
  23992. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  23993. this.mainSoundTrack.soundCollection[i].pause();
  23994. }
  23995. for (i = 0; i < this.soundTracks.length; i++) {
  23996. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  23997. this.soundTracks[i].soundCollection[j].pause();
  23998. }
  23999. }
  24000. };
  24001. Scene.prototype._enableAudio = function () {
  24002. var i;
  24003. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  24004. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  24005. this.mainSoundTrack.soundCollection[i].play();
  24006. }
  24007. }
  24008. for (i = 0; i < this.soundTracks.length; i++) {
  24009. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  24010. if (this.soundTracks[i].soundCollection[j].isPaused) {
  24011. this.soundTracks[i].soundCollection[j].play();
  24012. }
  24013. }
  24014. }
  24015. };
  24016. Object.defineProperty(Scene.prototype, "headphone", {
  24017. get: function () {
  24018. return this._headphone;
  24019. },
  24020. set: function (value) {
  24021. this._headphone = value;
  24022. if (BABYLON.AudioEngine) {
  24023. if (this._headphone) {
  24024. this._switchAudioModeForHeadphones();
  24025. }
  24026. else {
  24027. this._switchAudioModeForNormalSpeakers();
  24028. }
  24029. }
  24030. },
  24031. enumerable: true,
  24032. configurable: true
  24033. });
  24034. Scene.prototype._switchAudioModeForHeadphones = function () {
  24035. this.mainSoundTrack.switchPanningModelToHRTF();
  24036. for (var i = 0; i < this.soundTracks.length; i++) {
  24037. this.soundTracks[i].switchPanningModelToHRTF();
  24038. }
  24039. };
  24040. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  24041. this.mainSoundTrack.switchPanningModelToEqualPower();
  24042. for (var i = 0; i < this.soundTracks.length; i++) {
  24043. this.soundTracks[i].switchPanningModelToEqualPower();
  24044. }
  24045. };
  24046. Scene.prototype.enableDepthRenderer = function () {
  24047. if (this._depthRenderer) {
  24048. return this._depthRenderer;
  24049. }
  24050. this._depthRenderer = new BABYLON.DepthRenderer(this);
  24051. return this._depthRenderer;
  24052. };
  24053. Scene.prototype.disableDepthRenderer = function () {
  24054. if (!this._depthRenderer) {
  24055. return;
  24056. }
  24057. this._depthRenderer.dispose();
  24058. this._depthRenderer = null;
  24059. };
  24060. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  24061. if (ratio === void 0) { ratio = 1; }
  24062. if (this._geometryBufferRenderer) {
  24063. return this._geometryBufferRenderer;
  24064. }
  24065. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  24066. if (!this._geometryBufferRenderer.isSupported) {
  24067. this._geometryBufferRenderer = null;
  24068. }
  24069. return this._geometryBufferRenderer;
  24070. };
  24071. Scene.prototype.disableGeometryBufferRenderer = function () {
  24072. if (!this._geometryBufferRenderer) {
  24073. return;
  24074. }
  24075. this._geometryBufferRenderer.dispose();
  24076. this._geometryBufferRenderer = null;
  24077. };
  24078. Scene.prototype.freezeMaterials = function () {
  24079. for (var i = 0; i < this.materials.length; i++) {
  24080. this.materials[i].freeze();
  24081. }
  24082. };
  24083. Scene.prototype.unfreezeMaterials = function () {
  24084. for (var i = 0; i < this.materials.length; i++) {
  24085. this.materials[i].unfreeze();
  24086. }
  24087. };
  24088. Scene.prototype.dispose = function () {
  24089. this.beforeRender = null;
  24090. this.afterRender = null;
  24091. this.skeletons = [];
  24092. this.morphTargetManagers = [];
  24093. this.importedMeshesFiles = new Array();
  24094. this.stopAllAnimations();
  24095. this.resetCachedMaterial();
  24096. if (this._depthRenderer) {
  24097. this._depthRenderer.dispose();
  24098. }
  24099. if (this._gamepadManager) {
  24100. this._gamepadManager.dispose();
  24101. this._gamepadManager = null;
  24102. }
  24103. // Smart arrays
  24104. if (this.activeCamera) {
  24105. this.activeCamera._activeMeshes.dispose();
  24106. this.activeCamera = null;
  24107. }
  24108. this._activeMeshes.dispose();
  24109. this._renderingManager.dispose();
  24110. this._processedMaterials.dispose();
  24111. this._activeParticleSystems.dispose();
  24112. this._activeSkeletons.dispose();
  24113. this._softwareSkinnedMeshes.dispose();
  24114. this._renderTargets.dispose();
  24115. if (this._boundingBoxRenderer) {
  24116. this._boundingBoxRenderer.dispose();
  24117. }
  24118. this._meshesForIntersections.dispose();
  24119. this._toBeDisposed.dispose();
  24120. // Abort active requests
  24121. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  24122. var request = _a[_i];
  24123. request.abort();
  24124. }
  24125. // Debug layer
  24126. if (this._debugLayer) {
  24127. this._debugLayer.hide();
  24128. }
  24129. // Events
  24130. this.onDisposeObservable.notifyObservers(this);
  24131. this.onDisposeObservable.clear();
  24132. this.onBeforeRenderObservable.clear();
  24133. this.onAfterRenderObservable.clear();
  24134. this.OnBeforeRenderTargetsRenderObservable.clear();
  24135. this.OnAfterRenderTargetsRenderObservable.clear();
  24136. this.onAfterStepObservable.clear();
  24137. this.onBeforeStepObservable.clear();
  24138. this.onBeforeActiveMeshesEvaluationObservable.clear();
  24139. this.onAfterActiveMeshesEvaluationObservable.clear();
  24140. this.onBeforeParticlesRenderingObservable.clear();
  24141. this.onAfterParticlesRenderingObservable.clear();
  24142. this.onBeforeSpritesRenderingObservable.clear();
  24143. this.onAfterSpritesRenderingObservable.clear();
  24144. this.onBeforeDrawPhaseObservable.clear();
  24145. this.onAfterDrawPhaseObservable.clear();
  24146. this.onBeforePhysicsObservable.clear();
  24147. this.onAfterPhysicsObservable.clear();
  24148. this.onBeforeAnimationsObservable.clear();
  24149. this.onAfterAnimationsObservable.clear();
  24150. this.onDataLoadedObservable.clear();
  24151. this.detachControl();
  24152. // Release sounds & sounds tracks
  24153. if (BABYLON.AudioEngine) {
  24154. this.disposeSounds();
  24155. }
  24156. // VR Helper
  24157. if (this.VRHelper) {
  24158. this.VRHelper.dispose();
  24159. }
  24160. // Detach cameras
  24161. var canvas = this._engine.getRenderingCanvas();
  24162. if (canvas) {
  24163. var index;
  24164. for (index = 0; index < this.cameras.length; index++) {
  24165. this.cameras[index].detachControl(canvas);
  24166. }
  24167. }
  24168. // Release animation groups
  24169. while (this.animationGroups.length) {
  24170. this.animationGroups[0].dispose();
  24171. }
  24172. // Release lights
  24173. while (this.lights.length) {
  24174. this.lights[0].dispose();
  24175. }
  24176. // Release meshes
  24177. while (this.meshes.length) {
  24178. this.meshes[0].dispose(true);
  24179. }
  24180. while (this.transformNodes.length) {
  24181. this.removeTransformNode(this.transformNodes[0]);
  24182. }
  24183. // Release cameras
  24184. while (this.cameras.length) {
  24185. this.cameras[0].dispose();
  24186. }
  24187. // Release materials
  24188. if (this.defaultMaterial) {
  24189. this.defaultMaterial.dispose();
  24190. }
  24191. while (this.multiMaterials.length) {
  24192. this.multiMaterials[0].dispose();
  24193. }
  24194. while (this.materials.length) {
  24195. this.materials[0].dispose();
  24196. }
  24197. // Release particles
  24198. while (this.particleSystems.length) {
  24199. this.particleSystems[0].dispose();
  24200. }
  24201. // Release sprites
  24202. while (this.spriteManagers.length) {
  24203. this.spriteManagers[0].dispose();
  24204. }
  24205. // Release postProcesses
  24206. while (this.postProcesses.length) {
  24207. this.postProcesses[0].dispose();
  24208. }
  24209. // Release layers
  24210. while (this.layers.length) {
  24211. this.layers[0].dispose();
  24212. }
  24213. while (this.effectLayers.length) {
  24214. this.effectLayers[0].dispose();
  24215. }
  24216. // Release textures
  24217. while (this.textures.length) {
  24218. this.textures[0].dispose();
  24219. }
  24220. // Release UBO
  24221. this._sceneUbo.dispose();
  24222. if (this._alternateSceneUbo) {
  24223. this._alternateSceneUbo.dispose();
  24224. }
  24225. // Post-processes
  24226. this.postProcessManager.dispose();
  24227. if (this._postProcessRenderPipelineManager) {
  24228. this._postProcessRenderPipelineManager.dispose();
  24229. }
  24230. // Physics
  24231. if (this._physicsEngine) {
  24232. this.disablePhysicsEngine();
  24233. }
  24234. // Remove from engine
  24235. index = this._engine.scenes.indexOf(this);
  24236. if (index > -1) {
  24237. this._engine.scenes.splice(index, 1);
  24238. }
  24239. this._engine.wipeCaches(true);
  24240. this._isDisposed = true;
  24241. };
  24242. Object.defineProperty(Scene.prototype, "isDisposed", {
  24243. get: function () {
  24244. return this._isDisposed;
  24245. },
  24246. enumerable: true,
  24247. configurable: true
  24248. });
  24249. // Release sounds & sounds tracks
  24250. Scene.prototype.disposeSounds = function () {
  24251. if (!this._mainSoundTrack) {
  24252. return;
  24253. }
  24254. this.mainSoundTrack.dispose();
  24255. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  24256. this.soundTracks[scIndex].dispose();
  24257. }
  24258. };
  24259. // Octrees
  24260. Scene.prototype.getWorldExtends = function () {
  24261. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  24262. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  24263. for (var index = 0; index < this.meshes.length; index++) {
  24264. var mesh = this.meshes[index];
  24265. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  24266. continue;
  24267. }
  24268. mesh.computeWorldMatrix(true);
  24269. var boundingInfo = mesh.getBoundingInfo();
  24270. var minBox = boundingInfo.boundingBox.minimumWorld;
  24271. var maxBox = boundingInfo.boundingBox.maximumWorld;
  24272. BABYLON.Tools.CheckExtends(minBox, min, max);
  24273. BABYLON.Tools.CheckExtends(maxBox, min, max);
  24274. }
  24275. return {
  24276. min: min,
  24277. max: max
  24278. };
  24279. };
  24280. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  24281. if (maxCapacity === void 0) { maxCapacity = 64; }
  24282. if (maxDepth === void 0) { maxDepth = 2; }
  24283. if (!this._selectionOctree) {
  24284. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  24285. }
  24286. var worldExtends = this.getWorldExtends();
  24287. // Update octree
  24288. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  24289. return this._selectionOctree;
  24290. };
  24291. // Picking
  24292. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  24293. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  24294. var result = BABYLON.Ray.Zero();
  24295. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  24296. return result;
  24297. };
  24298. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  24299. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  24300. var engine = this._engine;
  24301. if (!camera) {
  24302. if (!this.activeCamera)
  24303. throw new Error("Active camera not set");
  24304. camera = this.activeCamera;
  24305. }
  24306. var cameraViewport = camera.viewport;
  24307. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  24308. // Moving coordinates to local viewport world
  24309. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  24310. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  24311. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  24312. return this;
  24313. };
  24314. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  24315. var result = BABYLON.Ray.Zero();
  24316. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  24317. return result;
  24318. };
  24319. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  24320. if (!BABYLON.PickingInfo) {
  24321. return this;
  24322. }
  24323. var engine = this._engine;
  24324. if (!camera) {
  24325. if (!this.activeCamera)
  24326. throw new Error("Active camera not set");
  24327. camera = this.activeCamera;
  24328. }
  24329. var cameraViewport = camera.viewport;
  24330. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  24331. var identity = BABYLON.Matrix.Identity();
  24332. // Moving coordinates to local viewport world
  24333. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  24334. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  24335. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  24336. return this;
  24337. };
  24338. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  24339. if (!BABYLON.PickingInfo) {
  24340. return null;
  24341. }
  24342. var pickingInfo = null;
  24343. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  24344. var mesh = this.meshes[meshIndex];
  24345. if (predicate) {
  24346. if (!predicate(mesh)) {
  24347. continue;
  24348. }
  24349. }
  24350. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  24351. continue;
  24352. }
  24353. var world = mesh.getWorldMatrix();
  24354. var ray = rayFunction(world);
  24355. var result = mesh.intersects(ray, fastCheck);
  24356. if (!result || !result.hit)
  24357. continue;
  24358. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  24359. continue;
  24360. pickingInfo = result;
  24361. if (fastCheck) {
  24362. break;
  24363. }
  24364. }
  24365. return pickingInfo || new BABYLON.PickingInfo();
  24366. };
  24367. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  24368. if (!BABYLON.PickingInfo) {
  24369. return null;
  24370. }
  24371. var pickingInfos = new Array();
  24372. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  24373. var mesh = this.meshes[meshIndex];
  24374. if (predicate) {
  24375. if (!predicate(mesh)) {
  24376. continue;
  24377. }
  24378. }
  24379. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  24380. continue;
  24381. }
  24382. var world = mesh.getWorldMatrix();
  24383. var ray = rayFunction(world);
  24384. var result = mesh.intersects(ray, false);
  24385. if (!result || !result.hit)
  24386. continue;
  24387. pickingInfos.push(result);
  24388. }
  24389. return pickingInfos;
  24390. };
  24391. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  24392. if (!BABYLON.PickingInfo) {
  24393. return null;
  24394. }
  24395. var pickingInfo = null;
  24396. if (!camera) {
  24397. if (!this.activeCamera) {
  24398. return null;
  24399. }
  24400. camera = this.activeCamera;
  24401. }
  24402. if (this.spriteManagers.length > 0) {
  24403. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  24404. var spriteManager = this.spriteManagers[spriteIndex];
  24405. if (!spriteManager.isPickable) {
  24406. continue;
  24407. }
  24408. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  24409. if (!result || !result.hit)
  24410. continue;
  24411. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  24412. continue;
  24413. pickingInfo = result;
  24414. if (fastCheck) {
  24415. break;
  24416. }
  24417. }
  24418. }
  24419. return pickingInfo || new BABYLON.PickingInfo();
  24420. };
  24421. /** Launch a ray to try to pick a mesh in the scene
  24422. * @param x position on screen
  24423. * @param y position on screen
  24424. * @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
  24425. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  24426. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  24427. */
  24428. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  24429. var _this = this;
  24430. if (!BABYLON.PickingInfo) {
  24431. return null;
  24432. }
  24433. return this._internalPick(function (world) {
  24434. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  24435. return _this._tempPickingRay;
  24436. }, predicate, fastCheck);
  24437. };
  24438. /** Launch a ray to try to pick a sprite in the scene
  24439. * @param x position on screen
  24440. * @param y position on screen
  24441. * @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
  24442. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  24443. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  24444. */
  24445. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  24446. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  24447. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  24448. };
  24449. /** Use the given ray to pick a mesh in the scene
  24450. * @param ray The ray to use to pick meshes
  24451. * @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
  24452. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  24453. */
  24454. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  24455. var _this = this;
  24456. return this._internalPick(function (world) {
  24457. if (!_this._pickWithRayInverseMatrix) {
  24458. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  24459. }
  24460. world.invertToRef(_this._pickWithRayInverseMatrix);
  24461. if (!_this._cachedRayForTransform) {
  24462. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  24463. }
  24464. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  24465. return _this._cachedRayForTransform;
  24466. }, predicate, fastCheck);
  24467. };
  24468. /**
  24469. * Launch a ray to try to pick a mesh in the scene
  24470. * @param x X position on screen
  24471. * @param y Y position on screen
  24472. * @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
  24473. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  24474. */
  24475. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  24476. var _this = this;
  24477. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  24478. };
  24479. /**
  24480. * Launch a ray to try to pick a mesh in the scene
  24481. * @param ray Ray to use
  24482. * @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
  24483. */
  24484. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  24485. var _this = this;
  24486. return this._internalMultiPick(function (world) {
  24487. if (!_this._pickWithRayInverseMatrix) {
  24488. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  24489. }
  24490. world.invertToRef(_this._pickWithRayInverseMatrix);
  24491. if (!_this._cachedRayForTransform) {
  24492. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  24493. }
  24494. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  24495. return _this._cachedRayForTransform;
  24496. }, predicate);
  24497. };
  24498. Scene.prototype.setPointerOverMesh = function (mesh) {
  24499. if (this._pointerOverMesh === mesh) {
  24500. return;
  24501. }
  24502. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  24503. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  24504. }
  24505. this._pointerOverMesh = mesh;
  24506. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  24507. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  24508. }
  24509. };
  24510. Scene.prototype.getPointerOverMesh = function () {
  24511. return this._pointerOverMesh;
  24512. };
  24513. Scene.prototype.setPointerOverSprite = function (sprite) {
  24514. if (this._pointerOverSprite === sprite) {
  24515. return;
  24516. }
  24517. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  24518. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  24519. }
  24520. this._pointerOverSprite = sprite;
  24521. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  24522. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  24523. }
  24524. };
  24525. Scene.prototype.getPointerOverSprite = function () {
  24526. return this._pointerOverSprite;
  24527. };
  24528. // Physics
  24529. Scene.prototype.getPhysicsEngine = function () {
  24530. return this._physicsEngine;
  24531. };
  24532. /**
  24533. * Enables physics to the current scene
  24534. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  24535. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  24536. * @return {boolean} was the physics engine initialized
  24537. */
  24538. Scene.prototype.enablePhysics = function (gravity, plugin) {
  24539. if (gravity === void 0) { gravity = null; }
  24540. if (this._physicsEngine) {
  24541. return true;
  24542. }
  24543. try {
  24544. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  24545. return true;
  24546. }
  24547. catch (e) {
  24548. BABYLON.Tools.Error(e.message);
  24549. return false;
  24550. }
  24551. };
  24552. Scene.prototype.disablePhysicsEngine = function () {
  24553. if (!this._physicsEngine) {
  24554. return;
  24555. }
  24556. this._physicsEngine.dispose();
  24557. this._physicsEngine = null;
  24558. };
  24559. Scene.prototype.isPhysicsEnabled = function () {
  24560. return this._physicsEngine !== undefined;
  24561. };
  24562. Scene.prototype.deleteCompoundImpostor = function (compound) {
  24563. var mesh = compound.parts[0].mesh;
  24564. if (mesh.physicsImpostor) {
  24565. mesh.physicsImpostor.dispose();
  24566. mesh.physicsImpostor = null;
  24567. }
  24568. };
  24569. // Misc.
  24570. Scene.prototype._rebuildGeometries = function () {
  24571. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  24572. var geometry = _a[_i];
  24573. geometry._rebuild();
  24574. }
  24575. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  24576. var mesh = _c[_b];
  24577. mesh._rebuild();
  24578. }
  24579. if (this.postProcessManager) {
  24580. this.postProcessManager._rebuild();
  24581. }
  24582. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  24583. var layer = _e[_d];
  24584. layer._rebuild();
  24585. }
  24586. for (var _f = 0, _g = this.effectLayers; _f < _g.length; _f++) {
  24587. var effectLayer = _g[_f];
  24588. effectLayer._rebuild();
  24589. }
  24590. if (this._boundingBoxRenderer) {
  24591. this._boundingBoxRenderer._rebuild();
  24592. }
  24593. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  24594. var system = _j[_h];
  24595. system.rebuild();
  24596. }
  24597. if (this._postProcessRenderPipelineManager) {
  24598. this._postProcessRenderPipelineManager._rebuild();
  24599. }
  24600. };
  24601. Scene.prototype._rebuildTextures = function () {
  24602. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  24603. var texture = _a[_i];
  24604. texture._rebuild();
  24605. }
  24606. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24607. };
  24608. /**
  24609. * Creates a default light for the scene.
  24610. * @param replace Whether to replace the existing lights in the scene.
  24611. */
  24612. Scene.prototype.createDefaultLight = function (replace) {
  24613. if (replace === void 0) { replace = false; }
  24614. // Dispose existing light in replace mode.
  24615. if (replace) {
  24616. if (this.lights) {
  24617. for (var i = 0; i < this.lights.length; i++) {
  24618. this.lights[i].dispose();
  24619. }
  24620. }
  24621. }
  24622. // Light
  24623. if (this.lights.length === 0) {
  24624. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  24625. }
  24626. };
  24627. /**
  24628. * Creates a default camera for the scene.
  24629. * @param createArcRotateCamera Whether to create an arc rotate or a free camera.
  24630. * @param replace Whether to replace the existing active camera in the scene.
  24631. * @param attachCameraControls Whether to attach camera controls to the canvas.
  24632. */
  24633. Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  24634. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  24635. if (replace === void 0) { replace = false; }
  24636. if (attachCameraControls === void 0) { attachCameraControls = false; }
  24637. // Dispose existing camera in replace mode.
  24638. if (replace) {
  24639. if (this.activeCamera) {
  24640. this.activeCamera.dispose();
  24641. this.activeCamera = null;
  24642. }
  24643. }
  24644. // Camera
  24645. if (!this.activeCamera) {
  24646. var worldExtends = this.getWorldExtends();
  24647. var worldSize = worldExtends.max.subtract(worldExtends.min);
  24648. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  24649. var camera;
  24650. var radius = worldSize.length() * 1.5;
  24651. // empty scene scenario!
  24652. if (!isFinite(radius)) {
  24653. radius = 1;
  24654. worldCenter.copyFromFloats(0, 0, 0);
  24655. }
  24656. if (createArcRotateCamera) {
  24657. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  24658. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  24659. arcRotateCamera.wheelPrecision = 100 / radius;
  24660. camera = arcRotateCamera;
  24661. }
  24662. else {
  24663. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  24664. freeCamera.setTarget(worldCenter);
  24665. camera = freeCamera;
  24666. }
  24667. camera.minZ = radius * 0.01;
  24668. camera.maxZ = radius * 1000;
  24669. camera.speed = radius * 0.2;
  24670. this.activeCamera = camera;
  24671. var canvas = this.getEngine().getRenderingCanvas();
  24672. if (attachCameraControls && canvas) {
  24673. camera.attachControl(canvas);
  24674. }
  24675. }
  24676. };
  24677. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  24678. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  24679. if (replace === void 0) { replace = false; }
  24680. if (attachCameraControls === void 0) { attachCameraControls = false; }
  24681. this.createDefaultLight(replace);
  24682. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  24683. };
  24684. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur) {
  24685. if (pbr === void 0) { pbr = false; }
  24686. if (scale === void 0) { scale = 1000; }
  24687. if (blur === void 0) { blur = 0; }
  24688. if (environmentTexture) {
  24689. this.environmentTexture = environmentTexture;
  24690. }
  24691. if (!this.environmentTexture) {
  24692. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  24693. return null;
  24694. }
  24695. // Skybox
  24696. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  24697. if (pbr) {
  24698. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  24699. hdrSkyboxMaterial.backFaceCulling = false;
  24700. hdrSkyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  24701. if (hdrSkyboxMaterial.reflectionTexture) {
  24702. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  24703. }
  24704. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  24705. hdrSkyboxMaterial.disableLighting = true;
  24706. hdrSkyboxMaterial.twoSidedLighting = true;
  24707. hdrSkybox.infiniteDistance = true;
  24708. hdrSkybox.material = hdrSkyboxMaterial;
  24709. }
  24710. else {
  24711. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  24712. skyboxMaterial.backFaceCulling = false;
  24713. skyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  24714. if (skyboxMaterial.reflectionTexture) {
  24715. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  24716. }
  24717. skyboxMaterial.disableLighting = true;
  24718. hdrSkybox.infiniteDistance = true;
  24719. hdrSkybox.material = skyboxMaterial;
  24720. }
  24721. return hdrSkybox;
  24722. };
  24723. Scene.prototype.createDefaultEnvironment = function (options) {
  24724. if (BABYLON.EnvironmentHelper) {
  24725. return new BABYLON.EnvironmentHelper(options, this);
  24726. }
  24727. return null;
  24728. };
  24729. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  24730. if (webVROptions === void 0) { webVROptions = {}; }
  24731. return new BABYLON.VRExperienceHelper(this, webVROptions);
  24732. };
  24733. // Tags
  24734. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  24735. if (tagsQuery === undefined) {
  24736. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  24737. return list;
  24738. }
  24739. var listByTags = [];
  24740. forEach = forEach || (function (item) { return; });
  24741. for (var i in list) {
  24742. var item = list[i];
  24743. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  24744. listByTags.push(item);
  24745. forEach(item);
  24746. }
  24747. }
  24748. return listByTags;
  24749. };
  24750. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  24751. return this._getByTags(this.meshes, tagsQuery, forEach);
  24752. };
  24753. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  24754. return this._getByTags(this.cameras, tagsQuery, forEach);
  24755. };
  24756. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  24757. return this._getByTags(this.lights, tagsQuery, forEach);
  24758. };
  24759. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  24760. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  24761. };
  24762. /**
  24763. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  24764. * This allowed control for front to back rendering or reversly depending of the special needs.
  24765. *
  24766. * @param renderingGroupId The rendering group id corresponding to its index
  24767. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  24768. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  24769. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  24770. */
  24771. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  24772. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  24773. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  24774. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  24775. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  24776. };
  24777. /**
  24778. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  24779. *
  24780. * @param renderingGroupId The rendering group id corresponding to its index
  24781. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  24782. * @param depth Automatically clears depth between groups if true and autoClear is true.
  24783. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  24784. */
  24785. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  24786. if (depth === void 0) { depth = true; }
  24787. if (stencil === void 0) { stencil = true; }
  24788. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  24789. };
  24790. /**
  24791. * Will flag all materials as dirty to trigger new shader compilation
  24792. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  24793. */
  24794. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  24795. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  24796. var material = _a[_i];
  24797. if (predicate && !predicate(material)) {
  24798. continue;
  24799. }
  24800. material.markAsDirty(flag);
  24801. }
  24802. };
  24803. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  24804. var _this = this;
  24805. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  24806. this._activeRequests.push(request);
  24807. request.onCompleteObservable.add(function (request) {
  24808. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  24809. });
  24810. return request;
  24811. };
  24812. /** @ignore */
  24813. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  24814. var _this = this;
  24815. return new Promise(function (resolve, reject) {
  24816. _this._loadFile(url, function (data) {
  24817. resolve(data);
  24818. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  24819. reject(exception);
  24820. });
  24821. });
  24822. };
  24823. // Statics
  24824. Scene._FOGMODE_NONE = 0;
  24825. Scene._FOGMODE_EXP = 1;
  24826. Scene._FOGMODE_EXP2 = 2;
  24827. Scene._FOGMODE_LINEAR = 3;
  24828. Scene._uniqueIdCounter = 0;
  24829. Scene.MinDeltaTime = 1.0;
  24830. Scene.MaxDeltaTime = 1000.0;
  24831. /** The distance in pixel that you have to move to prevent some events */
  24832. Scene.DragMovementThreshold = 10; // in pixels
  24833. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  24834. Scene.LongPressDelay = 500; // in milliseconds
  24835. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  24836. Scene.DoubleClickDelay = 300; // in milliseconds
  24837. /** If you need to check double click without raising a single click at first click, enable this flag */
  24838. Scene.ExclusiveDoubleClickMode = false;
  24839. return Scene;
  24840. }());
  24841. BABYLON.Scene = Scene;
  24842. })(BABYLON || (BABYLON = {}));
  24843. //# sourceMappingURL=babylon.scene.js.map
  24844. var BABYLON;
  24845. (function (BABYLON) {
  24846. /**
  24847. * Set of assets to keep when moving a scene into an asset container.
  24848. */
  24849. var KeepAssets = /** @class */ (function () {
  24850. function KeepAssets() {
  24851. /**
  24852. * Cameras to keep.
  24853. */
  24854. this.cameras = new Array();
  24855. /**
  24856. * Lights to keep.
  24857. */
  24858. this.lights = new Array();
  24859. /**
  24860. * Meshes to keep.
  24861. */
  24862. this.meshes = new Array();
  24863. /**
  24864. * Skeletons to keep.
  24865. */
  24866. this.skeletons = new Array();
  24867. /**
  24868. * ParticleSystems to keep.
  24869. */
  24870. this.particleSystems = new Array();
  24871. /**
  24872. * Animations to keep.
  24873. */
  24874. this.animations = new Array();
  24875. /**
  24876. * MultiMaterials to keep.
  24877. */
  24878. this.multiMaterials = new Array();
  24879. /**
  24880. * Materials to keep.
  24881. */
  24882. this.materials = new Array();
  24883. /**
  24884. * MorphTargetManagers to keep.
  24885. */
  24886. this.morphTargetManagers = new Array();
  24887. /**
  24888. * Geometries to keep.
  24889. */
  24890. this.geometries = new Array();
  24891. /**
  24892. * TransformNodes to keep.
  24893. */
  24894. this.transformNodes = new Array();
  24895. /**
  24896. * LensFlareSystems to keep.
  24897. */
  24898. this.lensFlareSystems = new Array();
  24899. /**
  24900. * ShadowGenerators to keep.
  24901. */
  24902. this.shadowGenerators = new Array();
  24903. /**
  24904. * ActionManagers to keep.
  24905. */
  24906. this.actionManagers = new Array();
  24907. /**
  24908. * Sounds to keep.
  24909. */
  24910. this.sounds = new Array();
  24911. }
  24912. return KeepAssets;
  24913. }());
  24914. BABYLON.KeepAssets = KeepAssets;
  24915. /**
  24916. * Container with a set of assets that can be added or removed from a scene.
  24917. */
  24918. var AssetContainer = /** @class */ (function () {
  24919. /**
  24920. * Instantiates an AssetContainer.
  24921. * @param scene The scene the AssetContainer belongs to.
  24922. */
  24923. function AssetContainer(scene) {
  24924. // Objects
  24925. /**
  24926. * Cameras populated in the container.
  24927. */
  24928. this.cameras = new Array();
  24929. /**
  24930. * Lights populated in the container.
  24931. */
  24932. this.lights = new Array();
  24933. /**
  24934. * Meshes populated in the container.
  24935. */
  24936. this.meshes = new Array();
  24937. /**
  24938. * Skeletons populated in the container.
  24939. */
  24940. this.skeletons = new Array();
  24941. /**
  24942. * ParticleSystems populated in the container.
  24943. */
  24944. this.particleSystems = new Array();
  24945. /**
  24946. * Animations populated in the container.
  24947. */
  24948. this.animations = new Array();
  24949. /**
  24950. * MultiMaterials populated in the container.
  24951. */
  24952. this.multiMaterials = new Array();
  24953. /**
  24954. * Materials populated in the container.
  24955. */
  24956. this.materials = new Array();
  24957. /**
  24958. * MorphTargetManagers populated in the container.
  24959. */
  24960. this.morphTargetManagers = new Array();
  24961. /**
  24962. * Geometries populated in the container.
  24963. */
  24964. this.geometries = new Array();
  24965. /**
  24966. * TransformNodes populated in the container.
  24967. */
  24968. this.transformNodes = new Array();
  24969. /**
  24970. * LensFlareSystems populated in the container.
  24971. */
  24972. this.lensFlareSystems = new Array();
  24973. /**
  24974. * ShadowGenerators populated in the container.
  24975. */
  24976. this.shadowGenerators = new Array();
  24977. /**
  24978. * ActionManagers populated in the container.
  24979. */
  24980. this.actionManagers = new Array();
  24981. /**
  24982. * Sounds populated in the container.
  24983. */
  24984. this.sounds = new Array();
  24985. this.scene = scene;
  24986. }
  24987. /**
  24988. * Adds all the assets from the container to the scene.
  24989. */
  24990. AssetContainer.prototype.addAllToScene = function () {
  24991. var _this = this;
  24992. this.cameras.forEach(function (o) {
  24993. _this.scene.addCamera(o);
  24994. });
  24995. this.lights.forEach(function (o) {
  24996. _this.scene.addLight(o);
  24997. });
  24998. this.meshes.forEach(function (o) {
  24999. _this.scene.addMesh(o);
  25000. });
  25001. this.skeletons.forEach(function (o) {
  25002. _this.scene.addSkeleton(o);
  25003. });
  25004. this.particleSystems.forEach(function (o) {
  25005. _this.scene.addParticleSystem(o);
  25006. });
  25007. this.animations.forEach(function (o) {
  25008. _this.scene.addAnimation(o);
  25009. });
  25010. this.multiMaterials.forEach(function (o) {
  25011. _this.scene.addMultiMaterial(o);
  25012. });
  25013. this.materials.forEach(function (o) {
  25014. _this.scene.addMaterial(o);
  25015. });
  25016. this.morphTargetManagers.forEach(function (o) {
  25017. _this.scene.addMorphTargetManager(o);
  25018. });
  25019. this.geometries.forEach(function (o) {
  25020. _this.scene.addGeometry(o);
  25021. });
  25022. this.transformNodes.forEach(function (o) {
  25023. _this.scene.addTransformNode(o);
  25024. });
  25025. this.lensFlareSystems.forEach(function (o) {
  25026. _this.scene.addLensFlareSystem(o);
  25027. });
  25028. this.actionManagers.forEach(function (o) {
  25029. _this.scene.addActionManager(o);
  25030. });
  25031. this.sounds.forEach(function (o) {
  25032. o.play();
  25033. o.autoplay = true;
  25034. _this.scene.mainSoundTrack.AddSound(o);
  25035. });
  25036. };
  25037. /**
  25038. * Removes all the assets in the container from the scene
  25039. */
  25040. AssetContainer.prototype.removeAllFromScene = function () {
  25041. var _this = this;
  25042. this.cameras.forEach(function (o) {
  25043. _this.scene.removeCamera(o);
  25044. });
  25045. this.lights.forEach(function (o) {
  25046. _this.scene.removeLight(o);
  25047. });
  25048. this.meshes.forEach(function (o) {
  25049. _this.scene.removeMesh(o);
  25050. });
  25051. this.skeletons.forEach(function (o) {
  25052. _this.scene.removeSkeleton(o);
  25053. });
  25054. this.particleSystems.forEach(function (o) {
  25055. _this.scene.removeParticleSystem(o);
  25056. });
  25057. this.animations.forEach(function (o) {
  25058. _this.scene.removeAnimation(o);
  25059. });
  25060. this.multiMaterials.forEach(function (o) {
  25061. _this.scene.removeMultiMaterial(o);
  25062. });
  25063. this.materials.forEach(function (o) {
  25064. _this.scene.removeMaterial(o);
  25065. });
  25066. this.morphTargetManagers.forEach(function (o) {
  25067. _this.scene.removeMorphTargetManager(o);
  25068. });
  25069. this.geometries.forEach(function (o) {
  25070. _this.scene.removeGeometry(o);
  25071. });
  25072. this.transformNodes.forEach(function (o) {
  25073. _this.scene.removeTransformNode(o);
  25074. });
  25075. this.lensFlareSystems.forEach(function (o) {
  25076. _this.scene.removeLensFlareSystem(o);
  25077. });
  25078. this.actionManagers.forEach(function (o) {
  25079. _this.scene.removeActionManager(o);
  25080. });
  25081. this.sounds.forEach(function (o) {
  25082. o.stop();
  25083. o.autoplay = false;
  25084. _this.scene.mainSoundTrack.RemoveSound(o);
  25085. });
  25086. };
  25087. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  25088. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  25089. var asset = sourceAssets_1[_i];
  25090. var move = true;
  25091. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  25092. var keepAsset = keepAssets_1[_a];
  25093. if (asset === keepAsset) {
  25094. move = false;
  25095. break;
  25096. }
  25097. }
  25098. if (move) {
  25099. targetAssets.push(asset);
  25100. }
  25101. }
  25102. };
  25103. /**
  25104. * Removes all the assets contained in the scene and adds them to the container.
  25105. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  25106. */
  25107. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  25108. if (keepAssets === undefined) {
  25109. keepAssets = new KeepAssets();
  25110. }
  25111. this._moveAssets(this.scene.cameras, this.cameras, keepAssets.cameras);
  25112. this._moveAssets(this.scene.meshes, this.meshes, keepAssets.meshes);
  25113. this._moveAssets(this.scene.getGeometries(), this.geometries, keepAssets.geometries);
  25114. this._moveAssets(this.scene.materials, this.materials, keepAssets.materials);
  25115. this._moveAssets(this.scene._actionManagers, this.actionManagers, keepAssets.actionManagers);
  25116. this._moveAssets(this.scene.animations, this.animations, keepAssets.animations);
  25117. this._moveAssets(this.scene.lensFlareSystems, this.lensFlareSystems, keepAssets.lensFlareSystems);
  25118. this._moveAssets(this.scene.lights, this.lights, keepAssets.lights);
  25119. this._moveAssets(this.scene.morphTargetManagers, this.morphTargetManagers, keepAssets.morphTargetManagers);
  25120. this._moveAssets(this.scene.multiMaterials, this.multiMaterials, keepAssets.multiMaterials);
  25121. this._moveAssets(this.scene.skeletons, this.skeletons, keepAssets.skeletons);
  25122. this._moveAssets(this.scene.particleSystems, this.particleSystems, keepAssets.particleSystems);
  25123. this._moveAssets(this.scene.mainSoundTrack.soundCollection, this.sounds, keepAssets.sounds);
  25124. this._moveAssets(this.scene.transformNodes, this.transformNodes, keepAssets.transformNodes);
  25125. this.removeAllFromScene();
  25126. };
  25127. return AssetContainer;
  25128. }());
  25129. BABYLON.AssetContainer = AssetContainer;
  25130. })(BABYLON || (BABYLON = {}));
  25131. //# sourceMappingURL=babylon.assetContainer.js.map
  25132. var BABYLON;
  25133. (function (BABYLON) {
  25134. var Buffer = /** @class */ (function () {
  25135. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  25136. if (instanced === void 0) { instanced = false; }
  25137. if (engine instanceof BABYLON.Mesh) {
  25138. this._engine = engine.getScene().getEngine();
  25139. }
  25140. else {
  25141. this._engine = engine;
  25142. }
  25143. this._updatable = updatable;
  25144. this._data = data;
  25145. this._strideSize = stride;
  25146. if (!postponeInternalCreation) {
  25147. this.create();
  25148. }
  25149. this._instanced = instanced;
  25150. this._instanceDivisor = instanced ? 1 : 0;
  25151. }
  25152. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride) {
  25153. // a lot of these parameters are ignored as they are overriden by the buffer
  25154. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, this._instanced, offset, size);
  25155. };
  25156. // Properties
  25157. Buffer.prototype.isUpdatable = function () {
  25158. return this._updatable;
  25159. };
  25160. Buffer.prototype.getData = function () {
  25161. return this._data;
  25162. };
  25163. Buffer.prototype.getBuffer = function () {
  25164. return this._buffer;
  25165. };
  25166. Buffer.prototype.getStrideSize = function () {
  25167. return this._strideSize;
  25168. };
  25169. Buffer.prototype.getIsInstanced = function () {
  25170. return this._instanced;
  25171. };
  25172. Object.defineProperty(Buffer.prototype, "instanceDivisor", {
  25173. get: function () {
  25174. return this._instanceDivisor;
  25175. },
  25176. set: function (value) {
  25177. this._instanceDivisor = value;
  25178. if (value == 0) {
  25179. this._instanced = false;
  25180. }
  25181. else {
  25182. this._instanced = true;
  25183. }
  25184. },
  25185. enumerable: true,
  25186. configurable: true
  25187. });
  25188. // Methods
  25189. Buffer.prototype.create = function (data) {
  25190. if (data === void 0) { data = null; }
  25191. if (!data && this._buffer) {
  25192. return; // nothing to do
  25193. }
  25194. data = data || this._data;
  25195. if (!data) {
  25196. return;
  25197. }
  25198. if (!this._buffer) {
  25199. if (this._updatable) {
  25200. this._buffer = this._engine.createDynamicVertexBuffer(data);
  25201. this._data = data;
  25202. }
  25203. else {
  25204. this._buffer = this._engine.createVertexBuffer(data);
  25205. }
  25206. }
  25207. else if (this._updatable) {
  25208. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  25209. this._data = data;
  25210. }
  25211. };
  25212. Buffer.prototype._rebuild = function () {
  25213. this._buffer = null;
  25214. this.create(this._data);
  25215. };
  25216. Buffer.prototype.update = function (data) {
  25217. this.create(data);
  25218. };
  25219. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  25220. if (!this._buffer) {
  25221. return;
  25222. }
  25223. if (this._updatable) {
  25224. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  25225. this._data = null;
  25226. }
  25227. };
  25228. Buffer.prototype.dispose = function () {
  25229. if (!this._buffer) {
  25230. return;
  25231. }
  25232. if (this._engine._releaseBuffer(this._buffer)) {
  25233. this._buffer = null;
  25234. }
  25235. };
  25236. return Buffer;
  25237. }());
  25238. BABYLON.Buffer = Buffer;
  25239. })(BABYLON || (BABYLON = {}));
  25240. //# sourceMappingURL=babylon.buffer.js.map
  25241. var BABYLON;
  25242. (function (BABYLON) {
  25243. var VertexBuffer = /** @class */ (function () {
  25244. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  25245. if (!stride) {
  25246. stride = VertexBuffer.DeduceStride(kind);
  25247. }
  25248. if (data instanceof BABYLON.Buffer) {
  25249. if (!stride) {
  25250. stride = data.getStrideSize();
  25251. }
  25252. this._buffer = data;
  25253. this._ownsBuffer = false;
  25254. }
  25255. else {
  25256. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  25257. this._ownsBuffer = true;
  25258. }
  25259. this._stride = stride;
  25260. this._offset = offset ? offset : 0;
  25261. this._size = size ? size : stride;
  25262. this._kind = kind;
  25263. }
  25264. VertexBuffer.prototype._rebuild = function () {
  25265. if (!this._buffer) {
  25266. return;
  25267. }
  25268. this._buffer._rebuild();
  25269. };
  25270. /**
  25271. * Returns the kind of the VertexBuffer (string).
  25272. */
  25273. VertexBuffer.prototype.getKind = function () {
  25274. return this._kind;
  25275. };
  25276. // Properties
  25277. /**
  25278. * Boolean : is the VertexBuffer updatable ?
  25279. */
  25280. VertexBuffer.prototype.isUpdatable = function () {
  25281. return this._buffer.isUpdatable();
  25282. };
  25283. /**
  25284. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  25285. */
  25286. VertexBuffer.prototype.getData = function () {
  25287. return this._buffer.getData();
  25288. };
  25289. /**
  25290. * Returns the WebGLBuffer associated to the VertexBuffer.
  25291. */
  25292. VertexBuffer.prototype.getBuffer = function () {
  25293. return this._buffer.getBuffer();
  25294. };
  25295. /**
  25296. * Returns the stride of the VertexBuffer (integer).
  25297. */
  25298. VertexBuffer.prototype.getStrideSize = function () {
  25299. return this._stride;
  25300. };
  25301. /**
  25302. * Returns the offset (integer).
  25303. */
  25304. VertexBuffer.prototype.getOffset = function () {
  25305. return this._offset;
  25306. };
  25307. /**
  25308. * Returns the VertexBuffer total size (integer).
  25309. */
  25310. VertexBuffer.prototype.getSize = function () {
  25311. return this._size;
  25312. };
  25313. /**
  25314. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  25315. */
  25316. VertexBuffer.prototype.getIsInstanced = function () {
  25317. return this._buffer.getIsInstanced();
  25318. };
  25319. /**
  25320. * Returns the instancing divisor, zero for non-instanced (integer).
  25321. */
  25322. VertexBuffer.prototype.getInstanceDivisor = function () {
  25323. return this._buffer.instanceDivisor;
  25324. };
  25325. // Methods
  25326. /**
  25327. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  25328. * Returns the created WebGLBuffer.
  25329. */
  25330. VertexBuffer.prototype.create = function (data) {
  25331. return this._buffer.create(data);
  25332. };
  25333. /**
  25334. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  25335. * This function will create a new buffer if the current one is not updatable
  25336. * Returns the updated WebGLBuffer.
  25337. */
  25338. VertexBuffer.prototype.update = function (data) {
  25339. return this._buffer.update(data);
  25340. };
  25341. /**
  25342. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  25343. * Returns the directly updated WebGLBuffer.
  25344. */
  25345. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  25346. return this._buffer.updateDirectly(data, offset);
  25347. };
  25348. /**
  25349. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  25350. */
  25351. VertexBuffer.prototype.dispose = function () {
  25352. if (this._ownsBuffer) {
  25353. this._buffer.dispose();
  25354. }
  25355. };
  25356. Object.defineProperty(VertexBuffer, "PositionKind", {
  25357. get: function () {
  25358. return VertexBuffer._PositionKind;
  25359. },
  25360. enumerable: true,
  25361. configurable: true
  25362. });
  25363. Object.defineProperty(VertexBuffer, "NormalKind", {
  25364. get: function () {
  25365. return VertexBuffer._NormalKind;
  25366. },
  25367. enumerable: true,
  25368. configurable: true
  25369. });
  25370. Object.defineProperty(VertexBuffer, "TangentKind", {
  25371. get: function () {
  25372. return VertexBuffer._TangentKind;
  25373. },
  25374. enumerable: true,
  25375. configurable: true
  25376. });
  25377. Object.defineProperty(VertexBuffer, "UVKind", {
  25378. get: function () {
  25379. return VertexBuffer._UVKind;
  25380. },
  25381. enumerable: true,
  25382. configurable: true
  25383. });
  25384. Object.defineProperty(VertexBuffer, "UV2Kind", {
  25385. get: function () {
  25386. return VertexBuffer._UV2Kind;
  25387. },
  25388. enumerable: true,
  25389. configurable: true
  25390. });
  25391. Object.defineProperty(VertexBuffer, "UV3Kind", {
  25392. get: function () {
  25393. return VertexBuffer._UV3Kind;
  25394. },
  25395. enumerable: true,
  25396. configurable: true
  25397. });
  25398. Object.defineProperty(VertexBuffer, "UV4Kind", {
  25399. get: function () {
  25400. return VertexBuffer._UV4Kind;
  25401. },
  25402. enumerable: true,
  25403. configurable: true
  25404. });
  25405. Object.defineProperty(VertexBuffer, "UV5Kind", {
  25406. get: function () {
  25407. return VertexBuffer._UV5Kind;
  25408. },
  25409. enumerable: true,
  25410. configurable: true
  25411. });
  25412. Object.defineProperty(VertexBuffer, "UV6Kind", {
  25413. get: function () {
  25414. return VertexBuffer._UV6Kind;
  25415. },
  25416. enumerable: true,
  25417. configurable: true
  25418. });
  25419. Object.defineProperty(VertexBuffer, "ColorKind", {
  25420. get: function () {
  25421. return VertexBuffer._ColorKind;
  25422. },
  25423. enumerable: true,
  25424. configurable: true
  25425. });
  25426. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  25427. get: function () {
  25428. return VertexBuffer._MatricesIndicesKind;
  25429. },
  25430. enumerable: true,
  25431. configurable: true
  25432. });
  25433. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  25434. get: function () {
  25435. return VertexBuffer._MatricesWeightsKind;
  25436. },
  25437. enumerable: true,
  25438. configurable: true
  25439. });
  25440. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  25441. get: function () {
  25442. return VertexBuffer._MatricesIndicesExtraKind;
  25443. },
  25444. enumerable: true,
  25445. configurable: true
  25446. });
  25447. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  25448. get: function () {
  25449. return VertexBuffer._MatricesWeightsExtraKind;
  25450. },
  25451. enumerable: true,
  25452. configurable: true
  25453. });
  25454. /**
  25455. * Deduces the stride given a kind.
  25456. * @param kind The kind string to deduce
  25457. * @returns The deduced stride
  25458. */
  25459. VertexBuffer.DeduceStride = function (kind) {
  25460. switch (kind) {
  25461. case VertexBuffer.PositionKind:
  25462. return 3;
  25463. case VertexBuffer.NormalKind:
  25464. return 3;
  25465. case VertexBuffer.UVKind:
  25466. case VertexBuffer.UV2Kind:
  25467. case VertexBuffer.UV3Kind:
  25468. case VertexBuffer.UV4Kind:
  25469. case VertexBuffer.UV5Kind:
  25470. case VertexBuffer.UV6Kind:
  25471. return 2;
  25472. case VertexBuffer.TangentKind:
  25473. case VertexBuffer.ColorKind:
  25474. return 4;
  25475. case VertexBuffer.MatricesIndicesKind:
  25476. case VertexBuffer.MatricesIndicesExtraKind:
  25477. return 4;
  25478. case VertexBuffer.MatricesWeightsKind:
  25479. case VertexBuffer.MatricesWeightsExtraKind:
  25480. return 4;
  25481. default:
  25482. throw new Error("Invalid kind '" + kind + "'");
  25483. }
  25484. };
  25485. // Enums
  25486. VertexBuffer._PositionKind = "position";
  25487. VertexBuffer._NormalKind = "normal";
  25488. VertexBuffer._TangentKind = "tangent";
  25489. VertexBuffer._UVKind = "uv";
  25490. VertexBuffer._UV2Kind = "uv2";
  25491. VertexBuffer._UV3Kind = "uv3";
  25492. VertexBuffer._UV4Kind = "uv4";
  25493. VertexBuffer._UV5Kind = "uv5";
  25494. VertexBuffer._UV6Kind = "uv6";
  25495. VertexBuffer._ColorKind = "color";
  25496. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  25497. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  25498. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  25499. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  25500. return VertexBuffer;
  25501. }());
  25502. BABYLON.VertexBuffer = VertexBuffer;
  25503. })(BABYLON || (BABYLON = {}));
  25504. //# sourceMappingURL=babylon.vertexBuffer.js.map
  25505. var BABYLON;
  25506. (function (BABYLON) {
  25507. /**
  25508. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  25509. */
  25510. var DummyInternalTextureTracker = /** @class */ (function () {
  25511. function DummyInternalTextureTracker() {
  25512. /**
  25513. * Gets or set the previous tracker in the list
  25514. */
  25515. this.previous = null;
  25516. /**
  25517. * Gets or set the next tracker in the list
  25518. */
  25519. this.next = null;
  25520. }
  25521. return DummyInternalTextureTracker;
  25522. }());
  25523. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  25524. })(BABYLON || (BABYLON = {}));
  25525. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  25526. var BABYLON;
  25527. (function (BABYLON) {
  25528. /**
  25529. * Class used to store data associated with WebGL texture data for the engine
  25530. * This class should not be used directly
  25531. */
  25532. var InternalTexture = /** @class */ (function () {
  25533. /**
  25534. * Creates a new InternalTexture
  25535. * @param engine defines the engine to use
  25536. * @param dataSource defines the type of data that will be used
  25537. */
  25538. function InternalTexture(engine, dataSource) {
  25539. /**
  25540. * Observable called when the texture is loaded
  25541. */
  25542. this.onLoadedObservable = new BABYLON.Observable();
  25543. /**
  25544. * Gets or set the previous tracker in the list
  25545. */
  25546. this.previous = null;
  25547. /**
  25548. * Gets or set the next tracker in the list
  25549. */
  25550. this.next = null;
  25551. // Private
  25552. /** @ignore */
  25553. this._initialSlot = -1;
  25554. /** @ignore */
  25555. this._designatedSlot = -1;
  25556. /** @ignore */
  25557. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  25558. /** @ignore */
  25559. this._references = 1;
  25560. this._engine = engine;
  25561. this._dataSource = dataSource;
  25562. this._webGLTexture = engine._createTexture();
  25563. }
  25564. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  25565. /**
  25566. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  25567. */
  25568. get: function () {
  25569. return this._dataSource;
  25570. },
  25571. enumerable: true,
  25572. configurable: true
  25573. });
  25574. /**
  25575. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  25576. */
  25577. InternalTexture.prototype.incrementReferences = function () {
  25578. this._references++;
  25579. };
  25580. /**
  25581. * Change the size of the texture (not the size of the content)
  25582. * @param width defines the new width
  25583. * @param height defines the new height
  25584. * @param depth defines the new depth (1 by default)
  25585. */
  25586. InternalTexture.prototype.updateSize = function (width, height, depth) {
  25587. if (depth === void 0) { depth = 1; }
  25588. this.width = width;
  25589. this.height = height;
  25590. this.depth = depth;
  25591. this.baseWidth = width;
  25592. this.baseHeight = height;
  25593. this.baseDepth = depth;
  25594. this._size = width * height * depth;
  25595. };
  25596. /** @ignore */
  25597. InternalTexture.prototype._rebuild = function () {
  25598. var _this = this;
  25599. var proxy;
  25600. this.isReady = false;
  25601. this._cachedCoordinatesMode = null;
  25602. this._cachedWrapU = null;
  25603. this._cachedWrapV = null;
  25604. this._cachedAnisotropicFilteringLevel = null;
  25605. switch (this._dataSource) {
  25606. case InternalTexture.DATASOURCE_TEMP:
  25607. return;
  25608. case InternalTexture.DATASOURCE_URL:
  25609. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  25610. _this.isReady = true;
  25611. }, null, this._buffer, undefined, this.format);
  25612. proxy._swapAndDie(this);
  25613. return;
  25614. case InternalTexture.DATASOURCE_RAW:
  25615. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  25616. proxy._swapAndDie(this);
  25617. this.isReady = true;
  25618. return;
  25619. case InternalTexture.DATASOURCE_RAW3D:
  25620. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  25621. proxy._swapAndDie(this);
  25622. this.isReady = true;
  25623. return;
  25624. case InternalTexture.DATASOURCE_DYNAMIC:
  25625. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  25626. proxy._swapAndDie(this);
  25627. // The engine will make sure to update content so no need to flag it as isReady = true
  25628. return;
  25629. case InternalTexture.DATASOURCE_RENDERTARGET:
  25630. var options = new BABYLON.RenderTargetCreationOptions();
  25631. options.generateDepthBuffer = this._generateDepthBuffer;
  25632. options.generateMipMaps = this.generateMipMaps;
  25633. options.generateStencilBuffer = this._generateStencilBuffer;
  25634. options.samplingMode = this.samplingMode;
  25635. options.type = this.type;
  25636. if (this.isCube) {
  25637. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  25638. }
  25639. else {
  25640. var size = {
  25641. width: this.width,
  25642. height: this.height
  25643. };
  25644. proxy = this._engine.createRenderTargetTexture(size, options);
  25645. }
  25646. proxy._swapAndDie(this);
  25647. this.isReady = true;
  25648. return;
  25649. case InternalTexture.DATASOURCE_CUBE:
  25650. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  25651. _this.isReady = true;
  25652. }, null, this.format, this._extension);
  25653. proxy._swapAndDie(this);
  25654. return;
  25655. case InternalTexture.DATASOURCE_CUBERAW:
  25656. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  25657. proxy._swapAndDie(this);
  25658. this.isReady = true;
  25659. return;
  25660. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  25661. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  25662. if (proxy) {
  25663. proxy._swapAndDie(_this);
  25664. }
  25665. _this.isReady = true;
  25666. }, null, this.format, this._extension);
  25667. return;
  25668. }
  25669. };
  25670. InternalTexture.prototype._swapAndDie = function (target) {
  25671. target._webGLTexture = this._webGLTexture;
  25672. if (this._framebuffer) {
  25673. target._framebuffer = this._framebuffer;
  25674. }
  25675. if (this._depthStencilBuffer) {
  25676. target._depthStencilBuffer = this._depthStencilBuffer;
  25677. }
  25678. if (this._lodTextureHigh) {
  25679. if (target._lodTextureHigh) {
  25680. target._lodTextureHigh.dispose();
  25681. }
  25682. target._lodTextureHigh = this._lodTextureHigh;
  25683. }
  25684. if (this._lodTextureMid) {
  25685. if (target._lodTextureMid) {
  25686. target._lodTextureMid.dispose();
  25687. }
  25688. target._lodTextureMid = this._lodTextureMid;
  25689. }
  25690. if (this._lodTextureLow) {
  25691. if (target._lodTextureLow) {
  25692. target._lodTextureLow.dispose();
  25693. }
  25694. target._lodTextureLow = this._lodTextureLow;
  25695. }
  25696. var cache = this._engine.getLoadedTexturesCache();
  25697. var index = cache.indexOf(this);
  25698. if (index !== -1) {
  25699. cache.splice(index, 1);
  25700. }
  25701. };
  25702. /**
  25703. * Dispose the current allocated resources
  25704. */
  25705. InternalTexture.prototype.dispose = function () {
  25706. if (!this._webGLTexture) {
  25707. return;
  25708. }
  25709. this._references--;
  25710. if (this._references === 0) {
  25711. this._engine._releaseTexture(this);
  25712. this._webGLTexture = null;
  25713. this.previous = null;
  25714. this.next = null;
  25715. }
  25716. };
  25717. /**
  25718. * The source of the texture data is unknown
  25719. */
  25720. InternalTexture.DATASOURCE_UNKNOWN = 0;
  25721. /**
  25722. * Texture data comes from an URL
  25723. */
  25724. InternalTexture.DATASOURCE_URL = 1;
  25725. /**
  25726. * Texture data is only used for temporary storage
  25727. */
  25728. InternalTexture.DATASOURCE_TEMP = 2;
  25729. /**
  25730. * Texture data comes from raw data (ArrayBuffer)
  25731. */
  25732. InternalTexture.DATASOURCE_RAW = 3;
  25733. /**
  25734. * Texture content is dynamic (video or dynamic texture)
  25735. */
  25736. InternalTexture.DATASOURCE_DYNAMIC = 4;
  25737. /**
  25738. * Texture content is generated by rendering to it
  25739. */
  25740. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  25741. /**
  25742. * Texture content is part of a multi render target process
  25743. */
  25744. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  25745. /**
  25746. * Texture data comes from a cube data file
  25747. */
  25748. InternalTexture.DATASOURCE_CUBE = 7;
  25749. /**
  25750. * Texture data comes from a raw cube data
  25751. */
  25752. InternalTexture.DATASOURCE_CUBERAW = 8;
  25753. /**
  25754. * Texture data come from a prefiltered cube data file
  25755. */
  25756. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  25757. /**
  25758. * Texture content is raw 3D data
  25759. */
  25760. InternalTexture.DATASOURCE_RAW3D = 10;
  25761. return InternalTexture;
  25762. }());
  25763. BABYLON.InternalTexture = InternalTexture;
  25764. })(BABYLON || (BABYLON = {}));
  25765. //# sourceMappingURL=babylon.internalTexture.js.map
  25766. var BABYLON;
  25767. (function (BABYLON) {
  25768. var BaseTexture = /** @class */ (function () {
  25769. function BaseTexture(scene) {
  25770. this._hasAlpha = false;
  25771. this.getAlphaFromRGB = false;
  25772. this.level = 1;
  25773. this.coordinatesIndex = 0;
  25774. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  25775. /*
  25776. * How a texture is mapped.
  25777. *
  25778. * | Value | Type | Description |
  25779. * | ----- | ----------------------------------- | ----------- |
  25780. * | 0 | EXPLICIT_MODE | |
  25781. * | 1 | SPHERICAL_MODE | |
  25782. * | 2 | PLANAR_MODE | |
  25783. * | 3 | CUBIC_MODE | |
  25784. * | 4 | PROJECTION_MODE | |
  25785. * | 5 | SKYBOX_MODE | |
  25786. * | 6 | INVCUBIC_MODE | |
  25787. * | 7 | EQUIRECTANGULAR_MODE | |
  25788. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  25789. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  25790. */
  25791. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  25792. /*
  25793. * | Value | Type | Description |
  25794. * | ----- | ------------------ | ----------- |
  25795. * | 0 | CLAMP_ADDRESSMODE | |
  25796. * | 1 | WRAP_ADDRESSMODE | |
  25797. * | 2 | MIRROR_ADDRESSMODE | |
  25798. */
  25799. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  25800. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  25801. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  25802. this.isCube = false;
  25803. this.is3D = false;
  25804. this.gammaSpace = true;
  25805. this.invertZ = false;
  25806. this.lodLevelInAlpha = false;
  25807. this.lodGenerationOffset = 0.0;
  25808. this.lodGenerationScale = 0.8;
  25809. this.isRenderTarget = false;
  25810. this.animations = new Array();
  25811. /**
  25812. * An event triggered when the texture is disposed.
  25813. * @type {BABYLON.Observable}
  25814. */
  25815. this.onDisposeObservable = new BABYLON.Observable();
  25816. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  25817. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  25818. if (this._scene) {
  25819. this._scene.textures.push(this);
  25820. }
  25821. this._uid = null;
  25822. }
  25823. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  25824. get: function () {
  25825. return this._hasAlpha;
  25826. },
  25827. set: function (value) {
  25828. if (this._hasAlpha === value) {
  25829. return;
  25830. }
  25831. this._hasAlpha = value;
  25832. if (this._scene) {
  25833. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  25834. }
  25835. },
  25836. enumerable: true,
  25837. configurable: true
  25838. });
  25839. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  25840. get: function () {
  25841. return this._coordinatesMode;
  25842. },
  25843. set: function (value) {
  25844. if (this._coordinatesMode === value) {
  25845. return;
  25846. }
  25847. this._coordinatesMode = value;
  25848. if (this._scene) {
  25849. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  25850. }
  25851. },
  25852. enumerable: true,
  25853. configurable: true
  25854. });
  25855. Object.defineProperty(BaseTexture.prototype, "uid", {
  25856. get: function () {
  25857. if (!this._uid) {
  25858. this._uid = BABYLON.Tools.RandomId();
  25859. }
  25860. return this._uid;
  25861. },
  25862. enumerable: true,
  25863. configurable: true
  25864. });
  25865. BaseTexture.prototype.toString = function () {
  25866. return this.name;
  25867. };
  25868. BaseTexture.prototype.getClassName = function () {
  25869. return "BaseTexture";
  25870. };
  25871. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  25872. set: function (callback) {
  25873. if (this._onDisposeObserver) {
  25874. this.onDisposeObservable.remove(this._onDisposeObserver);
  25875. }
  25876. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  25877. },
  25878. enumerable: true,
  25879. configurable: true
  25880. });
  25881. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  25882. get: function () {
  25883. return true;
  25884. },
  25885. enumerable: true,
  25886. configurable: true
  25887. });
  25888. BaseTexture.prototype.getScene = function () {
  25889. return this._scene;
  25890. };
  25891. BaseTexture.prototype.getTextureMatrix = function () {
  25892. return BABYLON.Matrix.IdentityReadOnly;
  25893. };
  25894. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  25895. return BABYLON.Matrix.IdentityReadOnly;
  25896. };
  25897. BaseTexture.prototype.getInternalTexture = function () {
  25898. return this._texture;
  25899. };
  25900. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  25901. return !this.isBlocking || this.isReady();
  25902. };
  25903. BaseTexture.prototype.isReady = function () {
  25904. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  25905. this.delayLoad();
  25906. return false;
  25907. }
  25908. if (this._texture) {
  25909. return this._texture.isReady;
  25910. }
  25911. return false;
  25912. };
  25913. BaseTexture.prototype.getSize = function () {
  25914. if (this._texture && this._texture.width) {
  25915. return new BABYLON.Size(this._texture.width, this._texture.height);
  25916. }
  25917. if (this._texture && this._texture._size) {
  25918. return new BABYLON.Size(this._texture._size, this._texture._size);
  25919. }
  25920. return BABYLON.Size.Zero();
  25921. };
  25922. BaseTexture.prototype.getBaseSize = function () {
  25923. if (!this.isReady() || !this._texture)
  25924. return BABYLON.Size.Zero();
  25925. if (this._texture._size) {
  25926. return new BABYLON.Size(this._texture._size, this._texture._size);
  25927. }
  25928. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  25929. };
  25930. BaseTexture.prototype.scale = function (ratio) {
  25931. };
  25932. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  25933. get: function () {
  25934. return false;
  25935. },
  25936. enumerable: true,
  25937. configurable: true
  25938. });
  25939. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  25940. if (!this._scene) {
  25941. return null;
  25942. }
  25943. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  25944. for (var index = 0; index < texturesCache.length; index++) {
  25945. var texturesCacheEntry = texturesCache[index];
  25946. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  25947. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  25948. texturesCacheEntry.incrementReferences();
  25949. return texturesCacheEntry;
  25950. }
  25951. }
  25952. }
  25953. return null;
  25954. };
  25955. BaseTexture.prototype._rebuild = function () {
  25956. };
  25957. BaseTexture.prototype.delayLoad = function () {
  25958. };
  25959. BaseTexture.prototype.clone = function () {
  25960. return null;
  25961. };
  25962. Object.defineProperty(BaseTexture.prototype, "textureType", {
  25963. get: function () {
  25964. if (!this._texture) {
  25965. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  25966. }
  25967. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  25968. },
  25969. enumerable: true,
  25970. configurable: true
  25971. });
  25972. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  25973. get: function () {
  25974. if (!this._texture) {
  25975. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  25976. }
  25977. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  25978. },
  25979. enumerable: true,
  25980. configurable: true
  25981. });
  25982. BaseTexture.prototype.readPixels = function (faceIndex) {
  25983. if (faceIndex === void 0) { faceIndex = 0; }
  25984. if (!this._texture) {
  25985. return null;
  25986. }
  25987. var size = this.getSize();
  25988. var scene = this.getScene();
  25989. if (!scene) {
  25990. return null;
  25991. }
  25992. var engine = scene.getEngine();
  25993. if (this._texture.isCube) {
  25994. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  25995. }
  25996. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  25997. };
  25998. BaseTexture.prototype.releaseInternalTexture = function () {
  25999. if (this._texture) {
  26000. this._texture.dispose();
  26001. this._texture = null;
  26002. }
  26003. };
  26004. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  26005. get: function () {
  26006. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  26007. return null;
  26008. }
  26009. if (!this._texture._sphericalPolynomial) {
  26010. this._texture._sphericalPolynomial =
  26011. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  26012. }
  26013. return this._texture._sphericalPolynomial;
  26014. },
  26015. set: function (value) {
  26016. if (this._texture) {
  26017. this._texture._sphericalPolynomial = value;
  26018. }
  26019. },
  26020. enumerable: true,
  26021. configurable: true
  26022. });
  26023. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  26024. get: function () {
  26025. if (this._texture) {
  26026. return this._texture._lodTextureHigh;
  26027. }
  26028. return null;
  26029. },
  26030. enumerable: true,
  26031. configurable: true
  26032. });
  26033. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  26034. get: function () {
  26035. if (this._texture) {
  26036. return this._texture._lodTextureMid;
  26037. }
  26038. return null;
  26039. },
  26040. enumerable: true,
  26041. configurable: true
  26042. });
  26043. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  26044. get: function () {
  26045. if (this._texture) {
  26046. return this._texture._lodTextureLow;
  26047. }
  26048. return null;
  26049. },
  26050. enumerable: true,
  26051. configurable: true
  26052. });
  26053. BaseTexture.prototype.dispose = function () {
  26054. if (!this._scene) {
  26055. return;
  26056. }
  26057. // Animations
  26058. this._scene.stopAnimation(this);
  26059. // Remove from scene
  26060. this._scene._removePendingData(this);
  26061. var index = this._scene.textures.indexOf(this);
  26062. if (index >= 0) {
  26063. this._scene.textures.splice(index, 1);
  26064. }
  26065. if (this._texture === undefined) {
  26066. return;
  26067. }
  26068. // Release
  26069. this.releaseInternalTexture();
  26070. // Callback
  26071. this.onDisposeObservable.notifyObservers(this);
  26072. this.onDisposeObservable.clear();
  26073. };
  26074. BaseTexture.prototype.serialize = function () {
  26075. if (!this.name) {
  26076. return null;
  26077. }
  26078. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  26079. // Animations
  26080. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  26081. return serializationObject;
  26082. };
  26083. BaseTexture.WhenAllReady = function (textures, callback) {
  26084. var numRemaining = textures.length;
  26085. if (numRemaining === 0) {
  26086. callback();
  26087. return;
  26088. }
  26089. var _loop_1 = function () {
  26090. texture = textures[i];
  26091. if (texture.isReady()) {
  26092. if (--numRemaining === 0) {
  26093. callback();
  26094. }
  26095. }
  26096. else {
  26097. onLoadObservable = texture.onLoadObservable;
  26098. var onLoadCallback_1 = function () {
  26099. onLoadObservable.removeCallback(onLoadCallback_1);
  26100. if (--numRemaining === 0) {
  26101. callback();
  26102. }
  26103. };
  26104. onLoadObservable.add(onLoadCallback_1);
  26105. }
  26106. };
  26107. var texture, onLoadObservable;
  26108. for (var i = 0; i < textures.length; i++) {
  26109. _loop_1();
  26110. }
  26111. };
  26112. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  26113. __decorate([
  26114. BABYLON.serialize()
  26115. ], BaseTexture.prototype, "name", void 0);
  26116. __decorate([
  26117. BABYLON.serialize("hasAlpha")
  26118. ], BaseTexture.prototype, "_hasAlpha", void 0);
  26119. __decorate([
  26120. BABYLON.serialize()
  26121. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  26122. __decorate([
  26123. BABYLON.serialize()
  26124. ], BaseTexture.prototype, "level", void 0);
  26125. __decorate([
  26126. BABYLON.serialize()
  26127. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  26128. __decorate([
  26129. BABYLON.serialize("coordinatesMode")
  26130. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  26131. __decorate([
  26132. BABYLON.serialize()
  26133. ], BaseTexture.prototype, "wrapU", void 0);
  26134. __decorate([
  26135. BABYLON.serialize()
  26136. ], BaseTexture.prototype, "wrapV", void 0);
  26137. __decorate([
  26138. BABYLON.serialize()
  26139. ], BaseTexture.prototype, "wrapR", void 0);
  26140. __decorate([
  26141. BABYLON.serialize()
  26142. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  26143. __decorate([
  26144. BABYLON.serialize()
  26145. ], BaseTexture.prototype, "isCube", void 0);
  26146. __decorate([
  26147. BABYLON.serialize()
  26148. ], BaseTexture.prototype, "is3D", void 0);
  26149. __decorate([
  26150. BABYLON.serialize()
  26151. ], BaseTexture.prototype, "gammaSpace", void 0);
  26152. __decorate([
  26153. BABYLON.serialize()
  26154. ], BaseTexture.prototype, "invertZ", void 0);
  26155. __decorate([
  26156. BABYLON.serialize()
  26157. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  26158. __decorate([
  26159. BABYLON.serialize()
  26160. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  26161. __decorate([
  26162. BABYLON.serialize()
  26163. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  26164. __decorate([
  26165. BABYLON.serialize()
  26166. ], BaseTexture.prototype, "isRenderTarget", void 0);
  26167. return BaseTexture;
  26168. }());
  26169. BABYLON.BaseTexture = BaseTexture;
  26170. })(BABYLON || (BABYLON = {}));
  26171. //# sourceMappingURL=babylon.baseTexture.js.map
  26172. var BABYLON;
  26173. (function (BABYLON) {
  26174. var Texture = /** @class */ (function (_super) {
  26175. __extends(Texture, _super);
  26176. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  26177. if (noMipmap === void 0) { noMipmap = false; }
  26178. if (invertY === void 0) { invertY = true; }
  26179. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  26180. if (onLoad === void 0) { onLoad = null; }
  26181. if (onError === void 0) { onError = null; }
  26182. if (buffer === void 0) { buffer = null; }
  26183. if (deleteBuffer === void 0) { deleteBuffer = false; }
  26184. var _this = _super.call(this, scene) || this;
  26185. _this.uOffset = 0;
  26186. _this.vOffset = 0;
  26187. _this.uScale = 1.0;
  26188. _this.vScale = 1.0;
  26189. _this.uAng = 0;
  26190. _this.vAng = 0;
  26191. _this.wAng = 0;
  26192. _this._isBlocking = true;
  26193. _this.name = url || "";
  26194. _this.url = url;
  26195. _this._noMipmap = noMipmap;
  26196. _this._invertY = invertY;
  26197. _this._samplingMode = samplingMode;
  26198. _this._buffer = buffer;
  26199. _this._deleteBuffer = deleteBuffer;
  26200. if (format) {
  26201. _this._format = format;
  26202. }
  26203. scene = _this.getScene();
  26204. if (!scene) {
  26205. return _this;
  26206. }
  26207. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  26208. var load = function () {
  26209. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  26210. _this.onLoadObservable.notifyObservers(_this);
  26211. }
  26212. if (onLoad) {
  26213. onLoad();
  26214. }
  26215. if (!_this.isBlocking && scene) {
  26216. scene.resetCachedMaterial();
  26217. }
  26218. };
  26219. if (!_this.url) {
  26220. _this._delayedOnLoad = load;
  26221. _this._delayedOnError = onError;
  26222. return _this;
  26223. }
  26224. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  26225. if (!_this._texture) {
  26226. if (!scene.useDelayedTextureLoading) {
  26227. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  26228. if (deleteBuffer) {
  26229. delete _this._buffer;
  26230. }
  26231. }
  26232. else {
  26233. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  26234. _this._delayedOnLoad = load;
  26235. _this._delayedOnError = onError;
  26236. }
  26237. }
  26238. else {
  26239. if (_this._texture.isReady) {
  26240. BABYLON.Tools.SetImmediate(function () { return load(); });
  26241. }
  26242. else {
  26243. _this._texture.onLoadedObservable.add(load);
  26244. }
  26245. }
  26246. return _this;
  26247. }
  26248. Object.defineProperty(Texture.prototype, "noMipmap", {
  26249. get: function () {
  26250. return this._noMipmap;
  26251. },
  26252. enumerable: true,
  26253. configurable: true
  26254. });
  26255. Object.defineProperty(Texture.prototype, "isBlocking", {
  26256. get: function () {
  26257. return this._isBlocking;
  26258. },
  26259. set: function (value) {
  26260. this._isBlocking = value;
  26261. },
  26262. enumerable: true,
  26263. configurable: true
  26264. });
  26265. Object.defineProperty(Texture.prototype, "samplingMode", {
  26266. get: function () {
  26267. return this._samplingMode;
  26268. },
  26269. enumerable: true,
  26270. configurable: true
  26271. });
  26272. Texture.prototype.updateURL = function (url) {
  26273. this.url = url;
  26274. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  26275. this.delayLoad();
  26276. };
  26277. Texture.prototype.delayLoad = function () {
  26278. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  26279. return;
  26280. }
  26281. var scene = this.getScene();
  26282. if (!scene) {
  26283. return;
  26284. }
  26285. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  26286. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  26287. if (!this._texture) {
  26288. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  26289. if (this._deleteBuffer) {
  26290. delete this._buffer;
  26291. }
  26292. }
  26293. else {
  26294. if (this._delayedOnLoad) {
  26295. if (this._texture.isReady) {
  26296. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  26297. }
  26298. else {
  26299. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  26300. }
  26301. }
  26302. }
  26303. this._delayedOnLoad = null;
  26304. this._delayedOnError = null;
  26305. };
  26306. Texture.prototype.updateSamplingMode = function (samplingMode) {
  26307. if (!this._texture) {
  26308. return;
  26309. }
  26310. var scene = this.getScene();
  26311. if (!scene) {
  26312. return;
  26313. }
  26314. this._samplingMode = samplingMode;
  26315. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  26316. };
  26317. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  26318. x *= this.uScale;
  26319. y *= this.vScale;
  26320. x -= 0.5 * this.uScale;
  26321. y -= 0.5 * this.vScale;
  26322. z -= 0.5;
  26323. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  26324. t.x += 0.5 * this.uScale + this.uOffset;
  26325. t.y += 0.5 * this.vScale + this.vOffset;
  26326. t.z += 0.5;
  26327. };
  26328. Texture.prototype.getTextureMatrix = function () {
  26329. var _this = this;
  26330. if (this.uOffset === this._cachedUOffset &&
  26331. this.vOffset === this._cachedVOffset &&
  26332. this.uScale === this._cachedUScale &&
  26333. this.vScale === this._cachedVScale &&
  26334. this.uAng === this._cachedUAng &&
  26335. this.vAng === this._cachedVAng &&
  26336. this.wAng === this._cachedWAng) {
  26337. return this._cachedTextureMatrix;
  26338. }
  26339. this._cachedUOffset = this.uOffset;
  26340. this._cachedVOffset = this.vOffset;
  26341. this._cachedUScale = this.uScale;
  26342. this._cachedVScale = this.vScale;
  26343. this._cachedUAng = this.uAng;
  26344. this._cachedVAng = this.vAng;
  26345. this._cachedWAng = this.wAng;
  26346. if (!this._cachedTextureMatrix) {
  26347. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  26348. this._rowGenerationMatrix = new BABYLON.Matrix();
  26349. this._t0 = BABYLON.Vector3.Zero();
  26350. this._t1 = BABYLON.Vector3.Zero();
  26351. this._t2 = BABYLON.Vector3.Zero();
  26352. }
  26353. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  26354. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  26355. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  26356. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  26357. this._t1.subtractInPlace(this._t0);
  26358. this._t2.subtractInPlace(this._t0);
  26359. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  26360. this._cachedTextureMatrix.m[0] = this._t1.x;
  26361. this._cachedTextureMatrix.m[1] = this._t1.y;
  26362. this._cachedTextureMatrix.m[2] = this._t1.z;
  26363. this._cachedTextureMatrix.m[4] = this._t2.x;
  26364. this._cachedTextureMatrix.m[5] = this._t2.y;
  26365. this._cachedTextureMatrix.m[6] = this._t2.z;
  26366. this._cachedTextureMatrix.m[8] = this._t0.x;
  26367. this._cachedTextureMatrix.m[9] = this._t0.y;
  26368. this._cachedTextureMatrix.m[10] = this._t0.z;
  26369. var scene = this.getScene();
  26370. if (!scene) {
  26371. return this._cachedTextureMatrix;
  26372. }
  26373. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  26374. return mat.hasTexture(_this);
  26375. });
  26376. return this._cachedTextureMatrix;
  26377. };
  26378. Texture.prototype.getReflectionTextureMatrix = function () {
  26379. var _this = this;
  26380. var scene = this.getScene();
  26381. if (!scene) {
  26382. return this._cachedTextureMatrix;
  26383. }
  26384. if (this.uOffset === this._cachedUOffset &&
  26385. this.vOffset === this._cachedVOffset &&
  26386. this.uScale === this._cachedUScale &&
  26387. this.vScale === this._cachedVScale &&
  26388. this.coordinatesMode === this._cachedCoordinatesMode) {
  26389. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  26390. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  26391. return this._cachedTextureMatrix;
  26392. }
  26393. }
  26394. else {
  26395. return this._cachedTextureMatrix;
  26396. }
  26397. }
  26398. if (!this._cachedTextureMatrix) {
  26399. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  26400. }
  26401. if (!this._projectionModeMatrix) {
  26402. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  26403. }
  26404. this._cachedUOffset = this.uOffset;
  26405. this._cachedVOffset = this.vOffset;
  26406. this._cachedUScale = this.uScale;
  26407. this._cachedVScale = this.vScale;
  26408. this._cachedCoordinatesMode = this.coordinatesMode;
  26409. switch (this.coordinatesMode) {
  26410. case Texture.PLANAR_MODE:
  26411. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  26412. this._cachedTextureMatrix[0] = this.uScale;
  26413. this._cachedTextureMatrix[5] = this.vScale;
  26414. this._cachedTextureMatrix[12] = this.uOffset;
  26415. this._cachedTextureMatrix[13] = this.vOffset;
  26416. break;
  26417. case Texture.PROJECTION_MODE:
  26418. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  26419. this._projectionModeMatrix.m[0] = 0.5;
  26420. this._projectionModeMatrix.m[5] = -0.5;
  26421. this._projectionModeMatrix.m[10] = 0.0;
  26422. this._projectionModeMatrix.m[12] = 0.5;
  26423. this._projectionModeMatrix.m[13] = 0.5;
  26424. this._projectionModeMatrix.m[14] = 1.0;
  26425. this._projectionModeMatrix.m[15] = 1.0;
  26426. var projectionMatrix = scene.getProjectionMatrix();
  26427. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  26428. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  26429. break;
  26430. default:
  26431. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  26432. break;
  26433. }
  26434. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  26435. return (mat.getActiveTextures().indexOf(_this) !== -1);
  26436. });
  26437. return this._cachedTextureMatrix;
  26438. };
  26439. Texture.prototype.clone = function () {
  26440. var _this = this;
  26441. return BABYLON.SerializationHelper.Clone(function () {
  26442. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  26443. }, this);
  26444. };
  26445. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  26446. get: function () {
  26447. if (!this._onLoadObservable) {
  26448. this._onLoadObservable = new BABYLON.Observable();
  26449. }
  26450. return this._onLoadObservable;
  26451. },
  26452. enumerable: true,
  26453. configurable: true
  26454. });
  26455. Texture.prototype.serialize = function () {
  26456. var serializationObject = _super.prototype.serialize.call(this);
  26457. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  26458. serializationObject.base64String = this._buffer;
  26459. serializationObject.name = serializationObject.name.replace("data:", "");
  26460. }
  26461. return serializationObject;
  26462. };
  26463. Texture.prototype.getClassName = function () {
  26464. return "Texture";
  26465. };
  26466. Texture.prototype.dispose = function () {
  26467. _super.prototype.dispose.call(this);
  26468. if (this.onLoadObservable) {
  26469. this.onLoadObservable.clear();
  26470. this._onLoadObservable = null;
  26471. }
  26472. this._delayedOnLoad = null;
  26473. this._delayedOnError = null;
  26474. };
  26475. // Statics
  26476. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  26477. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  26478. if (onLoad === void 0) { onLoad = null; }
  26479. if (onError === void 0) { onError = null; }
  26480. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  26481. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  26482. };
  26483. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  26484. if (parsedTexture.customType) {
  26485. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  26486. // Update Sampling Mode
  26487. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  26488. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  26489. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  26490. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  26491. }
  26492. }
  26493. return parsedCustomTexture;
  26494. }
  26495. if (parsedTexture.isCube) {
  26496. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  26497. }
  26498. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  26499. return null;
  26500. }
  26501. var texture = BABYLON.SerializationHelper.Parse(function () {
  26502. var generateMipMaps = true;
  26503. if (parsedTexture.noMipmap) {
  26504. generateMipMaps = false;
  26505. }
  26506. if (parsedTexture.mirrorPlane) {
  26507. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  26508. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  26509. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  26510. return mirrorTexture;
  26511. }
  26512. else if (parsedTexture.isRenderTarget) {
  26513. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  26514. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  26515. return renderTargetTexture;
  26516. }
  26517. else {
  26518. var texture;
  26519. if (parsedTexture.base64String) {
  26520. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  26521. }
  26522. else {
  26523. texture = new Texture(rootUrl + parsedTexture.name, scene, !generateMipMaps);
  26524. }
  26525. return texture;
  26526. }
  26527. }, parsedTexture, scene);
  26528. // Update Sampling Mode
  26529. if (parsedTexture.samplingMode) {
  26530. var sampling = parsedTexture.samplingMode;
  26531. if (texture._samplingMode !== sampling) {
  26532. texture.updateSamplingMode(sampling);
  26533. }
  26534. }
  26535. // Animations
  26536. if (parsedTexture.animations) {
  26537. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  26538. var parsedAnimation = parsedTexture.animations[animationIndex];
  26539. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  26540. }
  26541. }
  26542. return texture;
  26543. };
  26544. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  26545. if (deleteBuffer === void 0) { deleteBuffer = false; }
  26546. if (noMipmap === void 0) { noMipmap = false; }
  26547. if (invertY === void 0) { invertY = true; }
  26548. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  26549. if (onLoad === void 0) { onLoad = null; }
  26550. if (onError === void 0) { onError = null; }
  26551. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  26552. if (name.substr(0, 5) !== "data:") {
  26553. name = "data:" + name;
  26554. }
  26555. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  26556. };
  26557. // Constants
  26558. Texture.NEAREST_SAMPLINGMODE = 1;
  26559. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  26560. Texture.BILINEAR_SAMPLINGMODE = 2;
  26561. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  26562. Texture.TRILINEAR_SAMPLINGMODE = 3;
  26563. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  26564. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  26565. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  26566. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  26567. Texture.NEAREST_LINEAR = 7;
  26568. Texture.NEAREST_NEAREST = 8;
  26569. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  26570. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  26571. Texture.LINEAR_LINEAR = 11;
  26572. Texture.LINEAR_NEAREST = 12;
  26573. Texture.EXPLICIT_MODE = 0;
  26574. Texture.SPHERICAL_MODE = 1;
  26575. Texture.PLANAR_MODE = 2;
  26576. Texture.CUBIC_MODE = 3;
  26577. Texture.PROJECTION_MODE = 4;
  26578. Texture.SKYBOX_MODE = 5;
  26579. Texture.INVCUBIC_MODE = 6;
  26580. Texture.EQUIRECTANGULAR_MODE = 7;
  26581. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  26582. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  26583. Texture.CLAMP_ADDRESSMODE = 0;
  26584. Texture.WRAP_ADDRESSMODE = 1;
  26585. Texture.MIRROR_ADDRESSMODE = 2;
  26586. __decorate([
  26587. BABYLON.serialize()
  26588. ], Texture.prototype, "url", void 0);
  26589. __decorate([
  26590. BABYLON.serialize()
  26591. ], Texture.prototype, "uOffset", void 0);
  26592. __decorate([
  26593. BABYLON.serialize()
  26594. ], Texture.prototype, "vOffset", void 0);
  26595. __decorate([
  26596. BABYLON.serialize()
  26597. ], Texture.prototype, "uScale", void 0);
  26598. __decorate([
  26599. BABYLON.serialize()
  26600. ], Texture.prototype, "vScale", void 0);
  26601. __decorate([
  26602. BABYLON.serialize()
  26603. ], Texture.prototype, "uAng", void 0);
  26604. __decorate([
  26605. BABYLON.serialize()
  26606. ], Texture.prototype, "vAng", void 0);
  26607. __decorate([
  26608. BABYLON.serialize()
  26609. ], Texture.prototype, "wAng", void 0);
  26610. __decorate([
  26611. BABYLON.serialize()
  26612. ], Texture.prototype, "isBlocking", null);
  26613. return Texture;
  26614. }(BABYLON.BaseTexture));
  26615. BABYLON.Texture = Texture;
  26616. })(BABYLON || (BABYLON = {}));
  26617. //# sourceMappingURL=babylon.texture.js.map
  26618. var BABYLON;
  26619. (function (BABYLON) {
  26620. var _InstancesBatch = /** @class */ (function () {
  26621. function _InstancesBatch() {
  26622. this.mustReturn = false;
  26623. this.visibleInstances = new Array();
  26624. this.renderSelf = new Array();
  26625. }
  26626. return _InstancesBatch;
  26627. }());
  26628. BABYLON._InstancesBatch = _InstancesBatch;
  26629. var Mesh = /** @class */ (function (_super) {
  26630. __extends(Mesh, _super);
  26631. /**
  26632. * @constructor
  26633. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  26634. * @param {Scene} scene The scene to add this mesh to.
  26635. * @param {Node} parent The parent of this mesh, if it has one
  26636. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  26637. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  26638. * When false, achieved by calling a clone(), also passing False.
  26639. * This will make creation of children, recursive.
  26640. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  26641. */
  26642. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  26643. if (scene === void 0) { scene = null; }
  26644. if (parent === void 0) { parent = null; }
  26645. if (source === void 0) { source = null; }
  26646. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  26647. var _this = _super.call(this, name, scene) || this;
  26648. // Events
  26649. /**
  26650. * An event triggered before rendering the mesh
  26651. * @type {BABYLON.Observable}
  26652. */
  26653. _this.onBeforeRenderObservable = new BABYLON.Observable();
  26654. /**
  26655. * An event triggered after rendering the mesh
  26656. * @type {BABYLON.Observable}
  26657. */
  26658. _this.onAfterRenderObservable = new BABYLON.Observable();
  26659. /**
  26660. * An event triggered before drawing the mesh
  26661. * @type {BABYLON.Observable}
  26662. */
  26663. _this.onBeforeDrawObservable = new BABYLON.Observable();
  26664. // Members
  26665. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  26666. _this.instances = new Array();
  26667. _this._LODLevels = new Array();
  26668. _this._visibleInstances = {};
  26669. _this._renderIdForInstances = new Array();
  26670. _this._batchCache = new _InstancesBatch();
  26671. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  26672. // Use by builder only to know what orientation were the mesh build in.
  26673. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  26674. _this.overrideMaterialSideOrientation = null;
  26675. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  26676. // Will be used to save a source mesh reference, If any
  26677. _this._source = null;
  26678. scene = _this.getScene();
  26679. if (source) {
  26680. // Source mesh
  26681. _this._source = source;
  26682. // Geometry
  26683. if (source._geometry) {
  26684. source._geometry.applyToMesh(_this);
  26685. }
  26686. // Deep copy
  26687. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId", "source", "metadata"], ["_poseMatrix", "_source"]);
  26688. // Metadata
  26689. if (source.metadata && source.metadata.clone) {
  26690. _this.metadata = source.metadata.clone();
  26691. }
  26692. else {
  26693. _this.metadata = source.metadata;
  26694. }
  26695. // Tags
  26696. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  26697. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  26698. }
  26699. // Parent
  26700. _this.parent = source.parent;
  26701. // Pivot
  26702. _this.setPivotMatrix(source.getPivotMatrix());
  26703. _this.id = name + "." + source.id;
  26704. // Material
  26705. _this.material = source.material;
  26706. var index;
  26707. if (!doNotCloneChildren) {
  26708. // Children
  26709. var directDescendants = source.getDescendants(true);
  26710. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  26711. var child = directDescendants[index_1];
  26712. if (child.clone) {
  26713. child.clone(name + "." + child.name, _this);
  26714. }
  26715. }
  26716. }
  26717. // Physics clone
  26718. var physicsEngine = _this.getScene().getPhysicsEngine();
  26719. if (clonePhysicsImpostor && physicsEngine) {
  26720. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  26721. if (impostor) {
  26722. _this.physicsImpostor = impostor.clone(_this);
  26723. }
  26724. }
  26725. // Particles
  26726. for (index = 0; index < scene.particleSystems.length; index++) {
  26727. var system = scene.particleSystems[index];
  26728. if (system.emitter === source) {
  26729. system.clone(system.name, _this);
  26730. }
  26731. }
  26732. _this.computeWorldMatrix(true);
  26733. }
  26734. // Parent
  26735. if (parent !== null) {
  26736. _this.parent = parent;
  26737. }
  26738. return _this;
  26739. }
  26740. Object.defineProperty(Mesh, "FRONTSIDE", {
  26741. /**
  26742. * Mesh side orientation : usually the external or front surface
  26743. */
  26744. get: function () {
  26745. return Mesh._FRONTSIDE;
  26746. },
  26747. enumerable: true,
  26748. configurable: true
  26749. });
  26750. Object.defineProperty(Mesh, "BACKSIDE", {
  26751. /**
  26752. * Mesh side orientation : usually the internal or back surface
  26753. */
  26754. get: function () {
  26755. return Mesh._BACKSIDE;
  26756. },
  26757. enumerable: true,
  26758. configurable: true
  26759. });
  26760. Object.defineProperty(Mesh, "DOUBLESIDE", {
  26761. /**
  26762. * Mesh side orientation : both internal and external or front and back surfaces
  26763. */
  26764. get: function () {
  26765. return Mesh._DOUBLESIDE;
  26766. },
  26767. enumerable: true,
  26768. configurable: true
  26769. });
  26770. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  26771. /**
  26772. * Mesh side orientation : by default, `FRONTSIDE`
  26773. */
  26774. get: function () {
  26775. return Mesh._DEFAULTSIDE;
  26776. },
  26777. enumerable: true,
  26778. configurable: true
  26779. });
  26780. Object.defineProperty(Mesh, "NO_CAP", {
  26781. /**
  26782. * Mesh cap setting : no cap
  26783. */
  26784. get: function () {
  26785. return Mesh._NO_CAP;
  26786. },
  26787. enumerable: true,
  26788. configurable: true
  26789. });
  26790. Object.defineProperty(Mesh, "CAP_START", {
  26791. /**
  26792. * Mesh cap setting : one cap at the beginning of the mesh
  26793. */
  26794. get: function () {
  26795. return Mesh._CAP_START;
  26796. },
  26797. enumerable: true,
  26798. configurable: true
  26799. });
  26800. Object.defineProperty(Mesh, "CAP_END", {
  26801. /**
  26802. * Mesh cap setting : one cap at the end of the mesh
  26803. */
  26804. get: function () {
  26805. return Mesh._CAP_END;
  26806. },
  26807. enumerable: true,
  26808. configurable: true
  26809. });
  26810. Object.defineProperty(Mesh, "CAP_ALL", {
  26811. /**
  26812. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  26813. */
  26814. get: function () {
  26815. return Mesh._CAP_ALL;
  26816. },
  26817. enumerable: true,
  26818. configurable: true
  26819. });
  26820. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  26821. set: function (callback) {
  26822. if (this._onBeforeDrawObserver) {
  26823. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  26824. }
  26825. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  26826. },
  26827. enumerable: true,
  26828. configurable: true
  26829. });
  26830. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  26831. get: function () {
  26832. return this._morphTargetManager;
  26833. },
  26834. set: function (value) {
  26835. if (this._morphTargetManager === value) {
  26836. return;
  26837. }
  26838. this._morphTargetManager = value;
  26839. this._syncGeometryWithMorphTargetManager();
  26840. },
  26841. enumerable: true,
  26842. configurable: true
  26843. });
  26844. Object.defineProperty(Mesh.prototype, "source", {
  26845. get: function () {
  26846. return this._source;
  26847. },
  26848. enumerable: true,
  26849. configurable: true
  26850. });
  26851. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  26852. get: function () {
  26853. return this._unIndexed;
  26854. },
  26855. set: function (value) {
  26856. if (this._unIndexed !== value) {
  26857. this._unIndexed = value;
  26858. this._markSubMeshesAsAttributesDirty();
  26859. }
  26860. },
  26861. enumerable: true,
  26862. configurable: true
  26863. });
  26864. // Methods
  26865. /**
  26866. * Returns the string "Mesh".
  26867. */
  26868. Mesh.prototype.getClassName = function () {
  26869. return "Mesh";
  26870. };
  26871. /**
  26872. * Returns a string.
  26873. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  26874. */
  26875. Mesh.prototype.toString = function (fullDetails) {
  26876. var ret = _super.prototype.toString.call(this, fullDetails);
  26877. ret += ", n vertices: " + this.getTotalVertices();
  26878. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  26879. if (this.animations) {
  26880. for (var i = 0; i < this.animations.length; i++) {
  26881. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  26882. }
  26883. }
  26884. if (fullDetails) {
  26885. if (this._geometry) {
  26886. var ib = this.getIndices();
  26887. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  26888. if (vb && ib) {
  26889. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  26890. }
  26891. }
  26892. else {
  26893. ret += ", flat shading: UNKNOWN";
  26894. }
  26895. }
  26896. return ret;
  26897. };
  26898. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  26899. /**
  26900. * True if the mesh has some Levels Of Details (LOD).
  26901. * Returns a boolean.
  26902. */
  26903. get: function () {
  26904. return this._LODLevels.length > 0;
  26905. },
  26906. enumerable: true,
  26907. configurable: true
  26908. });
  26909. /**
  26910. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  26911. * @returns an array of {BABYLON.MeshLODLevel}
  26912. */
  26913. Mesh.prototype.getLODLevels = function () {
  26914. return this._LODLevels;
  26915. };
  26916. Mesh.prototype._sortLODLevels = function () {
  26917. this._LODLevels.sort(function (a, b) {
  26918. if (a.distance < b.distance) {
  26919. return 1;
  26920. }
  26921. if (a.distance > b.distance) {
  26922. return -1;
  26923. }
  26924. return 0;
  26925. });
  26926. };
  26927. /**
  26928. * Add a mesh as LOD level triggered at the given distance.
  26929. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  26930. * @param {number} distance The distance from the center of the object to show this level
  26931. * @param {Mesh} mesh The mesh to be added as LOD level
  26932. * @return {Mesh} This mesh (for chaining)
  26933. */
  26934. Mesh.prototype.addLODLevel = function (distance, mesh) {
  26935. if (mesh && mesh._masterMesh) {
  26936. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  26937. return this;
  26938. }
  26939. var level = new BABYLON.MeshLODLevel(distance, mesh);
  26940. this._LODLevels.push(level);
  26941. if (mesh) {
  26942. mesh._masterMesh = this;
  26943. }
  26944. this._sortLODLevels();
  26945. return this;
  26946. };
  26947. /**
  26948. * Returns the LOD level mesh at the passed distance or null if not found.
  26949. * It is related to the method `addLODLevel(distance, mesh)`.
  26950. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  26951. * Returns an object Mesh or `null`.
  26952. */
  26953. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  26954. for (var index = 0; index < this._LODLevels.length; index++) {
  26955. var level = this._LODLevels[index];
  26956. if (level.distance === distance) {
  26957. return level.mesh;
  26958. }
  26959. }
  26960. return null;
  26961. };
  26962. /**
  26963. * Remove a mesh from the LOD array
  26964. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  26965. * @param {Mesh} mesh The mesh to be removed.
  26966. * @return {Mesh} This mesh (for chaining)
  26967. */
  26968. Mesh.prototype.removeLODLevel = function (mesh) {
  26969. for (var index = 0; index < this._LODLevels.length; index++) {
  26970. if (this._LODLevels[index].mesh === mesh) {
  26971. this._LODLevels.splice(index, 1);
  26972. if (mesh) {
  26973. mesh._masterMesh = null;
  26974. }
  26975. }
  26976. }
  26977. this._sortLODLevels();
  26978. return this;
  26979. };
  26980. /**
  26981. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  26982. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  26983. */
  26984. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  26985. if (!this._LODLevels || this._LODLevels.length === 0) {
  26986. return this;
  26987. }
  26988. var bSphere;
  26989. if (boundingSphere) {
  26990. bSphere = boundingSphere;
  26991. }
  26992. else {
  26993. var boundingInfo = this.getBoundingInfo();
  26994. bSphere = boundingInfo.boundingSphere;
  26995. }
  26996. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  26997. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  26998. if (this.onLODLevelSelection) {
  26999. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  27000. }
  27001. return this;
  27002. }
  27003. for (var index = 0; index < this._LODLevels.length; index++) {
  27004. var level = this._LODLevels[index];
  27005. if (level.distance < distanceToCamera) {
  27006. if (level.mesh) {
  27007. level.mesh._preActivate();
  27008. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  27009. }
  27010. if (this.onLODLevelSelection) {
  27011. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  27012. }
  27013. return level.mesh;
  27014. }
  27015. }
  27016. if (this.onLODLevelSelection) {
  27017. this.onLODLevelSelection(distanceToCamera, this, this);
  27018. }
  27019. return this;
  27020. };
  27021. Object.defineProperty(Mesh.prototype, "geometry", {
  27022. /**
  27023. * Returns the mesh internal Geometry object.
  27024. */
  27025. get: function () {
  27026. return this._geometry;
  27027. },
  27028. enumerable: true,
  27029. configurable: true
  27030. });
  27031. /**
  27032. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  27033. */
  27034. Mesh.prototype.getTotalVertices = function () {
  27035. if (this._geometry === null || this._geometry === undefined) {
  27036. return 0;
  27037. }
  27038. return this._geometry.getTotalVertices();
  27039. };
  27040. /**
  27041. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  27042. * 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.
  27043. * You can force the copy with forceCopy === true
  27044. * Returns null if the mesh has no geometry or no vertex buffer.
  27045. * Possible `kind` values :
  27046. * - BABYLON.VertexBuffer.PositionKind
  27047. * - BABYLON.VertexBuffer.UVKind
  27048. * - BABYLON.VertexBuffer.UV2Kind
  27049. * - BABYLON.VertexBuffer.UV3Kind
  27050. * - BABYLON.VertexBuffer.UV4Kind
  27051. * - BABYLON.VertexBuffer.UV5Kind
  27052. * - BABYLON.VertexBuffer.UV6Kind
  27053. * - BABYLON.VertexBuffer.ColorKind
  27054. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27055. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27056. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27057. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27058. */
  27059. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  27060. if (!this._geometry) {
  27061. return null;
  27062. }
  27063. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  27064. };
  27065. /**
  27066. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  27067. * Returns `null` if the mesh has no geometry.
  27068. * Possible `kind` values :
  27069. * - BABYLON.VertexBuffer.PositionKind
  27070. * - BABYLON.VertexBuffer.UVKind
  27071. * - BABYLON.VertexBuffer.UV2Kind
  27072. * - BABYLON.VertexBuffer.UV3Kind
  27073. * - BABYLON.VertexBuffer.UV4Kind
  27074. * - BABYLON.VertexBuffer.UV5Kind
  27075. * - BABYLON.VertexBuffer.UV6Kind
  27076. * - BABYLON.VertexBuffer.ColorKind
  27077. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27078. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27079. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27080. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27081. */
  27082. Mesh.prototype.getVertexBuffer = function (kind) {
  27083. if (!this._geometry) {
  27084. return null;
  27085. }
  27086. return this._geometry.getVertexBuffer(kind);
  27087. };
  27088. /**
  27089. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  27090. * Possible `kind` values :
  27091. * - BABYLON.VertexBuffer.PositionKind
  27092. * - BABYLON.VertexBuffer.UVKind
  27093. * - BABYLON.VertexBuffer.UV2Kind
  27094. * - BABYLON.VertexBuffer.UV3Kind
  27095. * - BABYLON.VertexBuffer.UV4Kind
  27096. * - BABYLON.VertexBuffer.UV5Kind
  27097. * - BABYLON.VertexBuffer.UV6Kind
  27098. * - BABYLON.VertexBuffer.ColorKind
  27099. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27100. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27101. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27102. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27103. */
  27104. Mesh.prototype.isVerticesDataPresent = function (kind) {
  27105. if (!this._geometry) {
  27106. if (this._delayInfo) {
  27107. return this._delayInfo.indexOf(kind) !== -1;
  27108. }
  27109. return false;
  27110. }
  27111. return this._geometry.isVerticesDataPresent(kind);
  27112. };
  27113. /**
  27114. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  27115. * Possible `kind` values :
  27116. * - BABYLON.VertexBuffer.PositionKind
  27117. * - BABYLON.VertexBuffer.UVKind
  27118. * - BABYLON.VertexBuffer.UV2Kind
  27119. * - BABYLON.VertexBuffer.UV3Kind
  27120. * - BABYLON.VertexBuffer.UV4Kind
  27121. * - BABYLON.VertexBuffer.UV5Kind
  27122. * - BABYLON.VertexBuffer.UV6Kind
  27123. * - BABYLON.VertexBuffer.ColorKind
  27124. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27125. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27126. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27127. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27128. */
  27129. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  27130. if (!this._geometry) {
  27131. if (this._delayInfo) {
  27132. return this._delayInfo.indexOf(kind) !== -1;
  27133. }
  27134. return false;
  27135. }
  27136. return this._geometry.isVertexBufferUpdatable(kind);
  27137. };
  27138. /**
  27139. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  27140. * Possible `kind` values :
  27141. * - BABYLON.VertexBuffer.PositionKind
  27142. * - BABYLON.VertexBuffer.UVKind
  27143. * - BABYLON.VertexBuffer.UV2Kind
  27144. * - BABYLON.VertexBuffer.UV3Kind
  27145. * - BABYLON.VertexBuffer.UV4Kind
  27146. * - BABYLON.VertexBuffer.UV5Kind
  27147. * - BABYLON.VertexBuffer.UV6Kind
  27148. * - BABYLON.VertexBuffer.ColorKind
  27149. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27150. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27151. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27152. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27153. */
  27154. Mesh.prototype.getVerticesDataKinds = function () {
  27155. if (!this._geometry) {
  27156. var result = new Array();
  27157. if (this._delayInfo) {
  27158. this._delayInfo.forEach(function (kind, index, array) {
  27159. result.push(kind);
  27160. });
  27161. }
  27162. return result;
  27163. }
  27164. return this._geometry.getVerticesDataKinds();
  27165. };
  27166. /**
  27167. * Returns a positive integer : the total number of indices in this mesh geometry.
  27168. * Returns zero if the mesh has no geometry.
  27169. */
  27170. Mesh.prototype.getTotalIndices = function () {
  27171. if (!this._geometry) {
  27172. return 0;
  27173. }
  27174. return this._geometry.getTotalIndices();
  27175. };
  27176. /**
  27177. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  27178. * 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.
  27179. * Returns an empty array if the mesh has no geometry.
  27180. */
  27181. Mesh.prototype.getIndices = function (copyWhenShared) {
  27182. if (!this._geometry) {
  27183. return [];
  27184. }
  27185. return this._geometry.getIndices(copyWhenShared);
  27186. };
  27187. Object.defineProperty(Mesh.prototype, "isBlocked", {
  27188. get: function () {
  27189. return this._masterMesh !== null && this._masterMesh !== undefined;
  27190. },
  27191. enumerable: true,
  27192. configurable: true
  27193. });
  27194. /**
  27195. * Determine if the current mesh is ready to be rendered
  27196. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  27197. * @returns true if all associated assets are ready (material, textures, shaders)
  27198. */
  27199. Mesh.prototype.isReady = function (forceInstanceSupport) {
  27200. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  27201. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  27202. return false;
  27203. }
  27204. if (!_super.prototype.isReady.call(this)) {
  27205. return false;
  27206. }
  27207. if (!this.subMeshes || this.subMeshes.length === 0) {
  27208. return true;
  27209. }
  27210. var engine = this.getEngine();
  27211. var scene = this.getScene();
  27212. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  27213. this.computeWorldMatrix();
  27214. var mat = this.material || scene.defaultMaterial;
  27215. if (mat) {
  27216. if (mat.storeEffectOnSubMeshes) {
  27217. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  27218. var subMesh = _a[_i];
  27219. var effectiveMaterial = subMesh.getMaterial();
  27220. if (effectiveMaterial) {
  27221. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  27222. return false;
  27223. }
  27224. }
  27225. }
  27226. }
  27227. else {
  27228. if (!mat.isReady(this, hardwareInstancedRendering)) {
  27229. return false;
  27230. }
  27231. }
  27232. }
  27233. // Shadows
  27234. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  27235. var light = _c[_b];
  27236. var generator = light.getShadowGenerator();
  27237. if (generator) {
  27238. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  27239. var subMesh = _e[_d];
  27240. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  27241. return false;
  27242. }
  27243. }
  27244. }
  27245. }
  27246. // LOD
  27247. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  27248. var lod = _g[_f];
  27249. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  27250. return false;
  27251. }
  27252. }
  27253. return true;
  27254. };
  27255. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  27256. /**
  27257. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  27258. * This property is pertinent only for updatable parametric shapes.
  27259. */
  27260. get: function () {
  27261. return this._areNormalsFrozen;
  27262. },
  27263. enumerable: true,
  27264. configurable: true
  27265. });
  27266. /**
  27267. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  27268. * It has no effect at all on other shapes.
  27269. * It prevents the mesh normals from being recomputed on next `positions` array update.
  27270. * Returns the Mesh.
  27271. */
  27272. Mesh.prototype.freezeNormals = function () {
  27273. this._areNormalsFrozen = true;
  27274. return this;
  27275. };
  27276. /**
  27277. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  27278. * It has no effect at all on other shapes.
  27279. * It reactivates the mesh normals computation if it was previously frozen.
  27280. * Returns the Mesh.
  27281. */
  27282. Mesh.prototype.unfreezeNormals = function () {
  27283. this._areNormalsFrozen = false;
  27284. return this;
  27285. };
  27286. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  27287. /**
  27288. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  27289. */
  27290. set: function (count) {
  27291. this._overridenInstanceCount = count;
  27292. },
  27293. enumerable: true,
  27294. configurable: true
  27295. });
  27296. // Methods
  27297. Mesh.prototype._preActivate = function () {
  27298. var sceneRenderId = this.getScene().getRenderId();
  27299. if (this._preActivateId === sceneRenderId) {
  27300. return this;
  27301. }
  27302. this._preActivateId = sceneRenderId;
  27303. this._visibleInstances = null;
  27304. return this;
  27305. };
  27306. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  27307. if (this._visibleInstances) {
  27308. this._visibleInstances.intermediateDefaultRenderId = renderId;
  27309. }
  27310. return this;
  27311. };
  27312. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  27313. if (!this._visibleInstances) {
  27314. this._visibleInstances = {};
  27315. this._visibleInstances.defaultRenderId = renderId;
  27316. this._visibleInstances.selfDefaultRenderId = this._renderId;
  27317. }
  27318. if (!this._visibleInstances[renderId]) {
  27319. this._visibleInstances[renderId] = new Array();
  27320. }
  27321. this._visibleInstances[renderId].push(instance);
  27322. return this;
  27323. };
  27324. /**
  27325. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  27326. * This means the mesh underlying bounding box and sphere are recomputed.
  27327. * Returns the Mesh.
  27328. */
  27329. Mesh.prototype.refreshBoundingInfo = function () {
  27330. return this._refreshBoundingInfo(false);
  27331. };
  27332. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  27333. if (this._boundingInfo && this._boundingInfo.isLocked) {
  27334. return this;
  27335. }
  27336. var data = this._getPositionData(applySkeleton);
  27337. if (data) {
  27338. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  27339. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  27340. }
  27341. if (this.subMeshes) {
  27342. for (var index = 0; index < this.subMeshes.length; index++) {
  27343. this.subMeshes[index].refreshBoundingInfo();
  27344. }
  27345. }
  27346. this._updateBoundingInfo();
  27347. return this;
  27348. };
  27349. Mesh.prototype._getPositionData = function (applySkeleton) {
  27350. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27351. if (data && applySkeleton && this.skeleton) {
  27352. data = BABYLON.Tools.Slice(data);
  27353. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  27354. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  27355. if (matricesWeightsData && matricesIndicesData) {
  27356. var needExtras = this.numBoneInfluencers > 4;
  27357. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  27358. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  27359. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  27360. var tempVector = BABYLON.Tmp.Vector3[0];
  27361. var finalMatrix = BABYLON.Tmp.Matrix[0];
  27362. var tempMatrix = BABYLON.Tmp.Matrix[1];
  27363. var matWeightIdx = 0;
  27364. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  27365. finalMatrix.reset();
  27366. var inf;
  27367. var weight;
  27368. for (inf = 0; inf < 4; inf++) {
  27369. weight = matricesWeightsData[matWeightIdx + inf];
  27370. if (weight <= 0)
  27371. break;
  27372. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  27373. finalMatrix.addToSelf(tempMatrix);
  27374. }
  27375. if (needExtras) {
  27376. for (inf = 0; inf < 4; inf++) {
  27377. weight = matricesWeightsExtraData[matWeightIdx + inf];
  27378. if (weight <= 0)
  27379. break;
  27380. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  27381. finalMatrix.addToSelf(tempMatrix);
  27382. }
  27383. }
  27384. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  27385. tempVector.toArray(data, index);
  27386. }
  27387. }
  27388. }
  27389. return data;
  27390. };
  27391. Mesh.prototype._createGlobalSubMesh = function (force) {
  27392. var totalVertices = this.getTotalVertices();
  27393. if (!totalVertices || !this.getIndices()) {
  27394. return null;
  27395. }
  27396. // Check if we need to recreate the submeshes
  27397. if (this.subMeshes && this.subMeshes.length > 0) {
  27398. var ib = this.getIndices();
  27399. if (!ib) {
  27400. return null;
  27401. }
  27402. var totalIndices = ib.length;
  27403. var needToRecreate = false;
  27404. if (force) {
  27405. needToRecreate = true;
  27406. }
  27407. else {
  27408. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  27409. var submesh = _a[_i];
  27410. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  27411. needToRecreate = true;
  27412. break;
  27413. }
  27414. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  27415. needToRecreate = true;
  27416. break;
  27417. }
  27418. }
  27419. }
  27420. if (!needToRecreate) {
  27421. return this.subMeshes[0];
  27422. }
  27423. }
  27424. this.releaseSubMeshes();
  27425. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  27426. };
  27427. Mesh.prototype.subdivide = function (count) {
  27428. if (count < 1) {
  27429. return;
  27430. }
  27431. var totalIndices = this.getTotalIndices();
  27432. var subdivisionSize = (totalIndices / count) | 0;
  27433. var offset = 0;
  27434. // Ensure that subdivisionSize is a multiple of 3
  27435. while (subdivisionSize % 3 !== 0) {
  27436. subdivisionSize++;
  27437. }
  27438. this.releaseSubMeshes();
  27439. for (var index = 0; index < count; index++) {
  27440. if (offset >= totalIndices) {
  27441. break;
  27442. }
  27443. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  27444. offset += subdivisionSize;
  27445. }
  27446. this.synchronizeInstances();
  27447. };
  27448. /**
  27449. * Sets the vertex data of the mesh geometry for the requested `kind`.
  27450. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  27451. * The `data` are either a numeric array either a Float32Array.
  27452. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  27453. * 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).
  27454. * Note that a new underlying VertexBuffer object is created each call.
  27455. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  27456. *
  27457. * Possible `kind` values :
  27458. * - BABYLON.VertexBuffer.PositionKind
  27459. * - BABYLON.VertexBuffer.UVKind
  27460. * - BABYLON.VertexBuffer.UV2Kind
  27461. * - BABYLON.VertexBuffer.UV3Kind
  27462. * - BABYLON.VertexBuffer.UV4Kind
  27463. * - BABYLON.VertexBuffer.UV5Kind
  27464. * - BABYLON.VertexBuffer.UV6Kind
  27465. * - BABYLON.VertexBuffer.ColorKind
  27466. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27467. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27468. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27469. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27470. *
  27471. * Returns the Mesh.
  27472. */
  27473. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  27474. if (updatable === void 0) { updatable = false; }
  27475. if (!this._geometry) {
  27476. var vertexData = new BABYLON.VertexData();
  27477. vertexData.set(data, kind);
  27478. var scene = this.getScene();
  27479. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  27480. }
  27481. else {
  27482. this._geometry.setVerticesData(kind, data, updatable, stride);
  27483. }
  27484. return this;
  27485. };
  27486. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  27487. if (updatable === void 0) { updatable = true; }
  27488. var vb = this.getVertexBuffer(kind);
  27489. if (!vb || vb.isUpdatable() === updatable) {
  27490. return;
  27491. }
  27492. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  27493. };
  27494. /**
  27495. * Sets the mesh VertexBuffer.
  27496. * Returns the Mesh.
  27497. */
  27498. Mesh.prototype.setVerticesBuffer = function (buffer) {
  27499. if (!this._geometry) {
  27500. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  27501. }
  27502. this._geometry.setVerticesBuffer(buffer);
  27503. return this;
  27504. };
  27505. /**
  27506. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  27507. * If the mesh has no geometry, it is simply returned as it is.
  27508. * The `data` are either a numeric array either a Float32Array.
  27509. * No new underlying VertexBuffer object is created.
  27510. * 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.
  27511. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  27512. *
  27513. * Possible `kind` values :
  27514. * - BABYLON.VertexBuffer.PositionKind
  27515. * - BABYLON.VertexBuffer.UVKind
  27516. * - BABYLON.VertexBuffer.UV2Kind
  27517. * - BABYLON.VertexBuffer.UV3Kind
  27518. * - BABYLON.VertexBuffer.UV4Kind
  27519. * - BABYLON.VertexBuffer.UV5Kind
  27520. * - BABYLON.VertexBuffer.UV6Kind
  27521. * - BABYLON.VertexBuffer.ColorKind
  27522. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27523. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27524. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27525. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27526. *
  27527. * Returns the Mesh.
  27528. */
  27529. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  27530. if (!this._geometry) {
  27531. return this;
  27532. }
  27533. if (!makeItUnique) {
  27534. this._geometry.updateVerticesData(kind, data, updateExtends);
  27535. }
  27536. else {
  27537. this.makeGeometryUnique();
  27538. this.updateVerticesData(kind, data, updateExtends, false);
  27539. }
  27540. return this;
  27541. };
  27542. /**
  27543. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  27544. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  27545. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  27546. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  27547. * Returns the Mesh.
  27548. */
  27549. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  27550. if (computeNormals === void 0) { computeNormals = true; }
  27551. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27552. if (!positions) {
  27553. return this;
  27554. }
  27555. positionFunction(positions);
  27556. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  27557. if (computeNormals) {
  27558. var indices = this.getIndices();
  27559. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  27560. if (!normals) {
  27561. return this;
  27562. }
  27563. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  27564. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  27565. }
  27566. return this;
  27567. };
  27568. /**
  27569. * Creates a un-shared specific occurence of the geometry for the mesh.
  27570. * Returns the Mesh.
  27571. */
  27572. Mesh.prototype.makeGeometryUnique = function () {
  27573. if (!this._geometry) {
  27574. return this;
  27575. }
  27576. var oldGeometry = this._geometry;
  27577. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  27578. oldGeometry.releaseForMesh(this, true);
  27579. geometry.applyToMesh(this);
  27580. return this;
  27581. };
  27582. /**
  27583. * Sets the mesh indices.
  27584. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  27585. * Type is Uint16Array by default unless the mesh has more than 65536 vertices.
  27586. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  27587. * This method creates a new index buffer each call.
  27588. * Returns the Mesh.
  27589. */
  27590. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  27591. if (totalVertices === void 0) { totalVertices = null; }
  27592. if (updatable === void 0) { updatable = false; }
  27593. if (!this._geometry) {
  27594. var vertexData = new BABYLON.VertexData();
  27595. vertexData.indices = indices;
  27596. var scene = this.getScene();
  27597. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  27598. }
  27599. else {
  27600. this._geometry.setIndices(indices, totalVertices, updatable);
  27601. }
  27602. return this;
  27603. };
  27604. /**
  27605. * Update the current index buffer
  27606. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  27607. * Returns the Mesh.
  27608. */
  27609. Mesh.prototype.updateIndices = function (indices, offset) {
  27610. if (!this._geometry) {
  27611. return this;
  27612. }
  27613. this._geometry.updateIndices(indices, offset);
  27614. return this;
  27615. };
  27616. /**
  27617. * Invert the geometry to move from a right handed system to a left handed one.
  27618. * Returns the Mesh.
  27619. */
  27620. Mesh.prototype.toLeftHanded = function () {
  27621. if (!this._geometry) {
  27622. return this;
  27623. }
  27624. this._geometry.toLeftHanded();
  27625. return this;
  27626. };
  27627. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  27628. if (!this._geometry) {
  27629. return this;
  27630. }
  27631. var engine = this.getScene().getEngine();
  27632. // Wireframe
  27633. var indexToBind;
  27634. if (this._unIndexed) {
  27635. indexToBind = null;
  27636. }
  27637. else {
  27638. switch (fillMode) {
  27639. case BABYLON.Material.PointFillMode:
  27640. indexToBind = null;
  27641. break;
  27642. case BABYLON.Material.WireFrameFillMode:
  27643. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  27644. break;
  27645. default:
  27646. case BABYLON.Material.TriangleFillMode:
  27647. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  27648. break;
  27649. }
  27650. }
  27651. // VBOs
  27652. this._geometry._bind(effect, indexToBind);
  27653. return this;
  27654. };
  27655. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  27656. if (alternate === void 0) { alternate = false; }
  27657. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  27658. return this;
  27659. }
  27660. this.onBeforeDrawObservable.notifyObservers(this);
  27661. var scene = this.getScene();
  27662. var engine = scene.getEngine();
  27663. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  27664. // or triangles as points
  27665. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  27666. }
  27667. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  27668. // Triangles as wireframe
  27669. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  27670. }
  27671. else {
  27672. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  27673. }
  27674. if (scene._isAlternateRenderingEnabled && !alternate) {
  27675. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  27676. if (!effect || !scene.activeCamera) {
  27677. return this;
  27678. }
  27679. scene._switchToAlternateCameraConfiguration(true);
  27680. this._effectiveMaterial.bindView(effect);
  27681. this._effectiveMaterial.bindViewProjection(effect);
  27682. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  27683. this._draw(subMesh, fillMode, instancesCount, true);
  27684. engine.setViewport(scene.activeCamera.viewport);
  27685. scene._switchToAlternateCameraConfiguration(false);
  27686. this._effectiveMaterial.bindView(effect);
  27687. this._effectiveMaterial.bindViewProjection(effect);
  27688. }
  27689. return this;
  27690. };
  27691. /**
  27692. * Registers for this mesh a javascript function called just before the rendering process.
  27693. * This function is passed the current mesh.
  27694. * Return the Mesh.
  27695. */
  27696. Mesh.prototype.registerBeforeRender = function (func) {
  27697. this.onBeforeRenderObservable.add(func);
  27698. return this;
  27699. };
  27700. /**
  27701. * Disposes a previously registered javascript function called before the rendering.
  27702. * This function is passed the current mesh.
  27703. * Returns the Mesh.
  27704. */
  27705. Mesh.prototype.unregisterBeforeRender = function (func) {
  27706. this.onBeforeRenderObservable.removeCallback(func);
  27707. return this;
  27708. };
  27709. /**
  27710. * Registers for this mesh a javascript function called just after the rendering is complete.
  27711. * This function is passed the current mesh.
  27712. * Returns the Mesh.
  27713. */
  27714. Mesh.prototype.registerAfterRender = function (func) {
  27715. this.onAfterRenderObservable.add(func);
  27716. return this;
  27717. };
  27718. /**
  27719. * Disposes a previously registered javascript function called after the rendering.
  27720. * This function is passed the current mesh.
  27721. * Return the Mesh.
  27722. */
  27723. Mesh.prototype.unregisterAfterRender = function (func) {
  27724. this.onAfterRenderObservable.removeCallback(func);
  27725. return this;
  27726. };
  27727. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  27728. var scene = this.getScene();
  27729. this._batchCache.mustReturn = false;
  27730. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  27731. this._batchCache.visibleInstances[subMeshId] = null;
  27732. if (this._visibleInstances) {
  27733. var currentRenderId = scene.getRenderId();
  27734. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  27735. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  27736. var selfRenderId = this._renderId;
  27737. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  27738. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  27739. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  27740. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  27741. }
  27742. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  27743. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  27744. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  27745. this._batchCache.mustReturn = true;
  27746. return this._batchCache;
  27747. }
  27748. if (currentRenderId !== selfRenderId) {
  27749. this._batchCache.renderSelf[subMeshId] = false;
  27750. }
  27751. }
  27752. this._renderIdForInstances[subMeshId] = currentRenderId;
  27753. }
  27754. return this._batchCache;
  27755. };
  27756. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  27757. var visibleInstances = batch.visibleInstances[subMesh._id];
  27758. if (!visibleInstances) {
  27759. return this;
  27760. }
  27761. var matricesCount = visibleInstances.length + 1;
  27762. var bufferSize = matricesCount * 16 * 4;
  27763. var currentInstancesBufferSize = this._instancesBufferSize;
  27764. var instancesBuffer = this._instancesBuffer;
  27765. while (this._instancesBufferSize < bufferSize) {
  27766. this._instancesBufferSize *= 2;
  27767. }
  27768. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  27769. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  27770. }
  27771. var offset = 0;
  27772. var instancesCount = 0;
  27773. var world = this.getWorldMatrix();
  27774. if (batch.renderSelf[subMesh._id]) {
  27775. world.copyToArray(this._instancesData, offset);
  27776. offset += 16;
  27777. instancesCount++;
  27778. }
  27779. if (visibleInstances) {
  27780. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  27781. var instance = visibleInstances[instanceIndex];
  27782. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  27783. offset += 16;
  27784. instancesCount++;
  27785. }
  27786. }
  27787. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  27788. if (instancesBuffer) {
  27789. instancesBuffer.dispose();
  27790. }
  27791. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  27792. this._instancesBuffer = instancesBuffer;
  27793. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  27794. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  27795. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  27796. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  27797. }
  27798. else {
  27799. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  27800. }
  27801. this._bind(subMesh, effect, fillMode);
  27802. this._draw(subMesh, fillMode, instancesCount);
  27803. engine.unbindInstanceAttributes();
  27804. return this;
  27805. };
  27806. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  27807. var scene = this.getScene();
  27808. var engine = scene.getEngine();
  27809. if (hardwareInstancedRendering) {
  27810. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  27811. }
  27812. else {
  27813. if (batch.renderSelf[subMesh._id]) {
  27814. // Draw
  27815. if (onBeforeDraw) {
  27816. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  27817. }
  27818. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  27819. }
  27820. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  27821. if (visibleInstancesForSubMesh) {
  27822. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  27823. var instance = visibleInstancesForSubMesh[instanceIndex];
  27824. // World
  27825. var world = instance.getWorldMatrix();
  27826. if (onBeforeDraw) {
  27827. onBeforeDraw(true, world, effectiveMaterial);
  27828. }
  27829. // Draw
  27830. this._draw(subMesh, fillMode);
  27831. }
  27832. }
  27833. }
  27834. return this;
  27835. };
  27836. /**
  27837. * Triggers the draw call for the mesh.
  27838. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  27839. * Returns the Mesh.
  27840. */
  27841. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  27842. this.checkOcclusionQuery();
  27843. if (this._isOccluded) {
  27844. return this;
  27845. }
  27846. var scene = this.getScene();
  27847. // Managing instances
  27848. var batch = this._getInstancesRenderList(subMesh._id);
  27849. if (batch.mustReturn) {
  27850. return this;
  27851. }
  27852. // Checking geometry state
  27853. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  27854. return this;
  27855. }
  27856. this.onBeforeRenderObservable.notifyObservers(this);
  27857. var engine = scene.getEngine();
  27858. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  27859. // Material
  27860. var material = subMesh.getMaterial();
  27861. if (!material) {
  27862. return this;
  27863. }
  27864. this._effectiveMaterial = material;
  27865. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  27866. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  27867. return this;
  27868. }
  27869. }
  27870. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  27871. return this;
  27872. }
  27873. // Alpha mode
  27874. if (enableAlphaMode) {
  27875. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  27876. }
  27877. // Outline - step 1
  27878. var savedDepthWrite = engine.getDepthWrite();
  27879. if (this.renderOutline) {
  27880. engine.setDepthWrite(false);
  27881. scene.getOutlineRenderer().render(subMesh, batch);
  27882. engine.setDepthWrite(savedDepthWrite);
  27883. }
  27884. var effect;
  27885. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  27886. effect = subMesh.effect;
  27887. }
  27888. else {
  27889. effect = this._effectiveMaterial.getEffect();
  27890. }
  27891. if (!effect) {
  27892. return this;
  27893. }
  27894. var sideOrientation = this.overrideMaterialSideOrientation;
  27895. if (sideOrientation == null) {
  27896. sideOrientation = this._effectiveMaterial.sideOrientation;
  27897. if (this._getWorldMatrixDeterminant() < 0) {
  27898. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  27899. }
  27900. }
  27901. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  27902. if (this._effectiveMaterial.forceDepthWrite) {
  27903. engine.setDepthWrite(true);
  27904. }
  27905. // Bind
  27906. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  27907. if (!hardwareInstancedRendering) {
  27908. this._bind(subMesh, effect, fillMode);
  27909. }
  27910. var world = this.getWorldMatrix();
  27911. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  27912. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  27913. }
  27914. else {
  27915. this._effectiveMaterial.bind(world, this);
  27916. }
  27917. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  27918. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  27919. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  27920. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  27921. }
  27922. // Draw
  27923. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  27924. // Unbind
  27925. this._effectiveMaterial.unbind();
  27926. // Outline - step 2
  27927. if (this.renderOutline && savedDepthWrite) {
  27928. engine.setDepthWrite(true);
  27929. engine.setColorWrite(false);
  27930. scene.getOutlineRenderer().render(subMesh, batch);
  27931. engine.setColorWrite(true);
  27932. }
  27933. // Overlay
  27934. if (this.renderOverlay) {
  27935. var currentMode = engine.getAlphaMode();
  27936. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  27937. scene.getOutlineRenderer().render(subMesh, batch, true);
  27938. engine.setAlphaMode(currentMode);
  27939. }
  27940. this.onAfterRenderObservable.notifyObservers(this);
  27941. return this;
  27942. };
  27943. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  27944. if (isInstance && effectiveMaterial) {
  27945. effectiveMaterial.bindOnlyWorldMatrix(world);
  27946. }
  27947. };
  27948. /**
  27949. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  27950. */
  27951. Mesh.prototype.getEmittedParticleSystems = function () {
  27952. var results = new Array();
  27953. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  27954. var particleSystem = this.getScene().particleSystems[index];
  27955. if (particleSystem.emitter === this) {
  27956. results.push(particleSystem);
  27957. }
  27958. }
  27959. return results;
  27960. };
  27961. /**
  27962. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  27963. */
  27964. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  27965. var results = new Array();
  27966. var descendants = this.getDescendants();
  27967. descendants.push(this);
  27968. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  27969. var particleSystem = this.getScene().particleSystems[index];
  27970. var emitter = particleSystem.emitter;
  27971. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  27972. results.push(particleSystem);
  27973. }
  27974. }
  27975. return results;
  27976. };
  27977. Mesh.prototype._checkDelayState = function () {
  27978. var scene = this.getScene();
  27979. if (this._geometry) {
  27980. this._geometry.load(scene);
  27981. }
  27982. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  27983. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  27984. this._queueLoad(scene);
  27985. }
  27986. return this;
  27987. };
  27988. Mesh.prototype._queueLoad = function (scene) {
  27989. var _this = this;
  27990. scene._addPendingData(this);
  27991. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  27992. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  27993. if (data instanceof ArrayBuffer) {
  27994. _this._delayLoadingFunction(data, _this);
  27995. }
  27996. else {
  27997. _this._delayLoadingFunction(JSON.parse(data), _this);
  27998. }
  27999. _this.instances.forEach(function (instance) {
  28000. instance._syncSubMeshes();
  28001. });
  28002. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  28003. scene._removePendingData(_this);
  28004. }, function () { }, scene.database, getBinaryData);
  28005. return this;
  28006. };
  28007. /**
  28008. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  28009. */
  28010. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  28011. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  28012. return false;
  28013. }
  28014. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  28015. return false;
  28016. }
  28017. this._checkDelayState();
  28018. return true;
  28019. };
  28020. /**
  28021. * Sets the mesh material by the material or multiMaterial `id` property.
  28022. * The material `id` is a string identifying the material or the multiMaterial.
  28023. * This method returns the Mesh.
  28024. */
  28025. Mesh.prototype.setMaterialByID = function (id) {
  28026. var materials = this.getScene().materials;
  28027. var index;
  28028. for (index = materials.length - 1; index > -1; index--) {
  28029. if (materials[index].id === id) {
  28030. this.material = materials[index];
  28031. return this;
  28032. }
  28033. }
  28034. // Multi
  28035. var multiMaterials = this.getScene().multiMaterials;
  28036. for (index = multiMaterials.length - 1; index > -1; index--) {
  28037. if (multiMaterials[index].id === id) {
  28038. this.material = multiMaterials[index];
  28039. return this;
  28040. }
  28041. }
  28042. return this;
  28043. };
  28044. /**
  28045. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  28046. */
  28047. Mesh.prototype.getAnimatables = function () {
  28048. var results = new Array();
  28049. if (this.material) {
  28050. results.push(this.material);
  28051. }
  28052. if (this.skeleton) {
  28053. results.push(this.skeleton);
  28054. }
  28055. return results;
  28056. };
  28057. /**
  28058. * Modifies the mesh geometry according to the passed transformation matrix.
  28059. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  28060. * The mesh normals are modified accordingly the same transformation.
  28061. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  28062. * Note that, under the hood, this method sets a new VertexBuffer each call.
  28063. * Returns the Mesh.
  28064. */
  28065. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  28066. // Position
  28067. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  28068. return this;
  28069. }
  28070. var submeshes = this.subMeshes.splice(0);
  28071. this._resetPointsArrayCache();
  28072. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28073. var temp = new Array();
  28074. var index;
  28075. for (index = 0; index < data.length; index += 3) {
  28076. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  28077. }
  28078. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  28079. // Normals
  28080. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  28081. return this;
  28082. }
  28083. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28084. temp = [];
  28085. for (index = 0; index < data.length; index += 3) {
  28086. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  28087. }
  28088. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  28089. // flip faces?
  28090. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  28091. this.flipFaces();
  28092. }
  28093. // Restore submeshes
  28094. this.releaseSubMeshes();
  28095. this.subMeshes = submeshes;
  28096. return this;
  28097. };
  28098. /**
  28099. * Modifies the mesh geometry according to its own current World Matrix.
  28100. * The mesh World Matrix is then reset.
  28101. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  28102. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  28103. * Note that, under the hood, this method sets a new VertexBuffer each call.
  28104. * Returns the Mesh.
  28105. */
  28106. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  28107. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  28108. this.scaling.copyFromFloats(1, 1, 1);
  28109. this.position.copyFromFloats(0, 0, 0);
  28110. this.rotation.copyFromFloats(0, 0, 0);
  28111. //only if quaternion is already set
  28112. if (this.rotationQuaternion) {
  28113. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  28114. }
  28115. this._worldMatrix = BABYLON.Matrix.Identity();
  28116. return this;
  28117. };
  28118. Object.defineProperty(Mesh.prototype, "_positions", {
  28119. // Cache
  28120. get: function () {
  28121. if (this._geometry) {
  28122. return this._geometry._positions;
  28123. }
  28124. return null;
  28125. },
  28126. enumerable: true,
  28127. configurable: true
  28128. });
  28129. Mesh.prototype._resetPointsArrayCache = function () {
  28130. if (this._geometry) {
  28131. this._geometry._resetPointsArrayCache();
  28132. }
  28133. return this;
  28134. };
  28135. Mesh.prototype._generatePointsArray = function () {
  28136. if (this._geometry) {
  28137. return this._geometry._generatePointsArray();
  28138. }
  28139. return false;
  28140. };
  28141. /**
  28142. * Returns a new Mesh object generated from the current mesh properties.
  28143. * This method must not get confused with createInstance().
  28144. * The parameter `name` is a string, the name given to the new mesh.
  28145. * The optional parameter `newParent` can be any Node object (default `null`).
  28146. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  28147. * 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.
  28148. */
  28149. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  28150. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  28151. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  28152. };
  28153. /**
  28154. * Disposes the Mesh.
  28155. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  28156. * Returns nothing.
  28157. */
  28158. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  28159. var _this = this;
  28160. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  28161. this.morphTargetManager = null;
  28162. if (this._geometry) {
  28163. this._geometry.releaseForMesh(this, true);
  28164. }
  28165. // Sources
  28166. var meshes = this.getScene().meshes;
  28167. meshes.forEach(function (abstractMesh) {
  28168. var mesh = abstractMesh;
  28169. if (mesh._source && mesh._source === _this) {
  28170. mesh._source = null;
  28171. }
  28172. });
  28173. this._source = null;
  28174. // Instances
  28175. if (this._instancesBuffer) {
  28176. this._instancesBuffer.dispose();
  28177. this._instancesBuffer = null;
  28178. }
  28179. while (this.instances.length) {
  28180. this.instances[0].dispose();
  28181. }
  28182. // Effect layers.
  28183. var effectLayers = this.getScene().effectLayers;
  28184. for (var i = 0; i < effectLayers.length; i++) {
  28185. var effectLayer = effectLayers[i];
  28186. if (effectLayer) {
  28187. effectLayer._disposeMesh(this);
  28188. }
  28189. }
  28190. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  28191. };
  28192. /**
  28193. * Modifies the mesh geometry according to a displacement map.
  28194. * 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.
  28195. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  28196. * This method returns nothing.
  28197. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  28198. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  28199. * 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.
  28200. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  28201. * The parameter `uvScale` is an optional vector2 used to scale UV.
  28202. *
  28203. * Returns the Mesh.
  28204. */
  28205. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  28206. var _this = this;
  28207. var scene = this.getScene();
  28208. var onload = function (img) {
  28209. // Getting height map data
  28210. var canvas = document.createElement("canvas");
  28211. var context = canvas.getContext("2d");
  28212. var heightMapWidth = img.width;
  28213. var heightMapHeight = img.height;
  28214. canvas.width = heightMapWidth;
  28215. canvas.height = heightMapHeight;
  28216. context.drawImage(img, 0, 0);
  28217. // Create VertexData from map data
  28218. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  28219. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  28220. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  28221. //execute success callback, if set
  28222. if (onSuccess) {
  28223. onSuccess(_this);
  28224. }
  28225. };
  28226. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  28227. return this;
  28228. };
  28229. /**
  28230. * Modifies the mesh geometry according to a displacementMap buffer.
  28231. * 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.
  28232. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  28233. * This method returns nothing.
  28234. * 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.
  28235. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  28236. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  28237. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  28238. * The parameter `uvScale` is an optional vector2 used to scale UV.
  28239. *
  28240. * Returns the Mesh.
  28241. */
  28242. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  28243. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  28244. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  28245. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  28246. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  28247. return this;
  28248. }
  28249. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28250. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28251. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  28252. var position = BABYLON.Vector3.Zero();
  28253. var normal = BABYLON.Vector3.Zero();
  28254. var uv = BABYLON.Vector2.Zero();
  28255. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  28256. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  28257. for (var index = 0; index < positions.length; index += 3) {
  28258. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  28259. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  28260. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  28261. // Compute height
  28262. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  28263. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  28264. var pos = (u + v * heightMapWidth) * 4;
  28265. var r = buffer[pos] / 255.0;
  28266. var g = buffer[pos + 1] / 255.0;
  28267. var b = buffer[pos + 2] / 255.0;
  28268. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  28269. normal.normalize();
  28270. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  28271. position = position.add(normal);
  28272. position.toArray(positions, index);
  28273. }
  28274. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  28275. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  28276. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  28277. return this;
  28278. };
  28279. /**
  28280. * Modify the mesh to get a flat shading rendering.
  28281. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  28282. * This method returns the Mesh.
  28283. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  28284. */
  28285. Mesh.prototype.convertToFlatShadedMesh = function () {
  28286. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  28287. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  28288. var kinds = this.getVerticesDataKinds();
  28289. var vbs = {};
  28290. var data = {};
  28291. var newdata = {};
  28292. var updatableNormals = false;
  28293. var kindIndex;
  28294. var kind;
  28295. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  28296. kind = kinds[kindIndex];
  28297. var vertexBuffer = this.getVertexBuffer(kind);
  28298. if (kind === BABYLON.VertexBuffer.NormalKind) {
  28299. updatableNormals = vertexBuffer.isUpdatable();
  28300. kinds.splice(kindIndex, 1);
  28301. kindIndex--;
  28302. continue;
  28303. }
  28304. vbs[kind] = vertexBuffer;
  28305. data[kind] = vbs[kind].getData();
  28306. newdata[kind] = [];
  28307. }
  28308. // Save previous submeshes
  28309. var previousSubmeshes = this.subMeshes.slice(0);
  28310. var indices = this.getIndices();
  28311. var totalIndices = this.getTotalIndices();
  28312. // Generating unique vertices per face
  28313. var index;
  28314. for (index = 0; index < totalIndices; index++) {
  28315. var vertexIndex = indices[index];
  28316. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  28317. kind = kinds[kindIndex];
  28318. var stride = vbs[kind].getStrideSize();
  28319. for (var offset = 0; offset < stride; offset++) {
  28320. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  28321. }
  28322. }
  28323. }
  28324. // Updating faces & normal
  28325. var normals = [];
  28326. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  28327. for (index = 0; index < totalIndices; index += 3) {
  28328. indices[index] = index;
  28329. indices[index + 1] = index + 1;
  28330. indices[index + 2] = index + 2;
  28331. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  28332. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  28333. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  28334. var p1p2 = p1.subtract(p2);
  28335. var p3p2 = p3.subtract(p2);
  28336. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  28337. // Store same normals for every vertex
  28338. for (var localIndex = 0; localIndex < 3; localIndex++) {
  28339. normals.push(normal.x);
  28340. normals.push(normal.y);
  28341. normals.push(normal.z);
  28342. }
  28343. }
  28344. this.setIndices(indices);
  28345. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  28346. // Updating vertex buffers
  28347. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  28348. kind = kinds[kindIndex];
  28349. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  28350. }
  28351. // Updating submeshes
  28352. this.releaseSubMeshes();
  28353. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  28354. var previousOne = previousSubmeshes[submeshIndex];
  28355. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  28356. }
  28357. this.synchronizeInstances();
  28358. return this;
  28359. };
  28360. /**
  28361. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  28362. * In other words, more vertices, no more indices and a single bigger VBO.
  28363. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  28364. * Returns the Mesh.
  28365. */
  28366. Mesh.prototype.convertToUnIndexedMesh = function () {
  28367. /// <summary>Remove indices by unfolding faces into buffers</summary>
  28368. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  28369. var kinds = this.getVerticesDataKinds();
  28370. var vbs = {};
  28371. var data = {};
  28372. var newdata = {};
  28373. var kindIndex;
  28374. var kind;
  28375. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  28376. kind = kinds[kindIndex];
  28377. var vertexBuffer = this.getVertexBuffer(kind);
  28378. vbs[kind] = vertexBuffer;
  28379. data[kind] = vbs[kind].getData();
  28380. newdata[kind] = [];
  28381. }
  28382. // Save previous submeshes
  28383. var previousSubmeshes = this.subMeshes.slice(0);
  28384. var indices = this.getIndices();
  28385. var totalIndices = this.getTotalIndices();
  28386. // Generating unique vertices per face
  28387. var index;
  28388. for (index = 0; index < totalIndices; index++) {
  28389. var vertexIndex = indices[index];
  28390. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  28391. kind = kinds[kindIndex];
  28392. var stride = vbs[kind].getStrideSize();
  28393. for (var offset = 0; offset < stride; offset++) {
  28394. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  28395. }
  28396. }
  28397. }
  28398. // Updating indices
  28399. for (index = 0; index < totalIndices; index += 3) {
  28400. indices[index] = index;
  28401. indices[index + 1] = index + 1;
  28402. indices[index + 2] = index + 2;
  28403. }
  28404. this.setIndices(indices);
  28405. // Updating vertex buffers
  28406. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  28407. kind = kinds[kindIndex];
  28408. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  28409. }
  28410. // Updating submeshes
  28411. this.releaseSubMeshes();
  28412. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  28413. var previousOne = previousSubmeshes[submeshIndex];
  28414. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  28415. }
  28416. this._unIndexed = true;
  28417. this.synchronizeInstances();
  28418. return this;
  28419. };
  28420. /**
  28421. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  28422. * This method returns the Mesh.
  28423. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  28424. */
  28425. Mesh.prototype.flipFaces = function (flipNormals) {
  28426. if (flipNormals === void 0) { flipNormals = false; }
  28427. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  28428. var i;
  28429. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  28430. for (i = 0; i < vertex_data.normals.length; i++) {
  28431. vertex_data.normals[i] *= -1;
  28432. }
  28433. }
  28434. if (vertex_data.indices) {
  28435. var temp;
  28436. for (i = 0; i < vertex_data.indices.length; i += 3) {
  28437. // reassign indices
  28438. temp = vertex_data.indices[i + 1];
  28439. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  28440. vertex_data.indices[i + 2] = temp;
  28441. }
  28442. }
  28443. vertex_data.applyToMesh(this);
  28444. return this;
  28445. };
  28446. // Instances
  28447. /**
  28448. * Creates a new InstancedMesh object from the mesh model.
  28449. * An instance shares the same properties and the same material than its model.
  28450. * Only these properties of each instance can then be set individually :
  28451. * - position
  28452. * - rotation
  28453. * - rotationQuaternion
  28454. * - setPivotMatrix
  28455. * - scaling
  28456. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  28457. * Warning : this method is not supported for Line mesh and LineSystem
  28458. */
  28459. Mesh.prototype.createInstance = function (name) {
  28460. return new BABYLON.InstancedMesh(name, this);
  28461. };
  28462. /**
  28463. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  28464. * After this call, all the mesh instances have the same submeshes than the current mesh.
  28465. * This method returns the Mesh.
  28466. */
  28467. Mesh.prototype.synchronizeInstances = function () {
  28468. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  28469. var instance = this.instances[instanceIndex];
  28470. instance._syncSubMeshes();
  28471. }
  28472. return this;
  28473. };
  28474. /**
  28475. * Simplify the mesh according to the given array of settings.
  28476. * Function will return immediately and will simplify async. It returns the Mesh.
  28477. * @param settings a collection of simplification settings.
  28478. * @param parallelProcessing should all levels calculate parallel or one after the other.
  28479. * @param type the type of simplification to run.
  28480. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  28481. */
  28482. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  28483. if (parallelProcessing === void 0) { parallelProcessing = true; }
  28484. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  28485. this.getScene().simplificationQueue.addTask({
  28486. settings: settings,
  28487. parallelProcessing: parallelProcessing,
  28488. mesh: this,
  28489. simplificationType: simplificationType,
  28490. successCallback: successCallback
  28491. });
  28492. return this;
  28493. };
  28494. /**
  28495. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  28496. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  28497. * This should be used together with the simplification to avoid disappearing triangles.
  28498. * Returns the Mesh.
  28499. * @param successCallback an optional success callback to be called after the optimization finished.
  28500. */
  28501. Mesh.prototype.optimizeIndices = function (successCallback) {
  28502. var _this = this;
  28503. var indices = this.getIndices();
  28504. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28505. if (!positions || !indices) {
  28506. return this;
  28507. }
  28508. var vectorPositions = new Array();
  28509. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  28510. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  28511. }
  28512. var dupes = new Array();
  28513. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  28514. var realPos = vectorPositions.length - 1 - iteration;
  28515. var testedPosition = vectorPositions[realPos];
  28516. for (var j = 0; j < realPos; ++j) {
  28517. var againstPosition = vectorPositions[j];
  28518. if (testedPosition.equals(againstPosition)) {
  28519. dupes[realPos] = j;
  28520. break;
  28521. }
  28522. }
  28523. }, function () {
  28524. for (var i = 0; i < indices.length; ++i) {
  28525. indices[i] = dupes[indices[i]] || indices[i];
  28526. }
  28527. //indices are now reordered
  28528. var originalSubMeshes = _this.subMeshes.slice(0);
  28529. _this.setIndices(indices);
  28530. _this.subMeshes = originalSubMeshes;
  28531. if (successCallback) {
  28532. successCallback(_this);
  28533. }
  28534. });
  28535. return this;
  28536. };
  28537. Mesh.prototype.serialize = function (serializationObject) {
  28538. serializationObject.name = this.name;
  28539. serializationObject.id = this.id;
  28540. serializationObject.type = this.getClassName();
  28541. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  28542. serializationObject.tags = BABYLON.Tags.GetTags(this);
  28543. }
  28544. serializationObject.position = this.position.asArray();
  28545. if (this.rotationQuaternion) {
  28546. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  28547. }
  28548. else if (this.rotation) {
  28549. serializationObject.rotation = this.rotation.asArray();
  28550. }
  28551. serializationObject.scaling = this.scaling.asArray();
  28552. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  28553. serializationObject.isEnabled = this.isEnabled(false);
  28554. serializationObject.isVisible = this.isVisible;
  28555. serializationObject.infiniteDistance = this.infiniteDistance;
  28556. serializationObject.pickable = this.isPickable;
  28557. serializationObject.receiveShadows = this.receiveShadows;
  28558. serializationObject.billboardMode = this.billboardMode;
  28559. serializationObject.visibility = this.visibility;
  28560. serializationObject.checkCollisions = this.checkCollisions;
  28561. serializationObject.isBlocker = this.isBlocker;
  28562. // Parent
  28563. if (this.parent) {
  28564. serializationObject.parentId = this.parent.id;
  28565. }
  28566. // Geometry
  28567. serializationObject.isUnIndexed = this.isUnIndexed;
  28568. var geometry = this._geometry;
  28569. if (geometry) {
  28570. var geometryId = geometry.id;
  28571. serializationObject.geometryId = geometryId;
  28572. // SubMeshes
  28573. serializationObject.subMeshes = [];
  28574. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  28575. var subMesh = this.subMeshes[subIndex];
  28576. serializationObject.subMeshes.push({
  28577. materialIndex: subMesh.materialIndex,
  28578. verticesStart: subMesh.verticesStart,
  28579. verticesCount: subMesh.verticesCount,
  28580. indexStart: subMesh.indexStart,
  28581. indexCount: subMesh.indexCount
  28582. });
  28583. }
  28584. }
  28585. // Material
  28586. if (this.material) {
  28587. serializationObject.materialId = this.material.id;
  28588. }
  28589. else {
  28590. this.material = null;
  28591. }
  28592. // Morph targets
  28593. if (this.morphTargetManager) {
  28594. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  28595. }
  28596. // Skeleton
  28597. if (this.skeleton) {
  28598. serializationObject.skeletonId = this.skeleton.id;
  28599. }
  28600. // Physics
  28601. //TODO implement correct serialization for physics impostors.
  28602. var impostor = this.getPhysicsImpostor();
  28603. if (impostor) {
  28604. serializationObject.physicsMass = impostor.getParam("mass");
  28605. serializationObject.physicsFriction = impostor.getParam("friction");
  28606. serializationObject.physicsRestitution = impostor.getParam("mass");
  28607. serializationObject.physicsImpostor = impostor.type;
  28608. }
  28609. // Metadata
  28610. if (this.metadata) {
  28611. serializationObject.metadata = this.metadata;
  28612. }
  28613. // Instances
  28614. serializationObject.instances = [];
  28615. for (var index = 0; index < this.instances.length; index++) {
  28616. var instance = this.instances[index];
  28617. var serializationInstance = {
  28618. name: instance.name,
  28619. id: instance.id,
  28620. position: instance.position.asArray(),
  28621. scaling: instance.scaling.asArray()
  28622. };
  28623. if (instance.rotationQuaternion) {
  28624. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  28625. }
  28626. else if (instance.rotation) {
  28627. serializationInstance.rotation = instance.rotation.asArray();
  28628. }
  28629. serializationObject.instances.push(serializationInstance);
  28630. // Animations
  28631. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  28632. serializationInstance.ranges = instance.serializeAnimationRanges();
  28633. }
  28634. //
  28635. // Animations
  28636. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  28637. serializationObject.ranges = this.serializeAnimationRanges();
  28638. // Layer mask
  28639. serializationObject.layerMask = this.layerMask;
  28640. // Alpha
  28641. serializationObject.alphaIndex = this.alphaIndex;
  28642. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  28643. // Overlay
  28644. serializationObject.overlayAlpha = this.overlayAlpha;
  28645. serializationObject.overlayColor = this.overlayColor.asArray();
  28646. serializationObject.renderOverlay = this.renderOverlay;
  28647. // Fog
  28648. serializationObject.applyFog = this.applyFog;
  28649. // Action Manager
  28650. if (this.actionManager) {
  28651. serializationObject.actions = this.actionManager.serialize(this.name);
  28652. }
  28653. };
  28654. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  28655. if (!this.geometry) {
  28656. return;
  28657. }
  28658. this._markSubMeshesAsAttributesDirty();
  28659. var morphTargetManager = this._morphTargetManager;
  28660. if (morphTargetManager && morphTargetManager.vertexCount) {
  28661. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  28662. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  28663. this.morphTargetManager = null;
  28664. return;
  28665. }
  28666. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  28667. var morphTarget = morphTargetManager.getActiveTarget(index);
  28668. var positions = morphTarget.getPositions();
  28669. if (!positions) {
  28670. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  28671. return;
  28672. }
  28673. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  28674. var normals = morphTarget.getNormals();
  28675. if (normals) {
  28676. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  28677. }
  28678. var tangents = morphTarget.getTangents();
  28679. if (tangents) {
  28680. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  28681. }
  28682. }
  28683. }
  28684. else {
  28685. var index = 0;
  28686. // Positions
  28687. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  28688. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  28689. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  28690. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  28691. }
  28692. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  28693. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  28694. }
  28695. index++;
  28696. }
  28697. }
  28698. };
  28699. // Statics
  28700. /**
  28701. * Returns a new Mesh object parsed from the source provided.
  28702. * The parameter `parsedMesh` is the source.
  28703. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  28704. */
  28705. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  28706. var mesh;
  28707. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  28708. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  28709. }
  28710. else {
  28711. mesh = new Mesh(parsedMesh.name, scene);
  28712. }
  28713. mesh.id = parsedMesh.id;
  28714. if (BABYLON.Tags) {
  28715. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  28716. }
  28717. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  28718. if (parsedMesh.metadata !== undefined) {
  28719. mesh.metadata = parsedMesh.metadata;
  28720. }
  28721. if (parsedMesh.rotationQuaternion) {
  28722. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  28723. }
  28724. else if (parsedMesh.rotation) {
  28725. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  28726. }
  28727. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  28728. if (parsedMesh.localMatrix) {
  28729. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  28730. }
  28731. else if (parsedMesh.pivotMatrix) {
  28732. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  28733. }
  28734. mesh.setEnabled(parsedMesh.isEnabled);
  28735. mesh.isVisible = parsedMesh.isVisible;
  28736. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  28737. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  28738. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  28739. if (parsedMesh.applyFog !== undefined) {
  28740. mesh.applyFog = parsedMesh.applyFog;
  28741. }
  28742. if (parsedMesh.pickable !== undefined) {
  28743. mesh.isPickable = parsedMesh.pickable;
  28744. }
  28745. if (parsedMesh.alphaIndex !== undefined) {
  28746. mesh.alphaIndex = parsedMesh.alphaIndex;
  28747. }
  28748. mesh.receiveShadows = parsedMesh.receiveShadows;
  28749. mesh.billboardMode = parsedMesh.billboardMode;
  28750. if (parsedMesh.visibility !== undefined) {
  28751. mesh.visibility = parsedMesh.visibility;
  28752. }
  28753. mesh.checkCollisions = parsedMesh.checkCollisions;
  28754. if (parsedMesh.isBlocker !== undefined) {
  28755. mesh.isBlocker = parsedMesh.isBlocker;
  28756. }
  28757. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  28758. // freezeWorldMatrix
  28759. if (parsedMesh.freezeWorldMatrix) {
  28760. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  28761. }
  28762. // Parent
  28763. if (parsedMesh.parentId) {
  28764. mesh._waitingParentId = parsedMesh.parentId;
  28765. }
  28766. // Actions
  28767. if (parsedMesh.actions !== undefined) {
  28768. mesh._waitingActions = parsedMesh.actions;
  28769. }
  28770. // Overlay
  28771. if (parsedMesh.overlayAlpha !== undefined) {
  28772. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  28773. }
  28774. if (parsedMesh.overlayColor !== undefined) {
  28775. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  28776. }
  28777. if (parsedMesh.renderOverlay !== undefined) {
  28778. mesh.renderOverlay = parsedMesh.renderOverlay;
  28779. }
  28780. // Geometry
  28781. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  28782. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  28783. if (parsedMesh.delayLoadingFile) {
  28784. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  28785. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  28786. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  28787. if (parsedMesh._binaryInfo) {
  28788. mesh._binaryInfo = parsedMesh._binaryInfo;
  28789. }
  28790. mesh._delayInfo = [];
  28791. if (parsedMesh.hasUVs) {
  28792. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  28793. }
  28794. if (parsedMesh.hasUVs2) {
  28795. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  28796. }
  28797. if (parsedMesh.hasUVs3) {
  28798. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  28799. }
  28800. if (parsedMesh.hasUVs4) {
  28801. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  28802. }
  28803. if (parsedMesh.hasUVs5) {
  28804. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  28805. }
  28806. if (parsedMesh.hasUVs6) {
  28807. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  28808. }
  28809. if (parsedMesh.hasColors) {
  28810. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  28811. }
  28812. if (parsedMesh.hasMatricesIndices) {
  28813. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  28814. }
  28815. if (parsedMesh.hasMatricesWeights) {
  28816. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  28817. }
  28818. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  28819. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  28820. mesh._checkDelayState();
  28821. }
  28822. }
  28823. else {
  28824. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  28825. }
  28826. // Material
  28827. if (parsedMesh.materialId) {
  28828. mesh.setMaterialByID(parsedMesh.materialId);
  28829. }
  28830. else {
  28831. mesh.material = null;
  28832. }
  28833. // Morph targets
  28834. if (parsedMesh.morphTargetManagerId > -1) {
  28835. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  28836. }
  28837. // Skeleton
  28838. if (parsedMesh.skeletonId > -1) {
  28839. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  28840. if (parsedMesh.numBoneInfluencers) {
  28841. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  28842. }
  28843. }
  28844. // Animations
  28845. if (parsedMesh.animations) {
  28846. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  28847. var parsedAnimation = parsedMesh.animations[animationIndex];
  28848. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  28849. }
  28850. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  28851. }
  28852. if (parsedMesh.autoAnimate) {
  28853. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  28854. }
  28855. // Layer Mask
  28856. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  28857. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  28858. }
  28859. else {
  28860. mesh.layerMask = 0x0FFFFFFF;
  28861. }
  28862. // Physics
  28863. if (parsedMesh.physicsImpostor) {
  28864. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  28865. mass: parsedMesh.physicsMass,
  28866. friction: parsedMesh.physicsFriction,
  28867. restitution: parsedMesh.physicsRestitution
  28868. }, scene);
  28869. }
  28870. // Instances
  28871. if (parsedMesh.instances) {
  28872. for (var index = 0; index < parsedMesh.instances.length; index++) {
  28873. var parsedInstance = parsedMesh.instances[index];
  28874. var instance = mesh.createInstance(parsedInstance.name);
  28875. if (parsedInstance.id) {
  28876. instance.id = parsedInstance.id;
  28877. }
  28878. if (BABYLON.Tags) {
  28879. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  28880. }
  28881. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  28882. if (parsedInstance.parentId) {
  28883. instance._waitingParentId = parsedInstance.parentId;
  28884. }
  28885. if (parsedInstance.rotationQuaternion) {
  28886. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  28887. }
  28888. else if (parsedInstance.rotation) {
  28889. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  28890. }
  28891. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  28892. instance.checkCollisions = mesh.checkCollisions;
  28893. if (parsedMesh.animations) {
  28894. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  28895. parsedAnimation = parsedMesh.animations[animationIndex];
  28896. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  28897. }
  28898. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  28899. }
  28900. }
  28901. }
  28902. return mesh;
  28903. };
  28904. /**
  28905. * Creates a ribbon mesh.
  28906. * Please consider using the same method from the MeshBuilder class instead.
  28907. * 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.
  28908. *
  28909. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  28910. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  28911. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  28912. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  28913. * 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.
  28914. * 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.
  28915. * 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
  28916. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28917. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28918. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28919. */
  28920. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  28921. if (closeArray === void 0) { closeArray = false; }
  28922. if (updatable === void 0) { updatable = false; }
  28923. return BABYLON.MeshBuilder.CreateRibbon(name, {
  28924. pathArray: pathArray,
  28925. closeArray: closeArray,
  28926. closePath: closePath,
  28927. offset: offset,
  28928. updatable: updatable,
  28929. sideOrientation: sideOrientation,
  28930. instance: instance
  28931. }, scene);
  28932. };
  28933. /**
  28934. * Creates a plane polygonal mesh. By default, this is a disc.
  28935. * Please consider using the same method from the MeshBuilder class instead.
  28936. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  28937. * 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.
  28938. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28939. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28940. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28941. */
  28942. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  28943. if (scene === void 0) { scene = null; }
  28944. var options = {
  28945. radius: radius,
  28946. tessellation: tessellation,
  28947. sideOrientation: sideOrientation,
  28948. updatable: updatable
  28949. };
  28950. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  28951. };
  28952. /**
  28953. * Creates a box mesh.
  28954. * Please consider using the same method from the MeshBuilder class instead.
  28955. * The parameter `size` sets the size (float) of each box side (default 1).
  28956. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28957. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28958. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28959. */
  28960. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  28961. if (scene === void 0) { scene = null; }
  28962. var options = {
  28963. size: size,
  28964. sideOrientation: sideOrientation,
  28965. updatable: updatable
  28966. };
  28967. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  28968. };
  28969. /**
  28970. * Creates a sphere mesh.
  28971. * Please consider using the same method from the MeshBuilder class instead.
  28972. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  28973. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  28974. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28975. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28976. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28977. */
  28978. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  28979. var options = {
  28980. segments: segments,
  28981. diameterX: diameter,
  28982. diameterY: diameter,
  28983. diameterZ: diameter,
  28984. sideOrientation: sideOrientation,
  28985. updatable: updatable
  28986. };
  28987. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  28988. };
  28989. /**
  28990. * Creates a cylinder or a cone mesh.
  28991. * Please consider using the same method from the MeshBuilder class instead.
  28992. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  28993. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  28994. * 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.
  28995. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  28996. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  28997. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28998. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28999. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29000. */
  29001. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  29002. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  29003. if (scene !== undefined) {
  29004. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  29005. updatable = scene;
  29006. }
  29007. scene = subdivisions;
  29008. subdivisions = 1;
  29009. }
  29010. var options = {
  29011. height: height,
  29012. diameterTop: diameterTop,
  29013. diameterBottom: diameterBottom,
  29014. tessellation: tessellation,
  29015. subdivisions: subdivisions,
  29016. sideOrientation: sideOrientation,
  29017. updatable: updatable
  29018. };
  29019. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  29020. };
  29021. // Torus (Code from SharpDX.org)
  29022. /**
  29023. * Creates a torus mesh.
  29024. * Please consider using the same method from the MeshBuilder class instead.
  29025. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  29026. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  29027. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  29028. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29029. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29030. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29031. */
  29032. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  29033. var options = {
  29034. diameter: diameter,
  29035. thickness: thickness,
  29036. tessellation: tessellation,
  29037. sideOrientation: sideOrientation,
  29038. updatable: updatable
  29039. };
  29040. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  29041. };
  29042. /**
  29043. * Creates a torus knot mesh.
  29044. * Please consider using the same method from the MeshBuilder class instead.
  29045. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  29046. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  29047. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  29048. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  29049. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29050. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29051. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29052. */
  29053. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  29054. var options = {
  29055. radius: radius,
  29056. tube: tube,
  29057. radialSegments: radialSegments,
  29058. tubularSegments: tubularSegments,
  29059. p: p,
  29060. q: q,
  29061. sideOrientation: sideOrientation,
  29062. updatable: updatable
  29063. };
  29064. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  29065. };
  29066. /**
  29067. * Creates a line mesh.
  29068. * Please consider using the same method from the MeshBuilder class instead.
  29069. * 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.
  29070. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  29071. * The parameter `points` is an array successive Vector3.
  29072. * 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
  29073. * When updating an instance, remember that only point positions can change, not the number of points.
  29074. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29075. */
  29076. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  29077. if (scene === void 0) { scene = null; }
  29078. if (updatable === void 0) { updatable = false; }
  29079. if (instance === void 0) { instance = null; }
  29080. var options = {
  29081. points: points,
  29082. updatable: updatable,
  29083. instance: instance
  29084. };
  29085. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  29086. };
  29087. /**
  29088. * Creates a dashed line mesh.
  29089. * Please consider using the same method from the MeshBuilder class instead.
  29090. * 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.
  29091. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  29092. * The parameter `points` is an array successive Vector3.
  29093. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  29094. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  29095. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  29096. * 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
  29097. * When updating an instance, remember that only point positions can change, not the number of points.
  29098. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29099. */
  29100. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  29101. if (scene === void 0) { scene = null; }
  29102. var options = {
  29103. points: points,
  29104. dashSize: dashSize,
  29105. gapSize: gapSize,
  29106. dashNb: dashNb,
  29107. updatable: updatable,
  29108. instance: instance
  29109. };
  29110. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  29111. };
  29112. /**
  29113. * Creates a polygon mesh.
  29114. * Please consider using the same method from the MeshBuilder class instead.
  29115. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  29116. * 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.
  29117. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29118. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29119. * Remember you can only change the shape positions, not their number when updating a polygon.
  29120. */
  29121. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  29122. var options = {
  29123. shape: shape,
  29124. holes: holes,
  29125. updatable: updatable,
  29126. sideOrientation: sideOrientation
  29127. };
  29128. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  29129. };
  29130. /**
  29131. * Creates an extruded polygon mesh, with depth in the Y direction.
  29132. * Please consider using the same method from the MeshBuilder class instead.
  29133. */
  29134. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  29135. var options = {
  29136. shape: shape,
  29137. holes: holes,
  29138. depth: depth,
  29139. updatable: updatable,
  29140. sideOrientation: sideOrientation
  29141. };
  29142. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  29143. };
  29144. /**
  29145. * Creates an extruded shape mesh.
  29146. * 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.
  29147. * Please consider using the same method from the MeshBuilder class instead.
  29148. *
  29149. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  29150. * 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
  29151. * extruded along the Z axis.
  29152. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  29153. * 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.
  29154. * The parameter `scale` (float, default 1) is the value to scale the shape.
  29155. * 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
  29156. * 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
  29157. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  29158. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29159. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29160. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29161. */
  29162. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  29163. if (scene === void 0) { scene = null; }
  29164. var options = {
  29165. shape: shape,
  29166. path: path,
  29167. scale: scale,
  29168. rotation: rotation,
  29169. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  29170. sideOrientation: sideOrientation,
  29171. instance: instance,
  29172. updatable: updatable
  29173. };
  29174. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  29175. };
  29176. /**
  29177. * Creates an custom extruded shape mesh.
  29178. * 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.
  29179. * Please consider using the same method from the MeshBuilder class instead.
  29180. *
  29181. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  29182. * 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
  29183. * extruded along the Z axis.
  29184. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  29185. * 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
  29186. * and the distance of this point from the begining of the path :
  29187. * ```javascript
  29188. * var rotationFunction = function(i, distance) {
  29189. * // do things
  29190. * return rotationValue; }
  29191. * ```
  29192. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  29193. * 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
  29194. * and the distance of this point from the begining of the path :
  29195. * ```javascript
  29196. * var scaleFunction = function(i, distance) {
  29197. * // do things
  29198. * return scaleValue;}
  29199. * ```
  29200. * It must returns a float value that will be the scale value applied to the shape on each path point.
  29201. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  29202. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  29203. * 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
  29204. * 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
  29205. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  29206. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29207. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29208. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29209. */
  29210. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  29211. var options = {
  29212. shape: shape,
  29213. path: path,
  29214. scaleFunction: scaleFunction,
  29215. rotationFunction: rotationFunction,
  29216. ribbonCloseArray: ribbonCloseArray,
  29217. ribbonClosePath: ribbonClosePath,
  29218. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  29219. sideOrientation: sideOrientation,
  29220. instance: instance,
  29221. updatable: updatable
  29222. };
  29223. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  29224. };
  29225. /**
  29226. * Creates lathe mesh.
  29227. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  29228. * Please consider using the same method from the MeshBuilder class instead.
  29229. * 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
  29230. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  29231. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  29232. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  29233. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29234. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29235. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29236. */
  29237. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  29238. var options = {
  29239. shape: shape,
  29240. radius: radius,
  29241. tessellation: tessellation,
  29242. sideOrientation: sideOrientation,
  29243. updatable: updatable
  29244. };
  29245. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  29246. };
  29247. /**
  29248. * Creates a plane mesh.
  29249. * Please consider using the same method from the MeshBuilder class instead.
  29250. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  29251. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29252. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29253. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29254. */
  29255. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  29256. var options = {
  29257. size: size,
  29258. width: size,
  29259. height: size,
  29260. sideOrientation: sideOrientation,
  29261. updatable: updatable
  29262. };
  29263. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  29264. };
  29265. /**
  29266. * Creates a ground mesh.
  29267. * Please consider using the same method from the MeshBuilder class instead.
  29268. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  29269. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  29270. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29271. */
  29272. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  29273. var options = {
  29274. width: width,
  29275. height: height,
  29276. subdivisions: subdivisions,
  29277. updatable: updatable
  29278. };
  29279. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  29280. };
  29281. /**
  29282. * Creates a tiled ground mesh.
  29283. * Please consider using the same method from the MeshBuilder class instead.
  29284. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  29285. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  29286. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  29287. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  29288. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  29289. * numbers of subdivisions on the ground width and height of each tile.
  29290. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29291. */
  29292. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  29293. var options = {
  29294. xmin: xmin,
  29295. zmin: zmin,
  29296. xmax: xmax,
  29297. zmax: zmax,
  29298. subdivisions: subdivisions,
  29299. precision: precision,
  29300. updatable: updatable
  29301. };
  29302. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  29303. };
  29304. /**
  29305. * Creates a ground mesh from a height map.
  29306. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  29307. * Please consider using the same method from the MeshBuilder class instead.
  29308. * The parameter `url` sets the URL of the height map image resource.
  29309. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  29310. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  29311. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  29312. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  29313. * 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).
  29314. * This function is passed the newly built mesh :
  29315. * ```javascript
  29316. * function(mesh) { // do things
  29317. * return; }
  29318. * ```
  29319. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29320. */
  29321. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  29322. var options = {
  29323. width: width,
  29324. height: height,
  29325. subdivisions: subdivisions,
  29326. minHeight: minHeight,
  29327. maxHeight: maxHeight,
  29328. updatable: updatable,
  29329. onReady: onReady
  29330. };
  29331. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  29332. };
  29333. /**
  29334. * Creates a tube mesh.
  29335. * 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.
  29336. * Please consider using the same method from the MeshBuilder class instead.
  29337. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  29338. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  29339. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  29340. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  29341. * 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.
  29342. * It must return a radius value (positive float) :
  29343. * ```javascript
  29344. * var radiusFunction = function(i, distance) {
  29345. * // do things
  29346. * return radius; }
  29347. * ```
  29348. * 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
  29349. * 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
  29350. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29351. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29352. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29353. */
  29354. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  29355. var options = {
  29356. path: path,
  29357. radius: radius,
  29358. tessellation: tessellation,
  29359. radiusFunction: radiusFunction,
  29360. arc: 1,
  29361. cap: cap,
  29362. updatable: updatable,
  29363. sideOrientation: sideOrientation,
  29364. instance: instance
  29365. };
  29366. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  29367. };
  29368. /**
  29369. * Creates a polyhedron mesh.
  29370. * Please consider using the same method from the MeshBuilder class instead.
  29371. * 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
  29372. * to choose the wanted type.
  29373. * The parameter `size` (positive float, default 1) sets the polygon size.
  29374. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  29375. * 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`.
  29376. * 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
  29377. * 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)`).
  29378. * 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
  29379. * 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.
  29380. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29381. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29382. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29383. */
  29384. Mesh.CreatePolyhedron = function (name, options, scene) {
  29385. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  29386. };
  29387. /**
  29388. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  29389. * Please consider using the same method from the MeshBuilder class instead.
  29390. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  29391. * 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`).
  29392. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  29393. * 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.
  29394. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29395. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29396. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29397. */
  29398. Mesh.CreateIcoSphere = function (name, options, scene) {
  29399. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  29400. };
  29401. /**
  29402. * Creates a decal mesh.
  29403. * Please consider using the same method from the MeshBuilder class instead.
  29404. * 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.
  29405. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  29406. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  29407. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  29408. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  29409. */
  29410. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  29411. var options = {
  29412. position: position,
  29413. normal: normal,
  29414. size: size,
  29415. angle: angle
  29416. };
  29417. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  29418. };
  29419. // Skeletons
  29420. /**
  29421. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  29422. */
  29423. Mesh.prototype.setPositionsForCPUSkinning = function () {
  29424. if (!this._sourcePositions) {
  29425. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29426. if (!source) {
  29427. return this._sourcePositions;
  29428. }
  29429. this._sourcePositions = new Float32Array(source);
  29430. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  29431. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  29432. }
  29433. }
  29434. return this._sourcePositions;
  29435. };
  29436. /**
  29437. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  29438. */
  29439. Mesh.prototype.setNormalsForCPUSkinning = function () {
  29440. if (!this._sourceNormals) {
  29441. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  29442. if (!source) {
  29443. return this._sourceNormals;
  29444. }
  29445. this._sourceNormals = new Float32Array(source);
  29446. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  29447. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  29448. }
  29449. }
  29450. return this._sourceNormals;
  29451. };
  29452. /**
  29453. * Updates the vertex buffer by applying transformation from the bones.
  29454. * Returns the Mesh.
  29455. *
  29456. * @param {skeleton} skeleton to apply
  29457. */
  29458. Mesh.prototype.applySkeleton = function (skeleton) {
  29459. if (!this.geometry) {
  29460. return this;
  29461. }
  29462. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  29463. return this;
  29464. }
  29465. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  29466. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  29467. return this;
  29468. }
  29469. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  29470. return this;
  29471. }
  29472. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  29473. return this;
  29474. }
  29475. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  29476. return this;
  29477. }
  29478. if (!this._sourcePositions) {
  29479. var submeshes = this.subMeshes.slice();
  29480. this.setPositionsForCPUSkinning();
  29481. this.subMeshes = submeshes;
  29482. }
  29483. if (!this._sourceNormals) {
  29484. this.setNormalsForCPUSkinning();
  29485. }
  29486. // positionsData checks for not being Float32Array will only pass at most once
  29487. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29488. if (!positionsData) {
  29489. return this;
  29490. }
  29491. if (!(positionsData instanceof Float32Array)) {
  29492. positionsData = new Float32Array(positionsData);
  29493. }
  29494. // normalsData checks for not being Float32Array will only pass at most once
  29495. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  29496. if (!normalsData) {
  29497. return this;
  29498. }
  29499. if (!(normalsData instanceof Float32Array)) {
  29500. normalsData = new Float32Array(normalsData);
  29501. }
  29502. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  29503. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  29504. if (!matricesWeightsData || !matricesIndicesData) {
  29505. return this;
  29506. }
  29507. var needExtras = this.numBoneInfluencers > 4;
  29508. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  29509. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  29510. var skeletonMatrices = skeleton.getTransformMatrices(this);
  29511. var tempVector3 = BABYLON.Vector3.Zero();
  29512. var finalMatrix = new BABYLON.Matrix();
  29513. var tempMatrix = new BABYLON.Matrix();
  29514. var matWeightIdx = 0;
  29515. var inf;
  29516. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  29517. var weight;
  29518. for (inf = 0; inf < 4; inf++) {
  29519. weight = matricesWeightsData[matWeightIdx + inf];
  29520. if (weight > 0) {
  29521. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  29522. finalMatrix.addToSelf(tempMatrix);
  29523. }
  29524. else
  29525. break;
  29526. }
  29527. if (needExtras) {
  29528. for (inf = 0; inf < 4; inf++) {
  29529. weight = matricesWeightsExtraData[matWeightIdx + inf];
  29530. if (weight > 0) {
  29531. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  29532. finalMatrix.addToSelf(tempMatrix);
  29533. }
  29534. else
  29535. break;
  29536. }
  29537. }
  29538. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  29539. tempVector3.toArray(positionsData, index);
  29540. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  29541. tempVector3.toArray(normalsData, index);
  29542. finalMatrix.reset();
  29543. }
  29544. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  29545. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  29546. return this;
  29547. };
  29548. // Tools
  29549. /**
  29550. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  29551. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  29552. */
  29553. Mesh.MinMax = function (meshes) {
  29554. var minVector = null;
  29555. var maxVector = null;
  29556. meshes.forEach(function (mesh, index, array) {
  29557. var boundingInfo = mesh.getBoundingInfo();
  29558. var boundingBox = boundingInfo.boundingBox;
  29559. if (!minVector || !maxVector) {
  29560. minVector = boundingBox.minimumWorld;
  29561. maxVector = boundingBox.maximumWorld;
  29562. }
  29563. else {
  29564. minVector.minimizeInPlace(boundingBox.minimumWorld);
  29565. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  29566. }
  29567. });
  29568. if (!minVector || !maxVector) {
  29569. return {
  29570. min: BABYLON.Vector3.Zero(),
  29571. max: BABYLON.Vector3.Zero()
  29572. };
  29573. }
  29574. return {
  29575. min: minVector,
  29576. max: maxVector
  29577. };
  29578. };
  29579. /**
  29580. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  29581. */
  29582. Mesh.Center = function (meshesOrMinMaxVector) {
  29583. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  29584. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  29585. };
  29586. /**
  29587. * Merge the array of meshes into a single mesh for performance reasons.
  29588. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  29589. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  29590. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  29591. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  29592. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  29593. */
  29594. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  29595. if (disposeSource === void 0) { disposeSource = true; }
  29596. var index;
  29597. if (!allow32BitsIndices) {
  29598. var totalVertices = 0;
  29599. // Counting vertices
  29600. for (index = 0; index < meshes.length; index++) {
  29601. if (meshes[index]) {
  29602. totalVertices += meshes[index].getTotalVertices();
  29603. if (totalVertices > 65536) {
  29604. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  29605. return null;
  29606. }
  29607. }
  29608. }
  29609. }
  29610. // Merge
  29611. var vertexData = null;
  29612. var otherVertexData;
  29613. var indiceArray = new Array();
  29614. var source = null;
  29615. for (index = 0; index < meshes.length; index++) {
  29616. if (meshes[index]) {
  29617. meshes[index].computeWorldMatrix(true);
  29618. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  29619. otherVertexData.transform(meshes[index].getWorldMatrix());
  29620. if (vertexData) {
  29621. vertexData.merge(otherVertexData);
  29622. }
  29623. else {
  29624. vertexData = otherVertexData;
  29625. source = meshes[index];
  29626. }
  29627. if (subdivideWithSubMeshes) {
  29628. indiceArray.push(meshes[index].getTotalIndices());
  29629. }
  29630. }
  29631. }
  29632. source = source;
  29633. if (!meshSubclass) {
  29634. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  29635. }
  29636. vertexData.applyToMesh(meshSubclass);
  29637. // Setting properties
  29638. meshSubclass.material = source.material;
  29639. meshSubclass.checkCollisions = source.checkCollisions;
  29640. // Cleaning
  29641. if (disposeSource) {
  29642. for (index = 0; index < meshes.length; index++) {
  29643. if (meshes[index]) {
  29644. meshes[index].dispose();
  29645. }
  29646. }
  29647. }
  29648. // Subdivide
  29649. if (subdivideWithSubMeshes) {
  29650. //-- Suppresions du submesh global
  29651. meshSubclass.releaseSubMeshes();
  29652. index = 0;
  29653. var offset = 0;
  29654. //-- aplique la subdivision en fonction du tableau d'indices
  29655. while (index < indiceArray.length) {
  29656. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  29657. offset += indiceArray[index];
  29658. index++;
  29659. }
  29660. }
  29661. return meshSubclass;
  29662. };
  29663. // Consts
  29664. Mesh._FRONTSIDE = 0;
  29665. Mesh._BACKSIDE = 1;
  29666. Mesh._DOUBLESIDE = 2;
  29667. Mesh._DEFAULTSIDE = 0;
  29668. Mesh._NO_CAP = 0;
  29669. Mesh._CAP_START = 1;
  29670. Mesh._CAP_END = 2;
  29671. Mesh._CAP_ALL = 3;
  29672. return Mesh;
  29673. }(BABYLON.AbstractMesh));
  29674. BABYLON.Mesh = Mesh;
  29675. })(BABYLON || (BABYLON = {}));
  29676. //# sourceMappingURL=babylon.mesh.js.map
  29677. var BABYLON;
  29678. (function (BABYLON) {
  29679. var BaseSubMesh = /** @class */ (function () {
  29680. function BaseSubMesh() {
  29681. }
  29682. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  29683. get: function () {
  29684. return this._materialEffect;
  29685. },
  29686. enumerable: true,
  29687. configurable: true
  29688. });
  29689. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  29690. if (defines === void 0) { defines = null; }
  29691. if (this._materialEffect === effect) {
  29692. if (!effect) {
  29693. this._materialDefines = null;
  29694. }
  29695. return;
  29696. }
  29697. this._materialDefines = defines;
  29698. this._materialEffect = effect;
  29699. };
  29700. return BaseSubMesh;
  29701. }());
  29702. BABYLON.BaseSubMesh = BaseSubMesh;
  29703. var SubMesh = /** @class */ (function (_super) {
  29704. __extends(SubMesh, _super);
  29705. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  29706. if (createBoundingBox === void 0) { createBoundingBox = true; }
  29707. var _this = _super.call(this) || this;
  29708. _this.materialIndex = materialIndex;
  29709. _this.verticesStart = verticesStart;
  29710. _this.verticesCount = verticesCount;
  29711. _this.indexStart = indexStart;
  29712. _this.indexCount = indexCount;
  29713. _this._renderId = 0;
  29714. _this._mesh = mesh;
  29715. _this._renderingMesh = renderingMesh || mesh;
  29716. mesh.subMeshes.push(_this);
  29717. _this._trianglePlanes = [];
  29718. _this._id = mesh.subMeshes.length - 1;
  29719. if (createBoundingBox) {
  29720. _this.refreshBoundingInfo();
  29721. mesh.computeWorldMatrix(true);
  29722. }
  29723. return _this;
  29724. }
  29725. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  29726. if (createBoundingBox === void 0) { createBoundingBox = true; }
  29727. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  29728. };
  29729. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  29730. get: function () {
  29731. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  29732. },
  29733. enumerable: true,
  29734. configurable: true
  29735. });
  29736. /**
  29737. * Returns the submesh BoudingInfo object.
  29738. */
  29739. SubMesh.prototype.getBoundingInfo = function () {
  29740. if (this.IsGlobal) {
  29741. return this._mesh.getBoundingInfo();
  29742. }
  29743. return this._boundingInfo;
  29744. };
  29745. /**
  29746. * Sets the submesh BoundingInfo.
  29747. * Return the SubMesh.
  29748. */
  29749. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  29750. this._boundingInfo = boundingInfo;
  29751. return this;
  29752. };
  29753. /**
  29754. * Returns the mesh of the current submesh.
  29755. */
  29756. SubMesh.prototype.getMesh = function () {
  29757. return this._mesh;
  29758. };
  29759. /**
  29760. * Returns the rendering mesh of the submesh.
  29761. */
  29762. SubMesh.prototype.getRenderingMesh = function () {
  29763. return this._renderingMesh;
  29764. };
  29765. /**
  29766. * Returns the submesh material.
  29767. */
  29768. SubMesh.prototype.getMaterial = function () {
  29769. var rootMaterial = this._renderingMesh.material;
  29770. if (rootMaterial === null || rootMaterial === undefined) {
  29771. return this._mesh.getScene().defaultMaterial;
  29772. }
  29773. else if (rootMaterial.getSubMaterial) {
  29774. var multiMaterial = rootMaterial;
  29775. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  29776. if (this._currentMaterial !== effectiveMaterial) {
  29777. this._currentMaterial = effectiveMaterial;
  29778. this._materialDefines = null;
  29779. }
  29780. return effectiveMaterial;
  29781. }
  29782. return rootMaterial;
  29783. };
  29784. // Methods
  29785. /**
  29786. * Sets a new updated BoundingInfo object to the submesh.
  29787. * Returns the SubMesh.
  29788. */
  29789. SubMesh.prototype.refreshBoundingInfo = function () {
  29790. this._lastColliderWorldVertices = null;
  29791. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  29792. return this;
  29793. }
  29794. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29795. if (!data) {
  29796. this._boundingInfo = this._mesh.getBoundingInfo();
  29797. return this;
  29798. }
  29799. var indices = this._renderingMesh.getIndices();
  29800. var extend;
  29801. //is this the only submesh?
  29802. if (this.indexStart === 0 && this.indexCount === indices.length) {
  29803. var boundingInfo = this._renderingMesh.getBoundingInfo();
  29804. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  29805. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  29806. }
  29807. else {
  29808. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  29809. }
  29810. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  29811. return this;
  29812. };
  29813. SubMesh.prototype._checkCollision = function (collider) {
  29814. var boundingInfo = this._renderingMesh.getBoundingInfo();
  29815. return boundingInfo._checkCollision(collider);
  29816. };
  29817. /**
  29818. * Updates the submesh BoundingInfo.
  29819. * Returns the Submesh.
  29820. */
  29821. SubMesh.prototype.updateBoundingInfo = function (world) {
  29822. var boundingInfo = this.getBoundingInfo();
  29823. if (!boundingInfo) {
  29824. this.refreshBoundingInfo();
  29825. boundingInfo = this.getBoundingInfo();
  29826. }
  29827. boundingInfo.update(world);
  29828. return this;
  29829. };
  29830. /**
  29831. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  29832. * Boolean returned.
  29833. */
  29834. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  29835. var boundingInfo = this.getBoundingInfo();
  29836. if (!boundingInfo) {
  29837. return false;
  29838. }
  29839. return boundingInfo.isInFrustum(frustumPlanes);
  29840. };
  29841. /**
  29842. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  29843. * Boolean returned.
  29844. */
  29845. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  29846. var boundingInfo = this.getBoundingInfo();
  29847. if (!boundingInfo) {
  29848. return false;
  29849. }
  29850. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  29851. };
  29852. /**
  29853. * Renders the submesh.
  29854. * Returns it.
  29855. */
  29856. SubMesh.prototype.render = function (enableAlphaMode) {
  29857. this._renderingMesh.render(this, enableAlphaMode);
  29858. return this;
  29859. };
  29860. /**
  29861. * Returns a new Index Buffer.
  29862. * Type returned : WebGLBuffer.
  29863. */
  29864. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  29865. if (!this._linesIndexBuffer) {
  29866. var linesIndices = [];
  29867. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  29868. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  29869. }
  29870. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  29871. this.linesIndexCount = linesIndices.length;
  29872. }
  29873. return this._linesIndexBuffer;
  29874. };
  29875. /**
  29876. * True is the passed Ray intersects the submesh bounding box.
  29877. * Boolean returned.
  29878. */
  29879. SubMesh.prototype.canIntersects = function (ray) {
  29880. var boundingInfo = this.getBoundingInfo();
  29881. if (!boundingInfo) {
  29882. return false;
  29883. }
  29884. return ray.intersectsBox(boundingInfo.boundingBox);
  29885. };
  29886. /**
  29887. * Returns an object IntersectionInfo.
  29888. */
  29889. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  29890. var intersectInfo = null;
  29891. // LineMesh first as it's also a Mesh...
  29892. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  29893. var lineMesh = this._mesh;
  29894. // Line test
  29895. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  29896. var p0 = positions[indices[index]];
  29897. var p1 = positions[indices[index + 1]];
  29898. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  29899. if (length < 0) {
  29900. continue;
  29901. }
  29902. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  29903. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  29904. if (fastCheck) {
  29905. break;
  29906. }
  29907. }
  29908. }
  29909. }
  29910. else {
  29911. // Triangles test
  29912. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  29913. var p0 = positions[indices[index]];
  29914. var p1 = positions[indices[index + 1]];
  29915. var p2 = positions[indices[index + 2]];
  29916. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  29917. if (currentIntersectInfo) {
  29918. if (currentIntersectInfo.distance < 0) {
  29919. continue;
  29920. }
  29921. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  29922. intersectInfo = currentIntersectInfo;
  29923. intersectInfo.faceId = index / 3;
  29924. if (fastCheck) {
  29925. break;
  29926. }
  29927. }
  29928. }
  29929. }
  29930. }
  29931. return intersectInfo;
  29932. };
  29933. SubMesh.prototype._rebuild = function () {
  29934. if (this._linesIndexBuffer) {
  29935. this._linesIndexBuffer = null;
  29936. }
  29937. };
  29938. // Clone
  29939. /**
  29940. * Creates a new Submesh from the passed Mesh.
  29941. */
  29942. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  29943. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  29944. if (!this.IsGlobal) {
  29945. var boundingInfo = this.getBoundingInfo();
  29946. if (!boundingInfo) {
  29947. return result;
  29948. }
  29949. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  29950. }
  29951. return result;
  29952. };
  29953. // Dispose
  29954. /**
  29955. * Disposes the Submesh.
  29956. * Returns nothing.
  29957. */
  29958. SubMesh.prototype.dispose = function () {
  29959. if (this._linesIndexBuffer) {
  29960. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  29961. this._linesIndexBuffer = null;
  29962. }
  29963. // Remove from mesh
  29964. var index = this._mesh.subMeshes.indexOf(this);
  29965. this._mesh.subMeshes.splice(index, 1);
  29966. };
  29967. // Statics
  29968. /**
  29969. * Creates a new Submesh from the passed parameters :
  29970. * - materialIndex (integer) : the index of the main mesh material.
  29971. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  29972. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  29973. * - mesh (Mesh) : the main mesh to create the submesh from.
  29974. * - renderingMesh (optional Mesh) : rendering mesh.
  29975. */
  29976. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  29977. var minVertexIndex = Number.MAX_VALUE;
  29978. var maxVertexIndex = -Number.MAX_VALUE;
  29979. renderingMesh = (renderingMesh || mesh);
  29980. var indices = renderingMesh.getIndices();
  29981. for (var index = startIndex; index < startIndex + indexCount; index++) {
  29982. var vertexIndex = indices[index];
  29983. if (vertexIndex < minVertexIndex)
  29984. minVertexIndex = vertexIndex;
  29985. if (vertexIndex > maxVertexIndex)
  29986. maxVertexIndex = vertexIndex;
  29987. }
  29988. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  29989. };
  29990. return SubMesh;
  29991. }(BaseSubMesh));
  29992. BABYLON.SubMesh = SubMesh;
  29993. })(BABYLON || (BABYLON = {}));
  29994. //# sourceMappingURL=babylon.subMesh.js.map
  29995. var __assign = (this && this.__assign) || Object.assign || function(t) {
  29996. for (var s, i = 1, n = arguments.length; i < n; i++) {
  29997. s = arguments[i];
  29998. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  29999. t[p] = s[p];
  30000. }
  30001. return t;
  30002. };
  30003. var BABYLON;
  30004. (function (BABYLON) {
  30005. /**
  30006. * Manages the defines for the Material.
  30007. */
  30008. var MaterialDefines = /** @class */ (function () {
  30009. function MaterialDefines() {
  30010. this._isDirty = true;
  30011. this._areLightsDirty = true;
  30012. this._areAttributesDirty = true;
  30013. this._areTexturesDirty = true;
  30014. this._areFresnelDirty = true;
  30015. this._areMiscDirty = true;
  30016. this._areImageProcessingDirty = true;
  30017. this._normals = false;
  30018. this._uvs = false;
  30019. this._needNormals = false;
  30020. this._needUVs = false;
  30021. }
  30022. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  30023. /**
  30024. * Specifies if the material needs to be re-calculated.
  30025. */
  30026. get: function () {
  30027. return this._isDirty;
  30028. },
  30029. enumerable: true,
  30030. configurable: true
  30031. });
  30032. /**
  30033. * Marks the material to indicate that it has been re-calculated.
  30034. */
  30035. MaterialDefines.prototype.markAsProcessed = function () {
  30036. this._isDirty = false;
  30037. this._areAttributesDirty = false;
  30038. this._areTexturesDirty = false;
  30039. this._areFresnelDirty = false;
  30040. this._areLightsDirty = false;
  30041. this._areMiscDirty = false;
  30042. this._areImageProcessingDirty = false;
  30043. };
  30044. /**
  30045. * Marks the material to indicate that it needs to be re-calculated.
  30046. */
  30047. MaterialDefines.prototype.markAsUnprocessed = function () {
  30048. this._isDirty = true;
  30049. };
  30050. /**
  30051. * Marks the material to indicate all of its defines need to be re-calculated.
  30052. */
  30053. MaterialDefines.prototype.markAllAsDirty = function () {
  30054. this._areTexturesDirty = true;
  30055. this._areAttributesDirty = true;
  30056. this._areLightsDirty = true;
  30057. this._areFresnelDirty = true;
  30058. this._areMiscDirty = true;
  30059. this._areImageProcessingDirty = true;
  30060. this._isDirty = true;
  30061. };
  30062. /**
  30063. * Marks the material to indicate that image processing needs to be re-calculated.
  30064. */
  30065. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  30066. this._areImageProcessingDirty = true;
  30067. this._isDirty = true;
  30068. };
  30069. /**
  30070. * Marks the material to indicate the lights need to be re-calculated.
  30071. */
  30072. MaterialDefines.prototype.markAsLightDirty = function () {
  30073. this._areLightsDirty = true;
  30074. this._isDirty = true;
  30075. };
  30076. /**
  30077. * Marks the attribute state as changed.
  30078. */
  30079. MaterialDefines.prototype.markAsAttributesDirty = function () {
  30080. this._areAttributesDirty = true;
  30081. this._isDirty = true;
  30082. };
  30083. /**
  30084. * Marks the texture state as changed.
  30085. */
  30086. MaterialDefines.prototype.markAsTexturesDirty = function () {
  30087. this._areTexturesDirty = true;
  30088. this._isDirty = true;
  30089. };
  30090. /**
  30091. * Marks the fresnel state as changed.
  30092. */
  30093. MaterialDefines.prototype.markAsFresnelDirty = function () {
  30094. this._areFresnelDirty = true;
  30095. this._isDirty = true;
  30096. };
  30097. /**
  30098. * Marks the misc state as changed.
  30099. */
  30100. MaterialDefines.prototype.markAsMiscDirty = function () {
  30101. this._areMiscDirty = true;
  30102. this._isDirty = true;
  30103. };
  30104. /**
  30105. * Rebuilds the material defines.
  30106. */
  30107. MaterialDefines.prototype.rebuild = function () {
  30108. if (this._keys) {
  30109. delete this._keys;
  30110. }
  30111. this._keys = [];
  30112. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  30113. var key = _a[_i];
  30114. if (key[0] === "_") {
  30115. continue;
  30116. }
  30117. this._keys.push(key);
  30118. }
  30119. };
  30120. /**
  30121. * Specifies if two material defines are equal.
  30122. * @param other - A material define instance to compare to.
  30123. * @returns - Boolean indicating if the material defines are equal (true) or not (false).
  30124. */
  30125. MaterialDefines.prototype.isEqual = function (other) {
  30126. if (this._keys.length !== other._keys.length) {
  30127. return false;
  30128. }
  30129. for (var index = 0; index < this._keys.length; index++) {
  30130. var prop = this._keys[index];
  30131. if (this[prop] !== other[prop]) {
  30132. return false;
  30133. }
  30134. }
  30135. return true;
  30136. };
  30137. /**
  30138. * Clones this instance's defines to another instance.
  30139. * @param other - material defines to clone values to.
  30140. */
  30141. MaterialDefines.prototype.cloneTo = function (other) {
  30142. if (this._keys.length !== other._keys.length) {
  30143. other._keys = this._keys.slice(0);
  30144. }
  30145. for (var index = 0; index < this._keys.length; index++) {
  30146. var prop = this._keys[index];
  30147. other[prop] = this[prop];
  30148. }
  30149. };
  30150. /**
  30151. * Resets the material define values.
  30152. */
  30153. MaterialDefines.prototype.reset = function () {
  30154. for (var index = 0; index < this._keys.length; index++) {
  30155. var prop = this._keys[index];
  30156. if (typeof (this[prop]) === "number") {
  30157. this[prop] = 0;
  30158. }
  30159. else {
  30160. this[prop] = false;
  30161. }
  30162. }
  30163. };
  30164. /**
  30165. * Converts the material define values to a string.
  30166. * @returns - String of material define information.
  30167. */
  30168. MaterialDefines.prototype.toString = function () {
  30169. var result = "";
  30170. for (var index = 0; index < this._keys.length; index++) {
  30171. var prop = this._keys[index];
  30172. var value = this[prop];
  30173. if (typeof (value) === "number") {
  30174. result += "#define " + prop + " " + this[prop] + "\n";
  30175. }
  30176. else if (value) {
  30177. result += "#define " + prop + "\n";
  30178. }
  30179. }
  30180. return result;
  30181. };
  30182. return MaterialDefines;
  30183. }());
  30184. BABYLON.MaterialDefines = MaterialDefines;
  30185. /**
  30186. * This offers the main features of a material in BJS.
  30187. */
  30188. var Material = /** @class */ (function () {
  30189. /**
  30190. * Creates a material instance.
  30191. * @param name - The name of the material.
  30192. * @param scene - The BJS scene to reference.
  30193. * @param doNotAdd - Specifies if the material should be added to the scene.
  30194. */
  30195. function Material(name, scene, doNotAdd) {
  30196. /**
  30197. * Specifies if the ready state should be checked on each call.
  30198. */
  30199. this.checkReadyOnEveryCall = false;
  30200. /**
  30201. * Specifies if the ready state should be checked once.
  30202. */
  30203. this.checkReadyOnlyOnce = false;
  30204. /**
  30205. * The state of the material.
  30206. */
  30207. this.state = "";
  30208. /**
  30209. * The alpha value of the material.
  30210. */
  30211. this._alpha = 1.0;
  30212. /**
  30213. * Specifies if back face culling is enabled.
  30214. */
  30215. this._backFaceCulling = true;
  30216. /**
  30217. * Specifies if the material should be serialized.
  30218. */
  30219. this.doNotSerialize = false;
  30220. /**
  30221. * Specifies if the effect should be stored on sub meshes.
  30222. */
  30223. this.storeEffectOnSubMeshes = false;
  30224. /**
  30225. * An event triggered when the material is disposed.
  30226. * @type {BABYLON.Observable}
  30227. */
  30228. this.onDisposeObservable = new BABYLON.Observable();
  30229. /**
  30230. * An event triggered when the material is bound.
  30231. * @type {BABYLON.Observable}
  30232. */
  30233. this.onBindObservable = new BABYLON.Observable();
  30234. /**
  30235. * An event triggered when the material is unbound.
  30236. * @type {BABYLON.Observable}
  30237. */
  30238. this.onUnBindObservable = new BABYLON.Observable();
  30239. /**
  30240. * Stores the value of the alpha mode.
  30241. */
  30242. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  30243. /**
  30244. * Stores the state of the need depth pre-pass value.
  30245. */
  30246. this._needDepthPrePass = false;
  30247. /**
  30248. * Specifies if depth writing should be disabled.
  30249. */
  30250. this.disableDepthWrite = false;
  30251. /**
  30252. * Specifies if depth writing should be forced.
  30253. */
  30254. this.forceDepthWrite = false;
  30255. /**
  30256. * Specifies if there should be a separate pass for culling.
  30257. */
  30258. this.separateCullingPass = false;
  30259. /**
  30260. * Stores the state specifing if fog should be enabled.
  30261. */
  30262. this._fogEnabled = true;
  30263. /**
  30264. * Stores the size of points.
  30265. */
  30266. this.pointSize = 1.0;
  30267. /**
  30268. * Stores the z offset value.
  30269. */
  30270. this.zOffset = 0;
  30271. /**
  30272. * Specifies if the material was previously ready.
  30273. */
  30274. this._wasPreviouslyReady = false;
  30275. /**
  30276. * Stores the fill mode state.
  30277. */
  30278. this._fillMode = Material.TriangleFillMode;
  30279. this.name = name;
  30280. this.id = name || BABYLON.Tools.RandomId();
  30281. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  30282. if (this._scene.useRightHandedSystem) {
  30283. this.sideOrientation = Material.ClockWiseSideOrientation;
  30284. }
  30285. else {
  30286. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  30287. }
  30288. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  30289. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  30290. if (!doNotAdd) {
  30291. this._scene.materials.push(this);
  30292. }
  30293. }
  30294. Object.defineProperty(Material, "TriangleFillMode", {
  30295. /**
  30296. * Returns the triangle fill mode.
  30297. */
  30298. get: function () {
  30299. return Material._TriangleFillMode;
  30300. },
  30301. enumerable: true,
  30302. configurable: true
  30303. });
  30304. Object.defineProperty(Material, "WireFrameFillMode", {
  30305. /**
  30306. * Returns the wireframe mode.
  30307. */
  30308. get: function () {
  30309. return Material._WireFrameFillMode;
  30310. },
  30311. enumerable: true,
  30312. configurable: true
  30313. });
  30314. Object.defineProperty(Material, "PointFillMode", {
  30315. /**
  30316. * Returns the point fill mode.
  30317. */
  30318. get: function () {
  30319. return Material._PointFillMode;
  30320. },
  30321. enumerable: true,
  30322. configurable: true
  30323. });
  30324. Object.defineProperty(Material, "PointListDrawMode", {
  30325. /**
  30326. * Returns the point list draw mode.
  30327. */
  30328. get: function () {
  30329. return Material._PointListDrawMode;
  30330. },
  30331. enumerable: true,
  30332. configurable: true
  30333. });
  30334. Object.defineProperty(Material, "LineListDrawMode", {
  30335. /**
  30336. * Returns the line list draw mode.
  30337. */
  30338. get: function () {
  30339. return Material._LineListDrawMode;
  30340. },
  30341. enumerable: true,
  30342. configurable: true
  30343. });
  30344. Object.defineProperty(Material, "LineLoopDrawMode", {
  30345. /**
  30346. * Returns the line loop draw mode.
  30347. */
  30348. get: function () {
  30349. return Material._LineLoopDrawMode;
  30350. },
  30351. enumerable: true,
  30352. configurable: true
  30353. });
  30354. Object.defineProperty(Material, "LineStripDrawMode", {
  30355. /**
  30356. * Returns the line strip draw mode.
  30357. */
  30358. get: function () {
  30359. return Material._LineStripDrawMode;
  30360. },
  30361. enumerable: true,
  30362. configurable: true
  30363. });
  30364. Object.defineProperty(Material, "TriangleStripDrawMode", {
  30365. /**
  30366. * Returns the triangle strip draw mode.
  30367. */
  30368. get: function () {
  30369. return Material._TriangleStripDrawMode;
  30370. },
  30371. enumerable: true,
  30372. configurable: true
  30373. });
  30374. Object.defineProperty(Material, "TriangleFanDrawMode", {
  30375. /**
  30376. * Returns the triangle fan draw mode.
  30377. */
  30378. get: function () {
  30379. return Material._TriangleFanDrawMode;
  30380. },
  30381. enumerable: true,
  30382. configurable: true
  30383. });
  30384. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  30385. /**
  30386. * Returns the clock-wise side orientation.
  30387. */
  30388. get: function () {
  30389. return Material._ClockWiseSideOrientation;
  30390. },
  30391. enumerable: true,
  30392. configurable: true
  30393. });
  30394. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  30395. /**
  30396. * Returns the counter clock-wise side orientation.
  30397. */
  30398. get: function () {
  30399. return Material._CounterClockWiseSideOrientation;
  30400. },
  30401. enumerable: true,
  30402. configurable: true
  30403. });
  30404. Object.defineProperty(Material, "TextureDirtyFlag", {
  30405. /**
  30406. * Returns the dirty texture flag value.
  30407. */
  30408. get: function () {
  30409. return Material._TextureDirtyFlag;
  30410. },
  30411. enumerable: true,
  30412. configurable: true
  30413. });
  30414. Object.defineProperty(Material, "LightDirtyFlag", {
  30415. /**
  30416. * Returns the dirty light flag value.
  30417. */
  30418. get: function () {
  30419. return Material._LightDirtyFlag;
  30420. },
  30421. enumerable: true,
  30422. configurable: true
  30423. });
  30424. Object.defineProperty(Material, "FresnelDirtyFlag", {
  30425. /**
  30426. * Returns the dirty fresnel flag value.
  30427. */
  30428. get: function () {
  30429. return Material._FresnelDirtyFlag;
  30430. },
  30431. enumerable: true,
  30432. configurable: true
  30433. });
  30434. Object.defineProperty(Material, "AttributesDirtyFlag", {
  30435. /**
  30436. * Returns the dirty attributes flag value.
  30437. */
  30438. get: function () {
  30439. return Material._AttributesDirtyFlag;
  30440. },
  30441. enumerable: true,
  30442. configurable: true
  30443. });
  30444. Object.defineProperty(Material, "MiscDirtyFlag", {
  30445. /**
  30446. * Returns the dirty misc flag value.
  30447. */
  30448. get: function () {
  30449. return Material._MiscDirtyFlag;
  30450. },
  30451. enumerable: true,
  30452. configurable: true
  30453. });
  30454. Object.defineProperty(Material.prototype, "alpha", {
  30455. /**
  30456. * Gets the alpha value of the material.
  30457. */
  30458. get: function () {
  30459. return this._alpha;
  30460. },
  30461. /**
  30462. * Sets the alpha value of the material.
  30463. */
  30464. set: function (value) {
  30465. if (this._alpha === value) {
  30466. return;
  30467. }
  30468. this._alpha = value;
  30469. this.markAsDirty(Material.MiscDirtyFlag);
  30470. },
  30471. enumerable: true,
  30472. configurable: true
  30473. });
  30474. Object.defineProperty(Material.prototype, "backFaceCulling", {
  30475. /**
  30476. * Gets the back-face culling state.
  30477. */
  30478. get: function () {
  30479. return this._backFaceCulling;
  30480. },
  30481. /**
  30482. * Sets the back-face culling state.
  30483. */
  30484. set: function (value) {
  30485. if (this._backFaceCulling === value) {
  30486. return;
  30487. }
  30488. this._backFaceCulling = value;
  30489. this.markAsDirty(Material.TextureDirtyFlag);
  30490. },
  30491. enumerable: true,
  30492. configurable: true
  30493. });
  30494. Object.defineProperty(Material.prototype, "onDispose", {
  30495. /**
  30496. * Called during a dispose event.
  30497. */
  30498. set: function (callback) {
  30499. if (this._onDisposeObserver) {
  30500. this.onDisposeObservable.remove(this._onDisposeObserver);
  30501. }
  30502. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  30503. },
  30504. enumerable: true,
  30505. configurable: true
  30506. });
  30507. Object.defineProperty(Material.prototype, "onBind", {
  30508. /**
  30509. * Called during a bind event.
  30510. */
  30511. set: function (callback) {
  30512. if (this._onBindObserver) {
  30513. this.onBindObservable.remove(this._onBindObserver);
  30514. }
  30515. this._onBindObserver = this.onBindObservable.add(callback);
  30516. },
  30517. enumerable: true,
  30518. configurable: true
  30519. });
  30520. Object.defineProperty(Material.prototype, "alphaMode", {
  30521. /**
  30522. * Gets the value of the alpha mode.
  30523. */
  30524. get: function () {
  30525. return this._alphaMode;
  30526. },
  30527. /**
  30528. * Sets the value of the alpha mode.
  30529. */
  30530. set: function (value) {
  30531. if (this._alphaMode === value) {
  30532. return;
  30533. }
  30534. this._alphaMode = value;
  30535. this.markAsDirty(Material.TextureDirtyFlag);
  30536. },
  30537. enumerable: true,
  30538. configurable: true
  30539. });
  30540. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  30541. /**
  30542. * Gets the depth pre-pass value.
  30543. */
  30544. get: function () {
  30545. return this._needDepthPrePass;
  30546. },
  30547. /**
  30548. * Sets the need depth pre-pass value.
  30549. */
  30550. set: function (value) {
  30551. if (this._needDepthPrePass === value) {
  30552. return;
  30553. }
  30554. this._needDepthPrePass = value;
  30555. if (this._needDepthPrePass) {
  30556. this.checkReadyOnEveryCall = true;
  30557. }
  30558. },
  30559. enumerable: true,
  30560. configurable: true
  30561. });
  30562. Object.defineProperty(Material.prototype, "fogEnabled", {
  30563. /**
  30564. * Gets the value of the fog enabled state.
  30565. */
  30566. get: function () {
  30567. return this._fogEnabled;
  30568. },
  30569. /**
  30570. * Sets the state for enabling fog.
  30571. */
  30572. set: function (value) {
  30573. if (this._fogEnabled === value) {
  30574. return;
  30575. }
  30576. this._fogEnabled = value;
  30577. this.markAsDirty(Material.MiscDirtyFlag);
  30578. },
  30579. enumerable: true,
  30580. configurable: true
  30581. });
  30582. Object.defineProperty(Material.prototype, "wireframe", {
  30583. /**
  30584. * Gets a value specifying if wireframe mode is enabled.
  30585. */
  30586. get: function () {
  30587. return this._fillMode === Material.WireFrameFillMode;
  30588. },
  30589. /**
  30590. * Sets the state of wireframe mode.
  30591. */
  30592. set: function (value) {
  30593. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  30594. },
  30595. enumerable: true,
  30596. configurable: true
  30597. });
  30598. Object.defineProperty(Material.prototype, "pointsCloud", {
  30599. /**
  30600. * Gets the value specifying if point clouds are enabled.
  30601. */
  30602. get: function () {
  30603. return this._fillMode === Material.PointFillMode;
  30604. },
  30605. /**
  30606. * Sets the state of point cloud mode.
  30607. */
  30608. set: function (value) {
  30609. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  30610. },
  30611. enumerable: true,
  30612. configurable: true
  30613. });
  30614. Object.defineProperty(Material.prototype, "fillMode", {
  30615. /**
  30616. * Gets the material fill mode.
  30617. */
  30618. get: function () {
  30619. return this._fillMode;
  30620. },
  30621. /**
  30622. * Sets the material fill mode.
  30623. */
  30624. set: function (value) {
  30625. if (this._fillMode === value) {
  30626. return;
  30627. }
  30628. this._fillMode = value;
  30629. this.markAsDirty(Material.MiscDirtyFlag);
  30630. },
  30631. enumerable: true,
  30632. configurable: true
  30633. });
  30634. /**
  30635. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  30636. * subclasses should override adding information pertainent to themselves.
  30637. * @returns - String with material information.
  30638. */
  30639. Material.prototype.toString = function (fullDetails) {
  30640. var ret = "Name: " + this.name;
  30641. if (fullDetails) {
  30642. }
  30643. return ret;
  30644. };
  30645. /**
  30646. * Gets the class name of the material.
  30647. * @returns - String with the class name of the material.
  30648. */
  30649. Material.prototype.getClassName = function () {
  30650. return "Material";
  30651. };
  30652. Object.defineProperty(Material.prototype, "isFrozen", {
  30653. /**
  30654. * Specifies if updates for the material been locked.
  30655. */
  30656. get: function () {
  30657. return this.checkReadyOnlyOnce;
  30658. },
  30659. enumerable: true,
  30660. configurable: true
  30661. });
  30662. /**
  30663. * Locks updates for the material.
  30664. */
  30665. Material.prototype.freeze = function () {
  30666. this.checkReadyOnlyOnce = true;
  30667. };
  30668. /**
  30669. * Unlocks updates for the material.
  30670. */
  30671. Material.prototype.unfreeze = function () {
  30672. this.checkReadyOnlyOnce = false;
  30673. };
  30674. /**
  30675. * Specifies if the material is ready to be used.
  30676. * @param mesh - BJS mesh.
  30677. * @param useInstances - Specifies if instances should be used.
  30678. * @returns - Boolean indicating if the material is ready to be used.
  30679. */
  30680. Material.prototype.isReady = function (mesh, useInstances) {
  30681. return true;
  30682. };
  30683. /**
  30684. * Specifies that the submesh is ready to be used.
  30685. * @param mesh - BJS mesh.
  30686. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  30687. * @param useInstances - Specifies that instances should be used.
  30688. * @returns - boolean indicating that the submesh is ready or not.
  30689. */
  30690. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  30691. return false;
  30692. };
  30693. /**
  30694. * Returns the material effect.
  30695. * @returns - Nullable material effect.
  30696. */
  30697. Material.prototype.getEffect = function () {
  30698. return this._effect;
  30699. };
  30700. /**
  30701. * Returns the BJS scene.
  30702. * @returns - BJS Scene.
  30703. */
  30704. Material.prototype.getScene = function () {
  30705. return this._scene;
  30706. };
  30707. /**
  30708. * Specifies if the material will require alpha blending
  30709. * @returns - Boolean specifying if alpha blending is needed.
  30710. */
  30711. Material.prototype.needAlphaBlending = function () {
  30712. return (this.alpha < 1.0);
  30713. };
  30714. /**
  30715. * Specifies if the mesh will require alpha blending.
  30716. * @param mesh - BJS mesh.
  30717. * @returns - Boolean specifying if alpha blending is needed for the mesh.
  30718. */
  30719. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  30720. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  30721. };
  30722. /**
  30723. * Specifies if this material should be rendered in alpha test mode.
  30724. * @returns - Boolean specifying if an alpha test is needed.
  30725. */
  30726. Material.prototype.needAlphaTesting = function () {
  30727. return false;
  30728. };
  30729. /**
  30730. * Gets the texture used for the alpha test.
  30731. * @returns - Nullable alpha test texture.
  30732. */
  30733. Material.prototype.getAlphaTestTexture = function () {
  30734. return null;
  30735. };
  30736. /**
  30737. * Marks the material to indicate that it needs to be re-calculated.
  30738. */
  30739. Material.prototype.markDirty = function () {
  30740. this._wasPreviouslyReady = false;
  30741. };
  30742. Material.prototype._preBind = function (effect, overrideOrientation) {
  30743. if (overrideOrientation === void 0) { overrideOrientation = null; }
  30744. var engine = this._scene.getEngine();
  30745. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  30746. var reverse = orientation === Material.ClockWiseSideOrientation;
  30747. engine.enableEffect(effect ? effect : this._effect);
  30748. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  30749. return reverse;
  30750. };
  30751. /**
  30752. * Binds the material to the mesh.
  30753. * @param world - World transformation matrix.
  30754. * @param mesh - Mesh to bind the material to.
  30755. */
  30756. Material.prototype.bind = function (world, mesh) {
  30757. };
  30758. /**
  30759. * Binds the submesh to the material.
  30760. * @param world - World transformation matrix.
  30761. * @param mesh - Mesh containing the submesh.
  30762. * @param subMesh - Submesh to bind the material to.
  30763. */
  30764. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  30765. };
  30766. /**
  30767. * Binds the world matrix to the material.
  30768. * @param world - World transformation matrix.
  30769. */
  30770. Material.prototype.bindOnlyWorldMatrix = function (world) {
  30771. };
  30772. /**
  30773. * Binds the scene's uniform buffer to the effect.
  30774. * @param effect - Effect to bind to the scene uniform buffer.
  30775. * @param sceneUbo - Scene uniform buffer.
  30776. */
  30777. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  30778. sceneUbo.bindToEffect(effect, "Scene");
  30779. };
  30780. /**
  30781. * Binds the view matrix to the effect.
  30782. * @param effect - Effect to bind the view matrix to.
  30783. */
  30784. Material.prototype.bindView = function (effect) {
  30785. if (!this._useUBO) {
  30786. effect.setMatrix("view", this.getScene().getViewMatrix());
  30787. }
  30788. else {
  30789. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  30790. }
  30791. };
  30792. /**
  30793. * Binds the view projection matrix to the effect.
  30794. * @param effect - Effect to bind the view projection matrix to.
  30795. */
  30796. Material.prototype.bindViewProjection = function (effect) {
  30797. if (!this._useUBO) {
  30798. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  30799. }
  30800. else {
  30801. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  30802. }
  30803. };
  30804. /**
  30805. * Specifies if material alpha testing should be turned on for the mesh.
  30806. * @param mesh - BJS mesh.
  30807. */
  30808. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  30809. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  30810. };
  30811. /**
  30812. * Processes to execute after binding the material to a mesh.
  30813. * @param mesh - BJS mesh.
  30814. */
  30815. Material.prototype._afterBind = function (mesh) {
  30816. this._scene._cachedMaterial = this;
  30817. if (mesh) {
  30818. this._scene._cachedVisibility = mesh.visibility;
  30819. }
  30820. else {
  30821. this._scene._cachedVisibility = 1;
  30822. }
  30823. if (mesh) {
  30824. this.onBindObservable.notifyObservers(mesh);
  30825. }
  30826. if (this.disableDepthWrite) {
  30827. var engine = this._scene.getEngine();
  30828. this._cachedDepthWriteState = engine.getDepthWrite();
  30829. engine.setDepthWrite(false);
  30830. }
  30831. };
  30832. /**
  30833. * Unbinds the material from the mesh.
  30834. */
  30835. Material.prototype.unbind = function () {
  30836. this.onUnBindObservable.notifyObservers(this);
  30837. if (this.disableDepthWrite) {
  30838. var engine = this._scene.getEngine();
  30839. engine.setDepthWrite(this._cachedDepthWriteState);
  30840. }
  30841. };
  30842. /**
  30843. * Gets the active textures from the material.
  30844. * @returns - Array of textures.
  30845. */
  30846. Material.prototype.getActiveTextures = function () {
  30847. return [];
  30848. };
  30849. /**
  30850. * Specifies if the material uses a texture.
  30851. * @param texture - Texture to check against the material.
  30852. * @returns - Boolean specifying if the material uses the texture.
  30853. */
  30854. Material.prototype.hasTexture = function (texture) {
  30855. return false;
  30856. };
  30857. /**
  30858. * Makes a duplicate of the material, and gives it a new name.
  30859. * @param name - Name to call the duplicated material.
  30860. * @returns - Nullable cloned material
  30861. */
  30862. Material.prototype.clone = function (name) {
  30863. return null;
  30864. };
  30865. /**
  30866. * Gets the meshes bound to the material.
  30867. * @returns - Array of meshes bound to the material.
  30868. */
  30869. Material.prototype.getBindedMeshes = function () {
  30870. var result = new Array();
  30871. for (var index = 0; index < this._scene.meshes.length; index++) {
  30872. var mesh = this._scene.meshes[index];
  30873. if (mesh.material === this) {
  30874. result.push(mesh);
  30875. }
  30876. }
  30877. return result;
  30878. };
  30879. /**
  30880. * Force shader compilation
  30881. * @param mesh - BJS mesh.
  30882. * @param onCompiled - function to execute once the material is compiled.
  30883. * @param options - options to pass to this function.
  30884. */
  30885. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  30886. var _this = this;
  30887. var localOptions = __assign({ clipPlane: false }, options);
  30888. var subMesh = new BABYLON.BaseSubMesh();
  30889. var scene = this.getScene();
  30890. var checkReady = function () {
  30891. if (!_this._scene || !_this._scene.getEngine()) {
  30892. return;
  30893. }
  30894. if (subMesh._materialDefines) {
  30895. subMesh._materialDefines._renderId = -1;
  30896. }
  30897. var clipPlaneState = scene.clipPlane;
  30898. if (localOptions.clipPlane) {
  30899. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  30900. }
  30901. if (_this.storeEffectOnSubMeshes) {
  30902. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  30903. if (onCompiled) {
  30904. onCompiled(_this);
  30905. }
  30906. }
  30907. else {
  30908. setTimeout(checkReady, 16);
  30909. }
  30910. }
  30911. else {
  30912. if (_this.isReady(mesh)) {
  30913. if (onCompiled) {
  30914. onCompiled(_this);
  30915. }
  30916. }
  30917. else {
  30918. setTimeout(checkReady, 16);
  30919. }
  30920. }
  30921. if (localOptions.clipPlane) {
  30922. scene.clipPlane = clipPlaneState;
  30923. }
  30924. };
  30925. checkReady();
  30926. };
  30927. /**
  30928. * Force shader compilation.
  30929. * @param mesh The mesh that will use this material
  30930. * @param options Additional options for compiling the shaders
  30931. * @returns A promise that resolves when the compilation completes
  30932. */
  30933. Material.prototype.forceCompilationAsync = function (mesh, options) {
  30934. var _this = this;
  30935. return new Promise(function (resolve) {
  30936. _this.forceCompilation(mesh, function () {
  30937. resolve();
  30938. }, options);
  30939. });
  30940. };
  30941. /**
  30942. * Marks a define in the material to indicate that it needs to be re-computed.
  30943. * @param flag - Material define flag.
  30944. */
  30945. Material.prototype.markAsDirty = function (flag) {
  30946. if (flag & Material.TextureDirtyFlag) {
  30947. this._markAllSubMeshesAsTexturesDirty();
  30948. }
  30949. if (flag & Material.LightDirtyFlag) {
  30950. this._markAllSubMeshesAsLightsDirty();
  30951. }
  30952. if (flag & Material.FresnelDirtyFlag) {
  30953. this._markAllSubMeshesAsFresnelDirty();
  30954. }
  30955. if (flag & Material.AttributesDirtyFlag) {
  30956. this._markAllSubMeshesAsAttributesDirty();
  30957. }
  30958. if (flag & Material.MiscDirtyFlag) {
  30959. this._markAllSubMeshesAsMiscDirty();
  30960. }
  30961. this.getScene().resetCachedMaterial();
  30962. };
  30963. /**
  30964. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated.
  30965. * @param func - function which checks material defines against the submeshes.
  30966. */
  30967. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  30968. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  30969. var mesh = _a[_i];
  30970. if (!mesh.subMeshes) {
  30971. continue;
  30972. }
  30973. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  30974. var subMesh = _c[_b];
  30975. if (subMesh.getMaterial() !== this) {
  30976. continue;
  30977. }
  30978. if (!subMesh._materialDefines) {
  30979. continue;
  30980. }
  30981. func(subMesh._materialDefines);
  30982. }
  30983. }
  30984. };
  30985. /**
  30986. * Indicates that image processing needs to be re-calculated for all submeshes.
  30987. */
  30988. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  30989. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  30990. };
  30991. /**
  30992. * Indicates that textures need to be re-calculated for all submeshes.
  30993. */
  30994. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  30995. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  30996. };
  30997. /**
  30998. * Indicates that fresnel needs to be re-calculated for all submeshes.
  30999. */
  31000. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  31001. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  31002. };
  31003. /**
  31004. * Indicates that fresnel and misc need to be re-calculated for all submeshes.
  31005. */
  31006. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  31007. this._markAllSubMeshesAsDirty(function (defines) {
  31008. defines.markAsFresnelDirty();
  31009. defines.markAsMiscDirty();
  31010. });
  31011. };
  31012. /**
  31013. * Indicates that lights need to be re-calculated for all submeshes.
  31014. */
  31015. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  31016. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  31017. };
  31018. /**
  31019. * Indicates that attributes need to be re-calculated for all submeshes.
  31020. */
  31021. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  31022. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  31023. };
  31024. /**
  31025. * Indicates that misc needs to be re-calculated for all submeshes.
  31026. */
  31027. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  31028. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  31029. };
  31030. /**
  31031. * Indicates that textures and misc need to be re-calculated for all submeshes.
  31032. */
  31033. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  31034. this._markAllSubMeshesAsDirty(function (defines) {
  31035. defines.markAsTexturesDirty();
  31036. defines.markAsMiscDirty();
  31037. });
  31038. };
  31039. /**
  31040. * Disposes the material.
  31041. * @param forceDisposeEffect - Specifies if effects should be force disposed.
  31042. * @param forceDisposeTextures - Specifies if textures should be force disposed.
  31043. */
  31044. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  31045. // Animations
  31046. this.getScene().stopAnimation(this);
  31047. // Remove from scene
  31048. var index = this._scene.materials.indexOf(this);
  31049. if (index >= 0) {
  31050. this._scene.materials.splice(index, 1);
  31051. }
  31052. // Remove from meshes
  31053. for (index = 0; index < this._scene.meshes.length; index++) {
  31054. var mesh = this._scene.meshes[index];
  31055. if (mesh.material === this) {
  31056. mesh.material = null;
  31057. if (mesh.geometry) {
  31058. var geometry = (mesh.geometry);
  31059. if (this.storeEffectOnSubMeshes) {
  31060. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  31061. var subMesh = _a[_i];
  31062. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  31063. if (forceDisposeEffect && subMesh._materialEffect) {
  31064. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  31065. }
  31066. }
  31067. }
  31068. else {
  31069. geometry._releaseVertexArrayObject(this._effect);
  31070. }
  31071. }
  31072. }
  31073. }
  31074. this._uniformBuffer.dispose();
  31075. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  31076. if (forceDisposeEffect && this._effect) {
  31077. if (!this.storeEffectOnSubMeshes) {
  31078. this._scene.getEngine()._releaseEffect(this._effect);
  31079. }
  31080. this._effect = null;
  31081. }
  31082. // Callback
  31083. this.onDisposeObservable.notifyObservers(this);
  31084. this.onDisposeObservable.clear();
  31085. this.onBindObservable.clear();
  31086. this.onUnBindObservable.clear();
  31087. };
  31088. /**
  31089. * Serializes this material.
  31090. * @returns - serialized material object.
  31091. */
  31092. Material.prototype.serialize = function () {
  31093. return BABYLON.SerializationHelper.Serialize(this);
  31094. };
  31095. /**
  31096. * Creates a MultiMaterial from parse MultiMaterial data.
  31097. * @param parsedMultiMaterial - Parsed MultiMaterial data.
  31098. * @param scene - BJS scene.
  31099. * @returns - MultiMaterial.
  31100. */
  31101. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  31102. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  31103. multiMaterial.id = parsedMultiMaterial.id;
  31104. if (BABYLON.Tags) {
  31105. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  31106. }
  31107. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  31108. var subMatId = parsedMultiMaterial.materials[matIndex];
  31109. if (subMatId) {
  31110. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  31111. }
  31112. else {
  31113. multiMaterial.subMaterials.push(null);
  31114. }
  31115. }
  31116. return multiMaterial;
  31117. };
  31118. /**
  31119. * Creates a material from parsed material data.
  31120. * @param parsedMaterial - Parsed material data.
  31121. * @param scene - BJS scene.
  31122. * @param rootUrl - Root URL containing the material information.
  31123. * @returns - Parsed material.
  31124. */
  31125. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  31126. if (!parsedMaterial.customType) {
  31127. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  31128. }
  31129. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  31130. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  31131. if (!BABYLON.LegacyPBRMaterial) {
  31132. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  31133. return;
  31134. }
  31135. }
  31136. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  31137. return materialType.Parse(parsedMaterial, scene, rootUrl);
  31138. ;
  31139. };
  31140. // Triangle views
  31141. Material._TriangleFillMode = 0;
  31142. Material._WireFrameFillMode = 1;
  31143. Material._PointFillMode = 2;
  31144. // Draw modes
  31145. Material._PointListDrawMode = 3;
  31146. Material._LineListDrawMode = 4;
  31147. Material._LineLoopDrawMode = 5;
  31148. Material._LineStripDrawMode = 6;
  31149. Material._TriangleStripDrawMode = 7;
  31150. Material._TriangleFanDrawMode = 8;
  31151. /**
  31152. * Stores the clock-wise side orientation.
  31153. */
  31154. Material._ClockWiseSideOrientation = 0;
  31155. /**
  31156. * Stores the counter clock-wise side orientation.
  31157. */
  31158. Material._CounterClockWiseSideOrientation = 1;
  31159. /**
  31160. * The dirty texture flag value.
  31161. */
  31162. Material._TextureDirtyFlag = 1;
  31163. /**
  31164. * The dirty light flag value.
  31165. */
  31166. Material._LightDirtyFlag = 2;
  31167. /**
  31168. * The dirty fresnel flag value.
  31169. */
  31170. Material._FresnelDirtyFlag = 4;
  31171. /**
  31172. * The dirty attribute flag value.
  31173. */
  31174. Material._AttributesDirtyFlag = 8;
  31175. /**
  31176. * The dirty misc flag value.
  31177. */
  31178. Material._MiscDirtyFlag = 16;
  31179. __decorate([
  31180. BABYLON.serialize()
  31181. ], Material.prototype, "id", void 0);
  31182. __decorate([
  31183. BABYLON.serialize()
  31184. ], Material.prototype, "name", void 0);
  31185. __decorate([
  31186. BABYLON.serialize()
  31187. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  31188. __decorate([
  31189. BABYLON.serialize()
  31190. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  31191. __decorate([
  31192. BABYLON.serialize()
  31193. ], Material.prototype, "state", void 0);
  31194. __decorate([
  31195. BABYLON.serialize("alpha")
  31196. ], Material.prototype, "_alpha", void 0);
  31197. __decorate([
  31198. BABYLON.serialize("backFaceCulling")
  31199. ], Material.prototype, "_backFaceCulling", void 0);
  31200. __decorate([
  31201. BABYLON.serialize()
  31202. ], Material.prototype, "sideOrientation", void 0);
  31203. __decorate([
  31204. BABYLON.serialize("alphaMode")
  31205. ], Material.prototype, "_alphaMode", void 0);
  31206. __decorate([
  31207. BABYLON.serialize()
  31208. ], Material.prototype, "_needDepthPrePass", void 0);
  31209. __decorate([
  31210. BABYLON.serialize()
  31211. ], Material.prototype, "disableDepthWrite", void 0);
  31212. __decorate([
  31213. BABYLON.serialize()
  31214. ], Material.prototype, "forceDepthWrite", void 0);
  31215. __decorate([
  31216. BABYLON.serialize()
  31217. ], Material.prototype, "separateCullingPass", void 0);
  31218. __decorate([
  31219. BABYLON.serialize("fogEnabled")
  31220. ], Material.prototype, "_fogEnabled", void 0);
  31221. __decorate([
  31222. BABYLON.serialize()
  31223. ], Material.prototype, "pointSize", void 0);
  31224. __decorate([
  31225. BABYLON.serialize()
  31226. ], Material.prototype, "zOffset", void 0);
  31227. __decorate([
  31228. BABYLON.serialize()
  31229. ], Material.prototype, "wireframe", null);
  31230. __decorate([
  31231. BABYLON.serialize()
  31232. ], Material.prototype, "pointsCloud", null);
  31233. __decorate([
  31234. BABYLON.serialize()
  31235. ], Material.prototype, "fillMode", null);
  31236. return Material;
  31237. }());
  31238. BABYLON.Material = Material;
  31239. })(BABYLON || (BABYLON = {}));
  31240. //# sourceMappingURL=babylon.material.js.map
  31241. var BABYLON;
  31242. (function (BABYLON) {
  31243. var UniformBuffer = /** @class */ (function () {
  31244. /**
  31245. * Uniform buffer objects.
  31246. *
  31247. * Handles blocks of uniform on the GPU.
  31248. *
  31249. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  31250. *
  31251. * For more information, please refer to :
  31252. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  31253. */
  31254. function UniformBuffer(engine, data, dynamic) {
  31255. this._engine = engine;
  31256. this._noUBO = !engine.supportsUniformBuffers;
  31257. this._dynamic = dynamic;
  31258. this._data = data || [];
  31259. this._uniformLocations = {};
  31260. this._uniformSizes = {};
  31261. this._uniformLocationPointer = 0;
  31262. this._needSync = false;
  31263. if (this._noUBO) {
  31264. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  31265. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  31266. this.updateFloat = this._updateFloatForEffect;
  31267. this.updateFloat2 = this._updateFloat2ForEffect;
  31268. this.updateFloat3 = this._updateFloat3ForEffect;
  31269. this.updateFloat4 = this._updateFloat4ForEffect;
  31270. this.updateMatrix = this._updateMatrixForEffect;
  31271. this.updateVector3 = this._updateVector3ForEffect;
  31272. this.updateVector4 = this._updateVector4ForEffect;
  31273. this.updateColor3 = this._updateColor3ForEffect;
  31274. this.updateColor4 = this._updateColor4ForEffect;
  31275. }
  31276. else {
  31277. this._engine._uniformBuffers.push(this);
  31278. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  31279. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  31280. this.updateFloat = this._updateFloatForUniform;
  31281. this.updateFloat2 = this._updateFloat2ForUniform;
  31282. this.updateFloat3 = this._updateFloat3ForUniform;
  31283. this.updateFloat4 = this._updateFloat4ForUniform;
  31284. this.updateMatrix = this._updateMatrixForUniform;
  31285. this.updateVector3 = this._updateVector3ForUniform;
  31286. this.updateVector4 = this._updateVector4ForUniform;
  31287. this.updateColor3 = this._updateColor3ForUniform;
  31288. this.updateColor4 = this._updateColor4ForUniform;
  31289. }
  31290. }
  31291. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  31292. // Properties
  31293. /**
  31294. * Indicates if the buffer is using the WebGL2 UBO implementation,
  31295. * or just falling back on setUniformXXX calls.
  31296. */
  31297. get: function () {
  31298. return !this._noUBO;
  31299. },
  31300. enumerable: true,
  31301. configurable: true
  31302. });
  31303. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  31304. /**
  31305. * Indicates if the WebGL underlying uniform buffer is in sync
  31306. * with the javascript cache data.
  31307. */
  31308. get: function () {
  31309. return !this._needSync;
  31310. },
  31311. enumerable: true,
  31312. configurable: true
  31313. });
  31314. /**
  31315. * Indicates if the WebGL underlying uniform buffer is dynamic.
  31316. * Also, a dynamic UniformBuffer will disable cache verification and always
  31317. * update the underlying WebGL uniform buffer to the GPU.
  31318. */
  31319. UniformBuffer.prototype.isDynamic = function () {
  31320. return this._dynamic !== undefined;
  31321. };
  31322. /**
  31323. * The data cache on JS side.
  31324. */
  31325. UniformBuffer.prototype.getData = function () {
  31326. return this._bufferData;
  31327. };
  31328. /**
  31329. * The underlying WebGL Uniform buffer.
  31330. */
  31331. UniformBuffer.prototype.getBuffer = function () {
  31332. return this._buffer;
  31333. };
  31334. /**
  31335. * std140 layout specifies how to align data within an UBO structure.
  31336. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  31337. * for specs.
  31338. */
  31339. UniformBuffer.prototype._fillAlignment = function (size) {
  31340. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  31341. // and 4x4 matrices
  31342. // TODO : change if other types are used
  31343. var alignment;
  31344. if (size <= 2) {
  31345. alignment = size;
  31346. }
  31347. else {
  31348. alignment = 4;
  31349. }
  31350. if ((this._uniformLocationPointer % alignment) !== 0) {
  31351. var oldPointer = this._uniformLocationPointer;
  31352. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  31353. var diff = this._uniformLocationPointer - oldPointer;
  31354. for (var i = 0; i < diff; i++) {
  31355. this._data.push(0);
  31356. }
  31357. }
  31358. };
  31359. /**
  31360. * Adds an uniform in the buffer.
  31361. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  31362. * for the layout to be correct !
  31363. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31364. * @param {number|number[]} size Data size, or data directly.
  31365. */
  31366. UniformBuffer.prototype.addUniform = function (name, size) {
  31367. if (this._noUBO) {
  31368. return;
  31369. }
  31370. if (this._uniformLocations[name] !== undefined) {
  31371. // Already existing uniform
  31372. return;
  31373. }
  31374. // This function must be called in the order of the shader layout !
  31375. // size can be the size of the uniform, or data directly
  31376. var data;
  31377. if (size instanceof Array) {
  31378. data = size;
  31379. size = data.length;
  31380. }
  31381. else {
  31382. size = size;
  31383. data = [];
  31384. // Fill with zeros
  31385. for (var i = 0; i < size; i++) {
  31386. data.push(0);
  31387. }
  31388. }
  31389. this._fillAlignment(size);
  31390. this._uniformSizes[name] = size;
  31391. this._uniformLocations[name] = this._uniformLocationPointer;
  31392. this._uniformLocationPointer += size;
  31393. for (var i = 0; i < size; i++) {
  31394. this._data.push(data[i]);
  31395. }
  31396. this._needSync = true;
  31397. };
  31398. /**
  31399. * Wrapper for addUniform.
  31400. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31401. * @param {Matrix} mat A 4x4 matrix.
  31402. */
  31403. UniformBuffer.prototype.addMatrix = function (name, mat) {
  31404. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  31405. };
  31406. /**
  31407. * Wrapper for addUniform.
  31408. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31409. * @param {number} x
  31410. * @param {number} y
  31411. */
  31412. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  31413. var temp = [x, y];
  31414. this.addUniform(name, temp);
  31415. };
  31416. /**
  31417. * Wrapper for addUniform.
  31418. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31419. * @param {number} x
  31420. * @param {number} y
  31421. * @param {number} z
  31422. */
  31423. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  31424. var temp = [x, y, z];
  31425. this.addUniform(name, temp);
  31426. };
  31427. /**
  31428. * Wrapper for addUniform.
  31429. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31430. * @param {Color3} color
  31431. */
  31432. UniformBuffer.prototype.addColor3 = function (name, color) {
  31433. var temp = new Array();
  31434. color.toArray(temp);
  31435. this.addUniform(name, temp);
  31436. };
  31437. /**
  31438. * Wrapper for addUniform.
  31439. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31440. * @param {Color3} color
  31441. * @param {number} alpha
  31442. */
  31443. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  31444. var temp = new Array();
  31445. color.toArray(temp);
  31446. temp.push(alpha);
  31447. this.addUniform(name, temp);
  31448. };
  31449. /**
  31450. * Wrapper for addUniform.
  31451. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31452. * @param {Vector3} vector
  31453. */
  31454. UniformBuffer.prototype.addVector3 = function (name, vector) {
  31455. var temp = new Array();
  31456. vector.toArray(temp);
  31457. this.addUniform(name, temp);
  31458. };
  31459. /**
  31460. * Wrapper for addUniform.
  31461. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31462. */
  31463. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  31464. this.addUniform(name, 12);
  31465. };
  31466. /**
  31467. * Wrapper for addUniform.
  31468. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31469. */
  31470. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  31471. this.addUniform(name, 8);
  31472. };
  31473. /**
  31474. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  31475. */
  31476. UniformBuffer.prototype.create = function () {
  31477. if (this._noUBO) {
  31478. return;
  31479. }
  31480. if (this._buffer) {
  31481. return; // nothing to do
  31482. }
  31483. // See spec, alignment must be filled as a vec4
  31484. this._fillAlignment(4);
  31485. this._bufferData = new Float32Array(this._data);
  31486. this._rebuild();
  31487. this._needSync = true;
  31488. };
  31489. UniformBuffer.prototype._rebuild = function () {
  31490. if (this._noUBO) {
  31491. return;
  31492. }
  31493. if (this._dynamic) {
  31494. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  31495. }
  31496. else {
  31497. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  31498. }
  31499. };
  31500. /**
  31501. * Updates the WebGL Uniform Buffer on the GPU.
  31502. * If the `dynamic` flag is set to true, no cache comparison is done.
  31503. * Otherwise, the buffer will be updated only if the cache differs.
  31504. */
  31505. UniformBuffer.prototype.update = function () {
  31506. if (!this._buffer) {
  31507. this.create();
  31508. return;
  31509. }
  31510. if (!this._dynamic && !this._needSync) {
  31511. return;
  31512. }
  31513. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  31514. this._needSync = false;
  31515. };
  31516. /**
  31517. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  31518. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  31519. * @param {number[]|Float32Array} data Flattened data
  31520. * @param {number} size Size of the data.
  31521. */
  31522. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  31523. var location = this._uniformLocations[uniformName];
  31524. if (location === undefined) {
  31525. if (this._buffer) {
  31526. // Cannot add an uniform if the buffer is already created
  31527. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  31528. return;
  31529. }
  31530. this.addUniform(uniformName, size);
  31531. location = this._uniformLocations[uniformName];
  31532. }
  31533. if (!this._buffer) {
  31534. this.create();
  31535. }
  31536. if (!this._dynamic) {
  31537. // Cache for static uniform buffers
  31538. var changed = false;
  31539. for (var i = 0; i < size; i++) {
  31540. if (this._bufferData[location + i] !== data[i]) {
  31541. changed = true;
  31542. this._bufferData[location + i] = data[i];
  31543. }
  31544. }
  31545. this._needSync = this._needSync || changed;
  31546. }
  31547. else {
  31548. // No cache for dynamic
  31549. for (var i = 0; i < size; i++) {
  31550. this._bufferData[location + i] = data[i];
  31551. }
  31552. }
  31553. };
  31554. // Update methods
  31555. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  31556. // To match std140, matrix must be realigned
  31557. for (var i = 0; i < 3; i++) {
  31558. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  31559. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  31560. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  31561. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  31562. }
  31563. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  31564. };
  31565. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  31566. this._currentEffect.setMatrix3x3(name, matrix);
  31567. };
  31568. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  31569. this._currentEffect.setMatrix2x2(name, matrix);
  31570. };
  31571. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  31572. // To match std140, matrix must be realigned
  31573. for (var i = 0; i < 2; i++) {
  31574. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  31575. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  31576. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  31577. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  31578. }
  31579. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  31580. };
  31581. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  31582. this._currentEffect.setFloat(name, x);
  31583. };
  31584. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  31585. UniformBuffer._tempBuffer[0] = x;
  31586. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  31587. };
  31588. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  31589. if (suffix === void 0) { suffix = ""; }
  31590. this._currentEffect.setFloat2(name + suffix, x, y);
  31591. };
  31592. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  31593. if (suffix === void 0) { suffix = ""; }
  31594. UniformBuffer._tempBuffer[0] = x;
  31595. UniformBuffer._tempBuffer[1] = y;
  31596. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  31597. };
  31598. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  31599. if (suffix === void 0) { suffix = ""; }
  31600. this._currentEffect.setFloat3(name + suffix, x, y, z);
  31601. };
  31602. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  31603. if (suffix === void 0) { suffix = ""; }
  31604. UniformBuffer._tempBuffer[0] = x;
  31605. UniformBuffer._tempBuffer[1] = y;
  31606. UniformBuffer._tempBuffer[2] = z;
  31607. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  31608. };
  31609. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  31610. if (suffix === void 0) { suffix = ""; }
  31611. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  31612. };
  31613. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  31614. if (suffix === void 0) { suffix = ""; }
  31615. UniformBuffer._tempBuffer[0] = x;
  31616. UniformBuffer._tempBuffer[1] = y;
  31617. UniformBuffer._tempBuffer[2] = z;
  31618. UniformBuffer._tempBuffer[3] = w;
  31619. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  31620. };
  31621. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  31622. this._currentEffect.setMatrix(name, mat);
  31623. };
  31624. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  31625. this.updateUniform(name, mat.toArray(), 16);
  31626. };
  31627. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  31628. this._currentEffect.setVector3(name, vector);
  31629. };
  31630. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  31631. vector.toArray(UniformBuffer._tempBuffer);
  31632. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  31633. };
  31634. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  31635. this._currentEffect.setVector4(name, vector);
  31636. };
  31637. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  31638. vector.toArray(UniformBuffer._tempBuffer);
  31639. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  31640. };
  31641. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  31642. if (suffix === void 0) { suffix = ""; }
  31643. this._currentEffect.setColor3(name + suffix, color);
  31644. };
  31645. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  31646. if (suffix === void 0) { suffix = ""; }
  31647. color.toArray(UniformBuffer._tempBuffer);
  31648. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  31649. };
  31650. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  31651. if (suffix === void 0) { suffix = ""; }
  31652. this._currentEffect.setColor4(name + suffix, color, alpha);
  31653. };
  31654. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  31655. if (suffix === void 0) { suffix = ""; }
  31656. color.toArray(UniformBuffer._tempBuffer);
  31657. UniformBuffer._tempBuffer[3] = alpha;
  31658. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  31659. };
  31660. /**
  31661. * Sets a sampler uniform on the effect.
  31662. * @param {string} name Name of the sampler.
  31663. * @param {Texture} texture
  31664. */
  31665. UniformBuffer.prototype.setTexture = function (name, texture) {
  31666. this._currentEffect.setTexture(name, texture);
  31667. };
  31668. /**
  31669. * Directly updates the value of the uniform in the cache AND on the GPU.
  31670. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  31671. * @param {number[]|Float32Array} data Flattened data
  31672. */
  31673. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  31674. this.updateUniform(uniformName, data, data.length);
  31675. this.update();
  31676. };
  31677. /**
  31678. * Binds this uniform buffer to an effect.
  31679. * @param {Effect} effect
  31680. * @param {string} name Name of the uniform block in the shader.
  31681. */
  31682. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  31683. this._currentEffect = effect;
  31684. if (this._noUBO || !this._buffer) {
  31685. return;
  31686. }
  31687. effect.bindUniformBuffer(this._buffer, name);
  31688. };
  31689. /**
  31690. * Disposes the uniform buffer.
  31691. */
  31692. UniformBuffer.prototype.dispose = function () {
  31693. if (this._noUBO) {
  31694. return;
  31695. }
  31696. var index = this._engine._uniformBuffers.indexOf(this);
  31697. if (index !== -1) {
  31698. this._engine._uniformBuffers.splice(index, 1);
  31699. }
  31700. if (!this._buffer) {
  31701. return;
  31702. }
  31703. if (this._engine._releaseBuffer(this._buffer)) {
  31704. this._buffer = null;
  31705. }
  31706. };
  31707. // Pool for avoiding memory leaks
  31708. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  31709. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  31710. return UniformBuffer;
  31711. }());
  31712. BABYLON.UniformBuffer = UniformBuffer;
  31713. })(BABYLON || (BABYLON = {}));
  31714. //# sourceMappingURL=babylon.uniformBuffer.js.map
  31715. var BABYLON;
  31716. (function (BABYLON) {
  31717. var VertexData = /** @class */ (function () {
  31718. function VertexData() {
  31719. }
  31720. VertexData.prototype.set = function (data, kind) {
  31721. switch (kind) {
  31722. case BABYLON.VertexBuffer.PositionKind:
  31723. this.positions = data;
  31724. break;
  31725. case BABYLON.VertexBuffer.NormalKind:
  31726. this.normals = data;
  31727. break;
  31728. case BABYLON.VertexBuffer.TangentKind:
  31729. this.tangents = data;
  31730. break;
  31731. case BABYLON.VertexBuffer.UVKind:
  31732. this.uvs = data;
  31733. break;
  31734. case BABYLON.VertexBuffer.UV2Kind:
  31735. this.uvs2 = data;
  31736. break;
  31737. case BABYLON.VertexBuffer.UV3Kind:
  31738. this.uvs3 = data;
  31739. break;
  31740. case BABYLON.VertexBuffer.UV4Kind:
  31741. this.uvs4 = data;
  31742. break;
  31743. case BABYLON.VertexBuffer.UV5Kind:
  31744. this.uvs5 = data;
  31745. break;
  31746. case BABYLON.VertexBuffer.UV6Kind:
  31747. this.uvs6 = data;
  31748. break;
  31749. case BABYLON.VertexBuffer.ColorKind:
  31750. this.colors = data;
  31751. break;
  31752. case BABYLON.VertexBuffer.MatricesIndicesKind:
  31753. this.matricesIndices = data;
  31754. break;
  31755. case BABYLON.VertexBuffer.MatricesWeightsKind:
  31756. this.matricesWeights = data;
  31757. break;
  31758. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  31759. this.matricesIndicesExtra = data;
  31760. break;
  31761. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  31762. this.matricesWeightsExtra = data;
  31763. break;
  31764. }
  31765. };
  31766. /**
  31767. * Associates the vertexData to the passed Mesh.
  31768. * Sets it as updatable or not (default `false`).
  31769. * Returns the VertexData.
  31770. */
  31771. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  31772. this._applyTo(mesh, updatable);
  31773. return this;
  31774. };
  31775. /**
  31776. * Associates the vertexData to the passed Geometry.
  31777. * Sets it as updatable or not (default `false`).
  31778. * Returns the VertexData.
  31779. */
  31780. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  31781. this._applyTo(geometry, updatable);
  31782. return this;
  31783. };
  31784. /**
  31785. * Updates the associated mesh.
  31786. * Returns the VertexData.
  31787. */
  31788. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  31789. this._update(mesh);
  31790. return this;
  31791. };
  31792. /**
  31793. * Updates the associated geometry.
  31794. * Returns the VertexData.
  31795. */
  31796. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  31797. this._update(geometry);
  31798. return this;
  31799. };
  31800. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  31801. if (updatable === void 0) { updatable = false; }
  31802. if (this.positions) {
  31803. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  31804. }
  31805. if (this.normals) {
  31806. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  31807. }
  31808. if (this.tangents) {
  31809. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  31810. }
  31811. if (this.uvs) {
  31812. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  31813. }
  31814. if (this.uvs2) {
  31815. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  31816. }
  31817. if (this.uvs3) {
  31818. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  31819. }
  31820. if (this.uvs4) {
  31821. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  31822. }
  31823. if (this.uvs5) {
  31824. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  31825. }
  31826. if (this.uvs6) {
  31827. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  31828. }
  31829. if (this.colors) {
  31830. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  31831. }
  31832. if (this.matricesIndices) {
  31833. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  31834. }
  31835. if (this.matricesWeights) {
  31836. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  31837. }
  31838. if (this.matricesIndicesExtra) {
  31839. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  31840. }
  31841. if (this.matricesWeightsExtra) {
  31842. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  31843. }
  31844. if (this.indices) {
  31845. meshOrGeometry.setIndices(this.indices, null, updatable);
  31846. }
  31847. return this;
  31848. };
  31849. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  31850. if (this.positions) {
  31851. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  31852. }
  31853. if (this.normals) {
  31854. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  31855. }
  31856. if (this.tangents) {
  31857. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  31858. }
  31859. if (this.uvs) {
  31860. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  31861. }
  31862. if (this.uvs2) {
  31863. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  31864. }
  31865. if (this.uvs3) {
  31866. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  31867. }
  31868. if (this.uvs4) {
  31869. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  31870. }
  31871. if (this.uvs5) {
  31872. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  31873. }
  31874. if (this.uvs6) {
  31875. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  31876. }
  31877. if (this.colors) {
  31878. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  31879. }
  31880. if (this.matricesIndices) {
  31881. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  31882. }
  31883. if (this.matricesWeights) {
  31884. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  31885. }
  31886. if (this.matricesIndicesExtra) {
  31887. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  31888. }
  31889. if (this.matricesWeightsExtra) {
  31890. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  31891. }
  31892. if (this.indices) {
  31893. meshOrGeometry.setIndices(this.indices, null);
  31894. }
  31895. return this;
  31896. };
  31897. /**
  31898. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  31899. * Returns the VertexData.
  31900. */
  31901. VertexData.prototype.transform = function (matrix) {
  31902. var transformed = BABYLON.Vector3.Zero();
  31903. var index;
  31904. if (this.positions) {
  31905. var position = BABYLON.Vector3.Zero();
  31906. for (index = 0; index < this.positions.length; index += 3) {
  31907. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  31908. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  31909. this.positions[index] = transformed.x;
  31910. this.positions[index + 1] = transformed.y;
  31911. this.positions[index + 2] = transformed.z;
  31912. }
  31913. }
  31914. if (this.normals) {
  31915. var normal = BABYLON.Vector3.Zero();
  31916. for (index = 0; index < this.normals.length; index += 3) {
  31917. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  31918. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  31919. this.normals[index] = transformed.x;
  31920. this.normals[index + 1] = transformed.y;
  31921. this.normals[index + 2] = transformed.z;
  31922. }
  31923. }
  31924. if (this.tangents) {
  31925. var tangent = BABYLON.Vector4.Zero();
  31926. var tangentTransformed = BABYLON.Vector4.Zero();
  31927. for (index = 0; index < this.tangents.length; index += 4) {
  31928. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  31929. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  31930. this.tangents[index] = tangentTransformed.x;
  31931. this.tangents[index + 1] = tangentTransformed.y;
  31932. this.tangents[index + 2] = tangentTransformed.z;
  31933. this.tangents[index + 3] = tangentTransformed.w;
  31934. }
  31935. }
  31936. return this;
  31937. };
  31938. /**
  31939. * Merges the passed VertexData into the current one.
  31940. * Returns the modified VertexData.
  31941. */
  31942. VertexData.prototype.merge = function (other) {
  31943. this._validate();
  31944. other._validate();
  31945. if (!this.normals !== !other.normals ||
  31946. !this.tangents !== !other.tangents ||
  31947. !this.uvs !== !other.uvs ||
  31948. !this.uvs2 !== !other.uvs2 ||
  31949. !this.uvs3 !== !other.uvs3 ||
  31950. !this.uvs4 !== !other.uvs4 ||
  31951. !this.uvs5 !== !other.uvs5 ||
  31952. !this.uvs6 !== !other.uvs6 ||
  31953. !this.colors !== !other.colors ||
  31954. !this.matricesIndices !== !other.matricesIndices ||
  31955. !this.matricesWeights !== !other.matricesWeights ||
  31956. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  31957. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  31958. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  31959. }
  31960. if (other.indices) {
  31961. if (!this.indices) {
  31962. this.indices = [];
  31963. }
  31964. var offset = this.positions ? this.positions.length / 3 : 0;
  31965. for (var index = 0; index < other.indices.length; index++) {
  31966. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  31967. this.indices.push(other.indices[index] + offset);
  31968. }
  31969. }
  31970. this.positions = this._mergeElement(this.positions, other.positions);
  31971. this.normals = this._mergeElement(this.normals, other.normals);
  31972. this.tangents = this._mergeElement(this.tangents, other.tangents);
  31973. this.uvs = this._mergeElement(this.uvs, other.uvs);
  31974. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  31975. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  31976. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  31977. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  31978. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  31979. this.colors = this._mergeElement(this.colors, other.colors);
  31980. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  31981. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  31982. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  31983. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  31984. return this;
  31985. };
  31986. VertexData.prototype._mergeElement = function (source, other) {
  31987. if (!source) {
  31988. return other;
  31989. }
  31990. if (!other) {
  31991. return source;
  31992. }
  31993. var len = other.length + source.length;
  31994. var isSrcTypedArray = source instanceof Float32Array;
  31995. var isOthTypedArray = other instanceof Float32Array;
  31996. // use non-loop method when the source is Float32Array
  31997. if (isSrcTypedArray) {
  31998. var ret32 = new Float32Array(len);
  31999. ret32.set(source);
  32000. ret32.set(other, source.length);
  32001. return ret32;
  32002. // source is number[], when other is also use concat
  32003. }
  32004. else if (!isOthTypedArray) {
  32005. return source.concat(other);
  32006. // source is a number[], but other is a Float32Array, loop required
  32007. }
  32008. else {
  32009. var ret = source.slice(0); // copy source to a separate array
  32010. for (var i = 0, len = other.length; i < len; i++) {
  32011. ret.push(other[i]);
  32012. }
  32013. return ret;
  32014. }
  32015. };
  32016. VertexData.prototype._validate = function () {
  32017. if (!this.positions) {
  32018. throw new Error("Positions are required");
  32019. }
  32020. var getElementCount = function (kind, values) {
  32021. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  32022. if ((values.length % stride) !== 0) {
  32023. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  32024. }
  32025. return values.length / stride;
  32026. };
  32027. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  32028. var validateElementCount = function (kind, values) {
  32029. var elementCount = getElementCount(kind, values);
  32030. if (elementCount !== positionsElementCount) {
  32031. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  32032. }
  32033. };
  32034. if (this.normals)
  32035. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  32036. if (this.tangents)
  32037. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  32038. if (this.uvs)
  32039. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  32040. if (this.uvs2)
  32041. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  32042. if (this.uvs3)
  32043. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  32044. if (this.uvs4)
  32045. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  32046. if (this.uvs5)
  32047. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  32048. if (this.uvs6)
  32049. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  32050. if (this.colors)
  32051. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  32052. if (this.matricesIndices)
  32053. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  32054. if (this.matricesWeights)
  32055. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  32056. if (this.matricesIndicesExtra)
  32057. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  32058. if (this.matricesWeightsExtra)
  32059. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  32060. };
  32061. /**
  32062. * Serializes the VertexData.
  32063. * Returns a serialized object.
  32064. */
  32065. VertexData.prototype.serialize = function () {
  32066. var serializationObject = this.serialize();
  32067. if (this.positions) {
  32068. serializationObject.positions = this.positions;
  32069. }
  32070. if (this.normals) {
  32071. serializationObject.normals = this.normals;
  32072. }
  32073. if (this.tangents) {
  32074. serializationObject.tangents = this.tangents;
  32075. }
  32076. if (this.uvs) {
  32077. serializationObject.uvs = this.uvs;
  32078. }
  32079. if (this.uvs2) {
  32080. serializationObject.uvs2 = this.uvs2;
  32081. }
  32082. if (this.uvs3) {
  32083. serializationObject.uvs3 = this.uvs3;
  32084. }
  32085. if (this.uvs4) {
  32086. serializationObject.uvs4 = this.uvs4;
  32087. }
  32088. if (this.uvs5) {
  32089. serializationObject.uvs5 = this.uvs5;
  32090. }
  32091. if (this.uvs6) {
  32092. serializationObject.uvs6 = this.uvs6;
  32093. }
  32094. if (this.colors) {
  32095. serializationObject.colors = this.colors;
  32096. }
  32097. if (this.matricesIndices) {
  32098. serializationObject.matricesIndices = this.matricesIndices;
  32099. serializationObject.matricesIndices._isExpanded = true;
  32100. }
  32101. if (this.matricesWeights) {
  32102. serializationObject.matricesWeights = this.matricesWeights;
  32103. }
  32104. if (this.matricesIndicesExtra) {
  32105. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  32106. serializationObject.matricesIndicesExtra._isExpanded = true;
  32107. }
  32108. if (this.matricesWeightsExtra) {
  32109. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  32110. }
  32111. serializationObject.indices = this.indices;
  32112. return serializationObject;
  32113. };
  32114. // Statics
  32115. /**
  32116. * Returns the object VertexData associated to the passed mesh.
  32117. */
  32118. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  32119. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  32120. };
  32121. /**
  32122. * Returns the object VertexData associated to the passed geometry.
  32123. */
  32124. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  32125. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  32126. };
  32127. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  32128. var result = new VertexData();
  32129. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  32130. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  32131. }
  32132. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32133. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  32134. }
  32135. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  32136. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  32137. }
  32138. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32139. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  32140. }
  32141. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  32142. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  32143. }
  32144. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  32145. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  32146. }
  32147. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  32148. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  32149. }
  32150. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  32151. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  32152. }
  32153. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  32154. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  32155. }
  32156. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  32157. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  32158. }
  32159. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  32160. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  32161. }
  32162. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  32163. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  32164. }
  32165. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  32166. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  32167. }
  32168. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  32169. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  32170. }
  32171. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  32172. return result;
  32173. };
  32174. /**
  32175. * Creates the vertexData of the Ribbon.
  32176. */
  32177. VertexData.CreateRibbon = function (options) {
  32178. var pathArray = options.pathArray;
  32179. var closeArray = options.closeArray || false;
  32180. var closePath = options.closePath || false;
  32181. var invertUV = options.invertUV || false;
  32182. var defaultOffset = Math.floor(pathArray[0].length / 2);
  32183. var offset = options.offset || defaultOffset;
  32184. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  32185. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32186. var customUV = options.uvs;
  32187. var customColors = options.colors;
  32188. var positions = [];
  32189. var indices = [];
  32190. var normals = [];
  32191. var uvs = [];
  32192. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  32193. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  32194. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  32195. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  32196. var minlg; // minimal length among all paths from pathArray
  32197. var lg = []; // array of path lengths : nb of vertex per path
  32198. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  32199. var p; // path iterator
  32200. var i; // point iterator
  32201. var j; // point iterator
  32202. // if single path in pathArray
  32203. if (pathArray.length < 2) {
  32204. var ar1 = [];
  32205. var ar2 = [];
  32206. for (i = 0; i < pathArray[0].length - offset; i++) {
  32207. ar1.push(pathArray[0][i]);
  32208. ar2.push(pathArray[0][i + offset]);
  32209. }
  32210. pathArray = [ar1, ar2];
  32211. }
  32212. // positions and horizontal distances (u)
  32213. var idc = 0;
  32214. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  32215. var path;
  32216. var l;
  32217. minlg = pathArray[0].length;
  32218. var vectlg;
  32219. var dist;
  32220. for (p = 0; p < pathArray.length; p++) {
  32221. uTotalDistance[p] = 0;
  32222. us[p] = [0];
  32223. path = pathArray[p];
  32224. l = path.length;
  32225. minlg = (minlg < l) ? minlg : l;
  32226. j = 0;
  32227. while (j < l) {
  32228. positions.push(path[j].x, path[j].y, path[j].z);
  32229. if (j > 0) {
  32230. vectlg = path[j].subtract(path[j - 1]).length();
  32231. dist = vectlg + uTotalDistance[p];
  32232. us[p].push(dist);
  32233. uTotalDistance[p] = dist;
  32234. }
  32235. j++;
  32236. }
  32237. if (closePath) {
  32238. j--;
  32239. positions.push(path[0].x, path[0].y, path[0].z);
  32240. vectlg = path[j].subtract(path[0]).length();
  32241. dist = vectlg + uTotalDistance[p];
  32242. us[p].push(dist);
  32243. uTotalDistance[p] = dist;
  32244. }
  32245. lg[p] = l + closePathCorr;
  32246. idx[p] = idc;
  32247. idc += (l + closePathCorr);
  32248. }
  32249. // vertical distances (v)
  32250. var path1;
  32251. var path2;
  32252. var vertex1 = null;
  32253. var vertex2 = null;
  32254. for (i = 0; i < minlg + closePathCorr; i++) {
  32255. vTotalDistance[i] = 0;
  32256. vs[i] = [0];
  32257. for (p = 0; p < pathArray.length - 1; p++) {
  32258. path1 = pathArray[p];
  32259. path2 = pathArray[p + 1];
  32260. if (i === minlg) {
  32261. vertex1 = path1[0];
  32262. vertex2 = path2[0];
  32263. }
  32264. else {
  32265. vertex1 = path1[i];
  32266. vertex2 = path2[i];
  32267. }
  32268. vectlg = vertex2.subtract(vertex1).length();
  32269. dist = vectlg + vTotalDistance[i];
  32270. vs[i].push(dist);
  32271. vTotalDistance[i] = dist;
  32272. }
  32273. if (closeArray && vertex2 && vertex1) {
  32274. path1 = pathArray[p];
  32275. path2 = pathArray[0];
  32276. if (i === minlg) {
  32277. vertex2 = path2[0];
  32278. }
  32279. vectlg = vertex2.subtract(vertex1).length();
  32280. dist = vectlg + vTotalDistance[i];
  32281. vTotalDistance[i] = dist;
  32282. }
  32283. }
  32284. // uvs
  32285. var u;
  32286. var v;
  32287. if (customUV) {
  32288. for (p = 0; p < customUV.length; p++) {
  32289. uvs.push(customUV[p].x, customUV[p].y);
  32290. }
  32291. }
  32292. else {
  32293. for (p = 0; p < pathArray.length; p++) {
  32294. for (i = 0; i < minlg + closePathCorr; i++) {
  32295. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  32296. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  32297. if (invertUV) {
  32298. uvs.push(v, u);
  32299. }
  32300. else {
  32301. uvs.push(u, v);
  32302. }
  32303. }
  32304. }
  32305. }
  32306. // indices
  32307. p = 0; // path index
  32308. var pi = 0; // positions array index
  32309. var l1 = lg[p] - 1; // path1 length
  32310. var l2 = lg[p + 1] - 1; // path2 length
  32311. var min = (l1 < l2) ? l1 : l2; // current path stop index
  32312. var shft = idx[1] - idx[0]; // shift
  32313. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  32314. while (pi <= min && p < path1nb) {
  32315. // 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
  32316. indices.push(pi, pi + shft, pi + 1);
  32317. indices.push(pi + shft + 1, pi + 1, pi + shft);
  32318. pi += 1;
  32319. if (pi === min) {
  32320. p++;
  32321. if (p === lg.length - 1) {
  32322. shft = idx[0] - idx[p];
  32323. l1 = lg[p] - 1;
  32324. l2 = lg[0] - 1;
  32325. }
  32326. else {
  32327. shft = idx[p + 1] - idx[p];
  32328. l1 = lg[p] - 1;
  32329. l2 = lg[p + 1] - 1;
  32330. }
  32331. pi = idx[p];
  32332. min = (l1 < l2) ? l1 + pi : l2 + pi;
  32333. }
  32334. }
  32335. // normals
  32336. VertexData.ComputeNormals(positions, indices, normals);
  32337. if (closePath) {
  32338. var indexFirst = 0;
  32339. var indexLast = 0;
  32340. for (p = 0; p < pathArray.length; p++) {
  32341. indexFirst = idx[p] * 3;
  32342. if (p + 1 < pathArray.length) {
  32343. indexLast = (idx[p + 1] - 1) * 3;
  32344. }
  32345. else {
  32346. indexLast = normals.length - 3;
  32347. }
  32348. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  32349. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  32350. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  32351. normals[indexLast] = normals[indexFirst];
  32352. normals[indexLast + 1] = normals[indexFirst + 1];
  32353. normals[indexLast + 2] = normals[indexFirst + 2];
  32354. }
  32355. }
  32356. // sides
  32357. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  32358. // Colors
  32359. var colors = null;
  32360. if (customColors) {
  32361. colors = new Float32Array(customColors.length * 4);
  32362. for (var c = 0; c < customColors.length; c++) {
  32363. colors[c * 4] = customColors[c].r;
  32364. colors[c * 4 + 1] = customColors[c].g;
  32365. colors[c * 4 + 2] = customColors[c].b;
  32366. colors[c * 4 + 3] = customColors[c].a;
  32367. }
  32368. }
  32369. // Result
  32370. var vertexData = new VertexData();
  32371. var positions32 = new Float32Array(positions);
  32372. var normals32 = new Float32Array(normals);
  32373. var uvs32 = new Float32Array(uvs);
  32374. vertexData.indices = indices;
  32375. vertexData.positions = positions32;
  32376. vertexData.normals = normals32;
  32377. vertexData.uvs = uvs32;
  32378. if (colors) {
  32379. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  32380. }
  32381. if (closePath) {
  32382. vertexData._idx = idx;
  32383. }
  32384. return vertexData;
  32385. };
  32386. /**
  32387. * Creates the VertexData of the Box.
  32388. */
  32389. VertexData.CreateBox = function (options) {
  32390. var normalsSource = [
  32391. new BABYLON.Vector3(0, 0, 1),
  32392. new BABYLON.Vector3(0, 0, -1),
  32393. new BABYLON.Vector3(1, 0, 0),
  32394. new BABYLON.Vector3(-1, 0, 0),
  32395. new BABYLON.Vector3(0, 1, 0),
  32396. new BABYLON.Vector3(0, -1, 0)
  32397. ];
  32398. var indices = [];
  32399. var positions = [];
  32400. var normals = [];
  32401. var uvs = [];
  32402. var width = options.width || options.size || 1;
  32403. var height = options.height || options.size || 1;
  32404. var depth = options.depth || options.size || 1;
  32405. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32406. var faceUV = options.faceUV || new Array(6);
  32407. var faceColors = options.faceColors;
  32408. var colors = [];
  32409. // default face colors and UV if undefined
  32410. for (var f = 0; f < 6; f++) {
  32411. if (faceUV[f] === undefined) {
  32412. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  32413. }
  32414. if (faceColors && faceColors[f] === undefined) {
  32415. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  32416. }
  32417. }
  32418. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  32419. // Create each face in turn.
  32420. for (var index = 0; index < normalsSource.length; index++) {
  32421. var normal = normalsSource[index];
  32422. // Get two vectors perpendicular to the face normal and to each other.
  32423. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  32424. var side2 = BABYLON.Vector3.Cross(normal, side1);
  32425. // Six indices (two triangles) per face.
  32426. var verticesLength = positions.length / 3;
  32427. indices.push(verticesLength);
  32428. indices.push(verticesLength + 1);
  32429. indices.push(verticesLength + 2);
  32430. indices.push(verticesLength);
  32431. indices.push(verticesLength + 2);
  32432. indices.push(verticesLength + 3);
  32433. // Four vertices per face.
  32434. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  32435. positions.push(vertex.x, vertex.y, vertex.z);
  32436. normals.push(normal.x, normal.y, normal.z);
  32437. uvs.push(faceUV[index].z, faceUV[index].w);
  32438. if (faceColors) {
  32439. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  32440. }
  32441. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  32442. positions.push(vertex.x, vertex.y, vertex.z);
  32443. normals.push(normal.x, normal.y, normal.z);
  32444. uvs.push(faceUV[index].x, faceUV[index].w);
  32445. if (faceColors) {
  32446. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  32447. }
  32448. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  32449. positions.push(vertex.x, vertex.y, vertex.z);
  32450. normals.push(normal.x, normal.y, normal.z);
  32451. uvs.push(faceUV[index].x, faceUV[index].y);
  32452. if (faceColors) {
  32453. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  32454. }
  32455. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  32456. positions.push(vertex.x, vertex.y, vertex.z);
  32457. normals.push(normal.x, normal.y, normal.z);
  32458. uvs.push(faceUV[index].z, faceUV[index].y);
  32459. if (faceColors) {
  32460. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  32461. }
  32462. }
  32463. // sides
  32464. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  32465. // Result
  32466. var vertexData = new VertexData();
  32467. vertexData.indices = indices;
  32468. vertexData.positions = positions;
  32469. vertexData.normals = normals;
  32470. vertexData.uvs = uvs;
  32471. if (faceColors) {
  32472. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  32473. vertexData.colors = totalColors;
  32474. }
  32475. return vertexData;
  32476. };
  32477. /**
  32478. * Creates the VertexData of the Sphere.
  32479. */
  32480. VertexData.CreateSphere = function (options) {
  32481. var segments = options.segments || 32;
  32482. var diameterX = options.diameterX || options.diameter || 1;
  32483. var diameterY = options.diameterY || options.diameter || 1;
  32484. var diameterZ = options.diameterZ || options.diameter || 1;
  32485. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  32486. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  32487. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32488. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  32489. var totalZRotationSteps = 2 + segments;
  32490. var totalYRotationSteps = 2 * totalZRotationSteps;
  32491. var indices = [];
  32492. var positions = [];
  32493. var normals = [];
  32494. var uvs = [];
  32495. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  32496. var normalizedZ = zRotationStep / totalZRotationSteps;
  32497. var angleZ = normalizedZ * Math.PI * slice;
  32498. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  32499. var normalizedY = yRotationStep / totalYRotationSteps;
  32500. var angleY = normalizedY * Math.PI * 2 * arc;
  32501. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  32502. var rotationY = BABYLON.Matrix.RotationY(angleY);
  32503. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  32504. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  32505. var vertex = complete.multiply(radius);
  32506. var normal = complete.divide(radius).normalize();
  32507. positions.push(vertex.x, vertex.y, vertex.z);
  32508. normals.push(normal.x, normal.y, normal.z);
  32509. uvs.push(normalizedY, normalizedZ);
  32510. }
  32511. if (zRotationStep > 0) {
  32512. var verticesCount = positions.length / 3;
  32513. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  32514. indices.push((firstIndex));
  32515. indices.push((firstIndex + 1));
  32516. indices.push(firstIndex + totalYRotationSteps + 1);
  32517. indices.push((firstIndex + totalYRotationSteps + 1));
  32518. indices.push((firstIndex + 1));
  32519. indices.push((firstIndex + totalYRotationSteps + 2));
  32520. }
  32521. }
  32522. }
  32523. // Sides
  32524. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  32525. // Result
  32526. var vertexData = new VertexData();
  32527. vertexData.indices = indices;
  32528. vertexData.positions = positions;
  32529. vertexData.normals = normals;
  32530. vertexData.uvs = uvs;
  32531. return vertexData;
  32532. };
  32533. /**
  32534. * Creates the VertexData of the Cylinder or Cone.
  32535. */
  32536. VertexData.CreateCylinder = function (options) {
  32537. var height = options.height || 2;
  32538. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  32539. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  32540. var tessellation = options.tessellation || 24;
  32541. var subdivisions = options.subdivisions || 1;
  32542. var hasRings = options.hasRings ? true : false;
  32543. var enclose = options.enclose ? true : false;
  32544. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  32545. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32546. var faceUV = options.faceUV || new Array(3);
  32547. var faceColors = options.faceColors;
  32548. // default face colors and UV if undefined
  32549. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  32550. var ringNb = (hasRings) ? subdivisions : 1;
  32551. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  32552. var f;
  32553. for (f = 0; f < surfaceNb; f++) {
  32554. if (faceColors && faceColors[f] === undefined) {
  32555. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  32556. }
  32557. }
  32558. for (f = 0; f < surfaceNb; f++) {
  32559. if (faceUV && faceUV[f] === undefined) {
  32560. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  32561. }
  32562. }
  32563. var indices = new Array();
  32564. var positions = new Array();
  32565. var normals = new Array();
  32566. var uvs = new Array();
  32567. var colors = new Array();
  32568. var angle_step = Math.PI * 2 * arc / tessellation;
  32569. var angle;
  32570. var h;
  32571. var radius;
  32572. var tan = (diameterBottom - diameterTop) / 2 / height;
  32573. var ringVertex = BABYLON.Vector3.Zero();
  32574. var ringNormal = BABYLON.Vector3.Zero();
  32575. var ringFirstVertex = BABYLON.Vector3.Zero();
  32576. var ringFirstNormal = BABYLON.Vector3.Zero();
  32577. var quadNormal = BABYLON.Vector3.Zero();
  32578. var Y = BABYLON.Axis.Y;
  32579. // positions, normals, uvs
  32580. var i;
  32581. var j;
  32582. var r;
  32583. var ringIdx = 1;
  32584. var s = 1; // surface index
  32585. var cs = 0;
  32586. var v = 0;
  32587. for (i = 0; i <= subdivisions; i++) {
  32588. h = i / subdivisions;
  32589. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  32590. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  32591. for (r = 0; r < ringIdx; r++) {
  32592. if (hasRings) {
  32593. s += r;
  32594. }
  32595. if (enclose) {
  32596. s += 2 * r;
  32597. }
  32598. for (j = 0; j <= tessellation; j++) {
  32599. angle = j * angle_step;
  32600. // position
  32601. ringVertex.x = Math.cos(-angle) * radius;
  32602. ringVertex.y = -height / 2 + h * height;
  32603. ringVertex.z = Math.sin(-angle) * radius;
  32604. // normal
  32605. if (diameterTop === 0 && i === subdivisions) {
  32606. // if no top cap, reuse former normals
  32607. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  32608. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  32609. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  32610. }
  32611. else {
  32612. ringNormal.x = ringVertex.x;
  32613. ringNormal.z = ringVertex.z;
  32614. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  32615. ringNormal.normalize();
  32616. }
  32617. // keep first ring vertex values for enclose
  32618. if (j === 0) {
  32619. ringFirstVertex.copyFrom(ringVertex);
  32620. ringFirstNormal.copyFrom(ringNormal);
  32621. }
  32622. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  32623. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  32624. if (hasRings) {
  32625. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  32626. }
  32627. else {
  32628. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  32629. }
  32630. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  32631. if (faceColors) {
  32632. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  32633. }
  32634. }
  32635. // if enclose, add four vertices and their dedicated normals
  32636. if (arc !== 1 && enclose) {
  32637. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  32638. positions.push(0, ringVertex.y, 0);
  32639. positions.push(0, ringVertex.y, 0);
  32640. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  32641. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  32642. quadNormal.normalize();
  32643. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  32644. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  32645. quadNormal.normalize();
  32646. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  32647. if (hasRings) {
  32648. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  32649. }
  32650. else {
  32651. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  32652. }
  32653. uvs.push(faceUV[s + 1].x, v);
  32654. uvs.push(faceUV[s + 1].z, v);
  32655. if (hasRings) {
  32656. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  32657. }
  32658. else {
  32659. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  32660. }
  32661. uvs.push(faceUV[s + 2].x, v);
  32662. uvs.push(faceUV[s + 2].z, v);
  32663. if (faceColors) {
  32664. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  32665. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  32666. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  32667. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  32668. }
  32669. }
  32670. if (cs !== s) {
  32671. cs = s;
  32672. }
  32673. }
  32674. }
  32675. // indices
  32676. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  32677. var s;
  32678. i = 0;
  32679. for (s = 0; s < subdivisions; s++) {
  32680. var i0 = 0;
  32681. var i1 = 0;
  32682. var i2 = 0;
  32683. var i3 = 0;
  32684. for (j = 0; j < tessellation; j++) {
  32685. i0 = i * (e + 1) + j;
  32686. i1 = (i + 1) * (e + 1) + j;
  32687. i2 = i * (e + 1) + (j + 1);
  32688. i3 = (i + 1) * (e + 1) + (j + 1);
  32689. indices.push(i0, i1, i2);
  32690. indices.push(i3, i2, i1);
  32691. }
  32692. if (arc !== 1 && enclose) {
  32693. indices.push(i0 + 2, i1 + 2, i2 + 2);
  32694. indices.push(i3 + 2, i2 + 2, i1 + 2);
  32695. indices.push(i0 + 4, i1 + 4, i2 + 4);
  32696. indices.push(i3 + 4, i2 + 4, i1 + 4);
  32697. }
  32698. i = (hasRings) ? (i + 2) : (i + 1);
  32699. }
  32700. // Caps
  32701. var createCylinderCap = function (isTop) {
  32702. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  32703. if (radius === 0) {
  32704. return;
  32705. }
  32706. // Cap positions, normals & uvs
  32707. var angle;
  32708. var circleVector;
  32709. var i;
  32710. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  32711. var c = null;
  32712. if (faceColors) {
  32713. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  32714. }
  32715. // cap center
  32716. var vbase = positions.length / 3;
  32717. var offset = isTop ? height / 2 : -height / 2;
  32718. var center = new BABYLON.Vector3(0, offset, 0);
  32719. positions.push(center.x, center.y, center.z);
  32720. normals.push(0, isTop ? 1 : -1, 0);
  32721. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  32722. if (c) {
  32723. colors.push(c.r, c.g, c.b, c.a);
  32724. }
  32725. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  32726. for (i = 0; i <= tessellation; i++) {
  32727. angle = Math.PI * 2 * i * arc / tessellation;
  32728. var cos = Math.cos(-angle);
  32729. var sin = Math.sin(-angle);
  32730. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  32731. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  32732. positions.push(circleVector.x, circleVector.y, circleVector.z);
  32733. normals.push(0, isTop ? 1 : -1, 0);
  32734. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  32735. if (c) {
  32736. colors.push(c.r, c.g, c.b, c.a);
  32737. }
  32738. }
  32739. // Cap indices
  32740. for (i = 0; i < tessellation; i++) {
  32741. if (!isTop) {
  32742. indices.push(vbase);
  32743. indices.push(vbase + (i + 1));
  32744. indices.push(vbase + (i + 2));
  32745. }
  32746. else {
  32747. indices.push(vbase);
  32748. indices.push(vbase + (i + 2));
  32749. indices.push(vbase + (i + 1));
  32750. }
  32751. }
  32752. };
  32753. // add caps to geometry
  32754. createCylinderCap(false);
  32755. createCylinderCap(true);
  32756. // Sides
  32757. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  32758. var vertexData = new VertexData();
  32759. vertexData.indices = indices;
  32760. vertexData.positions = positions;
  32761. vertexData.normals = normals;
  32762. vertexData.uvs = uvs;
  32763. if (faceColors) {
  32764. vertexData.colors = colors;
  32765. }
  32766. return vertexData;
  32767. };
  32768. /**
  32769. * Creates the VertexData of the Torus.
  32770. */
  32771. VertexData.CreateTorus = function (options) {
  32772. var indices = [];
  32773. var positions = [];
  32774. var normals = [];
  32775. var uvs = [];
  32776. var diameter = options.diameter || 1;
  32777. var thickness = options.thickness || 0.5;
  32778. var tessellation = options.tessellation || 16;
  32779. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32780. var stride = tessellation + 1;
  32781. for (var i = 0; i <= tessellation; i++) {
  32782. var u = i / tessellation;
  32783. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  32784. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  32785. for (var j = 0; j <= tessellation; j++) {
  32786. var v = 1 - j / tessellation;
  32787. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  32788. var dx = Math.cos(innerAngle);
  32789. var dy = Math.sin(innerAngle);
  32790. // Create a vertex.
  32791. var normal = new BABYLON.Vector3(dx, dy, 0);
  32792. var position = normal.scale(thickness / 2);
  32793. var textureCoordinate = new BABYLON.Vector2(u, v);
  32794. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  32795. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  32796. positions.push(position.x, position.y, position.z);
  32797. normals.push(normal.x, normal.y, normal.z);
  32798. uvs.push(textureCoordinate.x, textureCoordinate.y);
  32799. // And create indices for two triangles.
  32800. var nextI = (i + 1) % stride;
  32801. var nextJ = (j + 1) % stride;
  32802. indices.push(i * stride + j);
  32803. indices.push(i * stride + nextJ);
  32804. indices.push(nextI * stride + j);
  32805. indices.push(i * stride + nextJ);
  32806. indices.push(nextI * stride + nextJ);
  32807. indices.push(nextI * stride + j);
  32808. }
  32809. }
  32810. // Sides
  32811. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  32812. // Result
  32813. var vertexData = new VertexData();
  32814. vertexData.indices = indices;
  32815. vertexData.positions = positions;
  32816. vertexData.normals = normals;
  32817. vertexData.uvs = uvs;
  32818. return vertexData;
  32819. };
  32820. /**
  32821. * Creates the VertexData of the LineSystem.
  32822. */
  32823. VertexData.CreateLineSystem = function (options) {
  32824. var indices = [];
  32825. var positions = [];
  32826. var lines = options.lines;
  32827. var colors = options.colors;
  32828. var vertexColors = [];
  32829. var idx = 0;
  32830. for (var l = 0; l < lines.length; l++) {
  32831. var points = lines[l];
  32832. for (var index = 0; index < points.length; index++) {
  32833. positions.push(points[index].x, points[index].y, points[index].z);
  32834. if (colors) {
  32835. var color = colors[l];
  32836. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  32837. }
  32838. if (index > 0) {
  32839. indices.push(idx - 1);
  32840. indices.push(idx);
  32841. }
  32842. idx++;
  32843. }
  32844. }
  32845. var vertexData = new VertexData();
  32846. vertexData.indices = indices;
  32847. vertexData.positions = positions;
  32848. if (colors) {
  32849. vertexData.colors = vertexColors;
  32850. }
  32851. return vertexData;
  32852. };
  32853. /**
  32854. * Create the VertexData of the DashedLines.
  32855. */
  32856. VertexData.CreateDashedLines = function (options) {
  32857. var dashSize = options.dashSize || 3;
  32858. var gapSize = options.gapSize || 1;
  32859. var dashNb = options.dashNb || 200;
  32860. var points = options.points;
  32861. var positions = new Array();
  32862. var indices = new Array();
  32863. var curvect = BABYLON.Vector3.Zero();
  32864. var lg = 0;
  32865. var nb = 0;
  32866. var shft = 0;
  32867. var dashshft = 0;
  32868. var curshft = 0;
  32869. var idx = 0;
  32870. var i = 0;
  32871. for (i = 0; i < points.length - 1; i++) {
  32872. points[i + 1].subtractToRef(points[i], curvect);
  32873. lg += curvect.length();
  32874. }
  32875. shft = lg / dashNb;
  32876. dashshft = dashSize * shft / (dashSize + gapSize);
  32877. for (i = 0; i < points.length - 1; i++) {
  32878. points[i + 1].subtractToRef(points[i], curvect);
  32879. nb = Math.floor(curvect.length() / shft);
  32880. curvect.normalize();
  32881. for (var j = 0; j < nb; j++) {
  32882. curshft = shft * j;
  32883. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  32884. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  32885. indices.push(idx, idx + 1);
  32886. idx += 2;
  32887. }
  32888. }
  32889. // Result
  32890. var vertexData = new VertexData();
  32891. vertexData.positions = positions;
  32892. vertexData.indices = indices;
  32893. return vertexData;
  32894. };
  32895. /**
  32896. * Creates the VertexData of the Ground.
  32897. */
  32898. VertexData.CreateGround = function (options) {
  32899. var indices = [];
  32900. var positions = [];
  32901. var normals = [];
  32902. var uvs = [];
  32903. var row, col;
  32904. var width = options.width || 1;
  32905. var height = options.height || 1;
  32906. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  32907. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  32908. for (row = 0; row <= subdivisionsY; row++) {
  32909. for (col = 0; col <= subdivisionsX; col++) {
  32910. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  32911. var normal = new BABYLON.Vector3(0, 1.0, 0);
  32912. positions.push(position.x, position.y, position.z);
  32913. normals.push(normal.x, normal.y, normal.z);
  32914. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  32915. }
  32916. }
  32917. for (row = 0; row < subdivisionsY; row++) {
  32918. for (col = 0; col < subdivisionsX; col++) {
  32919. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  32920. indices.push(col + 1 + row * (subdivisionsX + 1));
  32921. indices.push(col + row * (subdivisionsX + 1));
  32922. indices.push(col + (row + 1) * (subdivisionsX + 1));
  32923. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  32924. indices.push(col + row * (subdivisionsX + 1));
  32925. }
  32926. }
  32927. // Result
  32928. var vertexData = new VertexData();
  32929. vertexData.indices = indices;
  32930. vertexData.positions = positions;
  32931. vertexData.normals = normals;
  32932. vertexData.uvs = uvs;
  32933. return vertexData;
  32934. };
  32935. /**
  32936. * Creates the VertexData of the TiledGround.
  32937. */
  32938. VertexData.CreateTiledGround = function (options) {
  32939. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  32940. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  32941. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  32942. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  32943. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  32944. var precision = options.precision || { w: 1, h: 1 };
  32945. var indices = new Array();
  32946. var positions = new Array();
  32947. var normals = new Array();
  32948. var uvs = new Array();
  32949. var row, col, tileRow, tileCol;
  32950. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  32951. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  32952. precision.w = (precision.w < 1) ? 1 : precision.w;
  32953. precision.h = (precision.h < 1) ? 1 : precision.h;
  32954. var tileSize = {
  32955. 'w': (xmax - xmin) / subdivisions.w,
  32956. 'h': (zmax - zmin) / subdivisions.h
  32957. };
  32958. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  32959. // Indices
  32960. var base = positions.length / 3;
  32961. var rowLength = precision.w + 1;
  32962. for (row = 0; row < precision.h; row++) {
  32963. for (col = 0; col < precision.w; col++) {
  32964. var square = [
  32965. base + col + row * rowLength,
  32966. base + (col + 1) + row * rowLength,
  32967. base + (col + 1) + (row + 1) * rowLength,
  32968. base + col + (row + 1) * rowLength
  32969. ];
  32970. indices.push(square[1]);
  32971. indices.push(square[2]);
  32972. indices.push(square[3]);
  32973. indices.push(square[0]);
  32974. indices.push(square[1]);
  32975. indices.push(square[3]);
  32976. }
  32977. }
  32978. // Position, normals and uvs
  32979. var position = BABYLON.Vector3.Zero();
  32980. var normal = new BABYLON.Vector3(0, 1.0, 0);
  32981. for (row = 0; row <= precision.h; row++) {
  32982. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  32983. for (col = 0; col <= precision.w; col++) {
  32984. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  32985. position.y = 0;
  32986. positions.push(position.x, position.y, position.z);
  32987. normals.push(normal.x, normal.y, normal.z);
  32988. uvs.push(col / precision.w, row / precision.h);
  32989. }
  32990. }
  32991. }
  32992. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  32993. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  32994. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  32995. }
  32996. }
  32997. // Result
  32998. var vertexData = new VertexData();
  32999. vertexData.indices = indices;
  33000. vertexData.positions = positions;
  33001. vertexData.normals = normals;
  33002. vertexData.uvs = uvs;
  33003. return vertexData;
  33004. };
  33005. /**
  33006. * Creates the VertexData of the Ground designed from a heightmap.
  33007. */
  33008. VertexData.CreateGroundFromHeightMap = function (options) {
  33009. var indices = [];
  33010. var positions = [];
  33011. var normals = [];
  33012. var uvs = [];
  33013. var row, col;
  33014. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  33015. // Vertices
  33016. for (row = 0; row <= options.subdivisions; row++) {
  33017. for (col = 0; col <= options.subdivisions; col++) {
  33018. 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));
  33019. // Compute height
  33020. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  33021. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  33022. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  33023. var r = options.buffer[pos] / 255.0;
  33024. var g = options.buffer[pos + 1] / 255.0;
  33025. var b = options.buffer[pos + 2] / 255.0;
  33026. var gradient = r * filter.r + g * filter.g + b * filter.b;
  33027. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  33028. // Add vertex
  33029. positions.push(position.x, position.y, position.z);
  33030. normals.push(0, 0, 0);
  33031. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  33032. }
  33033. }
  33034. // Indices
  33035. for (row = 0; row < options.subdivisions; row++) {
  33036. for (col = 0; col < options.subdivisions; col++) {
  33037. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  33038. indices.push(col + 1 + row * (options.subdivisions + 1));
  33039. indices.push(col + row * (options.subdivisions + 1));
  33040. indices.push(col + (row + 1) * (options.subdivisions + 1));
  33041. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  33042. indices.push(col + row * (options.subdivisions + 1));
  33043. }
  33044. }
  33045. // Normals
  33046. VertexData.ComputeNormals(positions, indices, normals);
  33047. // Result
  33048. var vertexData = new VertexData();
  33049. vertexData.indices = indices;
  33050. vertexData.positions = positions;
  33051. vertexData.normals = normals;
  33052. vertexData.uvs = uvs;
  33053. return vertexData;
  33054. };
  33055. /**
  33056. * Creates the VertexData of the Plane.
  33057. */
  33058. VertexData.CreatePlane = function (options) {
  33059. var indices = [];
  33060. var positions = [];
  33061. var normals = [];
  33062. var uvs = [];
  33063. var width = options.width || options.size || 1;
  33064. var height = options.height || options.size || 1;
  33065. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33066. // Vertices
  33067. var halfWidth = width / 2.0;
  33068. var halfHeight = height / 2.0;
  33069. positions.push(-halfWidth, -halfHeight, 0);
  33070. normals.push(0, 0, -1.0);
  33071. uvs.push(0.0, 0.0);
  33072. positions.push(halfWidth, -halfHeight, 0);
  33073. normals.push(0, 0, -1.0);
  33074. uvs.push(1.0, 0.0);
  33075. positions.push(halfWidth, halfHeight, 0);
  33076. normals.push(0, 0, -1.0);
  33077. uvs.push(1.0, 1.0);
  33078. positions.push(-halfWidth, halfHeight, 0);
  33079. normals.push(0, 0, -1.0);
  33080. uvs.push(0.0, 1.0);
  33081. // Indices
  33082. indices.push(0);
  33083. indices.push(1);
  33084. indices.push(2);
  33085. indices.push(0);
  33086. indices.push(2);
  33087. indices.push(3);
  33088. // Sides
  33089. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33090. // Result
  33091. var vertexData = new VertexData();
  33092. vertexData.indices = indices;
  33093. vertexData.positions = positions;
  33094. vertexData.normals = normals;
  33095. vertexData.uvs = uvs;
  33096. return vertexData;
  33097. };
  33098. /**
  33099. * Creates the VertexData of the Disc or regular Polygon.
  33100. */
  33101. VertexData.CreateDisc = function (options) {
  33102. var positions = new Array();
  33103. var indices = new Array();
  33104. var normals = new Array();
  33105. var uvs = new Array();
  33106. var radius = options.radius || 0.5;
  33107. var tessellation = options.tessellation || 64;
  33108. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  33109. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33110. // positions and uvs
  33111. positions.push(0, 0, 0); // disc center first
  33112. uvs.push(0.5, 0.5);
  33113. var theta = Math.PI * 2 * arc;
  33114. var step = theta / tessellation;
  33115. for (var a = 0; a < theta; a += step) {
  33116. var x = Math.cos(a);
  33117. var y = Math.sin(a);
  33118. var u = (x + 1) / 2;
  33119. var v = (1 - y) / 2;
  33120. positions.push(radius * x, radius * y, 0);
  33121. uvs.push(u, v);
  33122. }
  33123. if (arc === 1) {
  33124. positions.push(positions[3], positions[4], positions[5]); // close the circle
  33125. uvs.push(uvs[2], uvs[3]);
  33126. }
  33127. //indices
  33128. var vertexNb = positions.length / 3;
  33129. for (var i = 1; i < vertexNb - 1; i++) {
  33130. indices.push(i + 1, 0, i);
  33131. }
  33132. // result
  33133. VertexData.ComputeNormals(positions, indices, normals);
  33134. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33135. var vertexData = new VertexData();
  33136. vertexData.indices = indices;
  33137. vertexData.positions = positions;
  33138. vertexData.normals = normals;
  33139. vertexData.uvs = uvs;
  33140. return vertexData;
  33141. };
  33142. /**
  33143. * Re-creates the VertexData of the Polygon for sideOrientation.
  33144. */
  33145. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  33146. var faceUV = fUV || new Array(3);
  33147. var faceColors = fColors;
  33148. var colors = [];
  33149. // default face colors and UV if undefined
  33150. for (var f = 0; f < 3; f++) {
  33151. if (faceUV[f] === undefined) {
  33152. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  33153. }
  33154. if (faceColors && faceColors[f] === undefined) {
  33155. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  33156. }
  33157. }
  33158. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33159. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33160. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  33161. var indices = polygon.getIndices();
  33162. // set face colours and textures
  33163. var idx = 0;
  33164. var face = 0;
  33165. for (var index = 0; index < normals.length; index += 3) {
  33166. //Edge Face no. 1
  33167. if (Math.abs(normals[index + 1]) < 0.001) {
  33168. face = 1;
  33169. }
  33170. //Top Face no. 0
  33171. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  33172. face = 0;
  33173. }
  33174. //Bottom Face no. 2
  33175. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  33176. face = 2;
  33177. }
  33178. idx = index / 3;
  33179. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  33180. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  33181. if (faceColors) {
  33182. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  33183. }
  33184. }
  33185. // sides
  33186. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  33187. // Result
  33188. var vertexData = new VertexData();
  33189. vertexData.indices = indices;
  33190. vertexData.positions = positions;
  33191. vertexData.normals = normals;
  33192. vertexData.uvs = uvs;
  33193. if (faceColors) {
  33194. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  33195. vertexData.colors = totalColors;
  33196. }
  33197. return vertexData;
  33198. };
  33199. /**
  33200. * Creates the VertexData of the IcoSphere.
  33201. */
  33202. VertexData.CreateIcoSphere = function (options) {
  33203. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33204. var radius = options.radius || 1;
  33205. var flat = (options.flat === undefined) ? true : options.flat;
  33206. var subdivisions = options.subdivisions || 4;
  33207. var radiusX = options.radiusX || radius;
  33208. var radiusY = options.radiusY || radius;
  33209. var radiusZ = options.radiusZ || radius;
  33210. var t = (1 + Math.sqrt(5)) / 2;
  33211. // 12 vertex x,y,z
  33212. var ico_vertices = [
  33213. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  33214. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  33215. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  33216. ];
  33217. // index of 3 vertex makes a face of icopshere
  33218. var ico_indices = [
  33219. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  33220. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  33221. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  33222. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  33223. ];
  33224. // vertex for uv have aliased position, not for UV
  33225. var vertices_unalias_id = [
  33226. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  33227. // vertex alias
  33228. 0,
  33229. 2,
  33230. 3,
  33231. 3,
  33232. 3,
  33233. 4,
  33234. 7,
  33235. 8,
  33236. 9,
  33237. 9,
  33238. 10,
  33239. 11 // 23: B + 12
  33240. ];
  33241. // uv as integer step (not pixels !)
  33242. var ico_vertexuv = [
  33243. 5, 1, 3, 1, 6, 4, 0, 0,
  33244. 5, 3, 4, 2, 2, 2, 4, 0,
  33245. 2, 0, 1, 1, 6, 0, 6, 2,
  33246. // vertex alias (for same vertex on different faces)
  33247. 0, 4,
  33248. 3, 3,
  33249. 4, 4,
  33250. 3, 1,
  33251. 4, 2,
  33252. 4, 4,
  33253. 0, 2,
  33254. 1, 1,
  33255. 2, 2,
  33256. 3, 3,
  33257. 1, 3,
  33258. 2, 4 // 23: B + 12
  33259. ];
  33260. // Vertices[0, 1, ...9, A, B] : position on UV plane
  33261. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  33262. // First island of uv mapping
  33263. // v = 4h 3+ 2
  33264. // v = 3h 9+ 4
  33265. // v = 2h 9+ 5 B
  33266. // v = 1h 9 1 0
  33267. // v = 0h 3 8 7 A
  33268. // u = 0 1 2 3 4 5 6 *a
  33269. // Second island of uv mapping
  33270. // v = 4h 0+ B+ 4+
  33271. // v = 3h A+ 2+
  33272. // v = 2h 7+ 6 3+
  33273. // v = 1h 8+ 3+
  33274. // v = 0h
  33275. // u = 0 1 2 3 4 5 6 *a
  33276. // Face layout on texture UV mapping
  33277. // ============
  33278. // \ 4 /\ 16 / ======
  33279. // \ / \ / /\ 11 /
  33280. // \/ 7 \/ / \ /
  33281. // ======= / 10 \/
  33282. // /\ 17 /\ =======
  33283. // / \ / \ \ 15 /\
  33284. // / 8 \/ 12 \ \ / \
  33285. // ============ \/ 6 \
  33286. // \ 18 /\ ============
  33287. // \ / \ \ 5 /\ 0 /
  33288. // \/ 13 \ \ / \ /
  33289. // ======= \/ 1 \/
  33290. // =============
  33291. // /\ 19 /\ 2 /\
  33292. // / \ / \ / \
  33293. // / 14 \/ 9 \/ 3 \
  33294. // ===================
  33295. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  33296. var ustep = 138 / 1024;
  33297. var vstep = 239 / 1024;
  33298. var uoffset = 60 / 1024;
  33299. var voffset = 26 / 1024;
  33300. // Second island should have margin, not to touch the first island
  33301. // avoid any borderline artefact in pixel rounding
  33302. var island_u_offset = -40 / 1024;
  33303. var island_v_offset = +20 / 1024;
  33304. // face is either island 0 or 1 :
  33305. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  33306. var island = [
  33307. 0, 0, 0, 0, 1,
  33308. 0, 0, 1, 1, 0,
  33309. 0, 0, 1, 1, 0,
  33310. 0, 1, 1, 1, 0 // 15 - 19
  33311. ];
  33312. var indices = new Array();
  33313. var positions = new Array();
  33314. var normals = new Array();
  33315. var uvs = new Array();
  33316. var current_indice = 0;
  33317. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  33318. var face_vertex_pos = new Array(3);
  33319. var face_vertex_uv = new Array(3);
  33320. var v012;
  33321. for (v012 = 0; v012 < 3; v012++) {
  33322. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  33323. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  33324. }
  33325. // create all with normals
  33326. for (var face = 0; face < 20; face++) {
  33327. // 3 vertex per face
  33328. for (v012 = 0; v012 < 3; v012++) {
  33329. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  33330. var v_id = ico_indices[3 * face + v012];
  33331. // vertex have 3D position (x,y,z)
  33332. 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]);
  33333. // Normalize to get normal, then scale to radius
  33334. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  33335. // uv Coordinates from vertex ID
  33336. 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);
  33337. }
  33338. // Subdivide the face (interpolate pos, norm, uv)
  33339. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  33340. // - norm is linear interpolation of vertex corner normal
  33341. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  33342. // - uv is linear interpolation
  33343. //
  33344. // Topology is as below for sub-divide by 2
  33345. // vertex shown as v0,v1,v2
  33346. // interp index is i1 to progress in range [v0,v1[
  33347. // interp index is i2 to progress in range [v0,v2[
  33348. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  33349. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  33350. //
  33351. //
  33352. // i2 v2
  33353. // ^ ^
  33354. // / / \
  33355. // / / \
  33356. // / / \
  33357. // / / (0,1) \
  33358. // / #---------\
  33359. // / / \ (0,0)'/ \
  33360. // / / \ / \
  33361. // / / \ / \
  33362. // / / (0,0) \ / (1,0) \
  33363. // / #---------#---------\
  33364. // v0 v1
  33365. //
  33366. // --------------------> i1
  33367. //
  33368. // interp of (i1,i2):
  33369. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  33370. // along i1 : lerp(x0,x1, i1/(S-i2))
  33371. //
  33372. // centroid of triangle is needed to get help normal computation
  33373. // (c1,c2) are used for centroid location
  33374. var interp_vertex = function (i1, i2, c1, c2) {
  33375. // vertex is interpolated from
  33376. // - face_vertex_pos[0..2]
  33377. // - face_vertex_uv[0..2]
  33378. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  33379. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  33380. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  33381. pos_interp.normalize();
  33382. var vertex_normal;
  33383. if (flat) {
  33384. // in flat mode, recalculate normal as face centroid normal
  33385. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  33386. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  33387. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  33388. }
  33389. else {
  33390. // in smooth mode, recalculate normal from each single vertex position
  33391. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  33392. }
  33393. // Vertex normal need correction due to X,Y,Z radius scaling
  33394. vertex_normal.x /= radiusX;
  33395. vertex_normal.y /= radiusY;
  33396. vertex_normal.z /= radiusZ;
  33397. vertex_normal.normalize();
  33398. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  33399. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  33400. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  33401. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  33402. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  33403. uvs.push(uv_interp.x, uv_interp.y);
  33404. // push each vertex has member of a face
  33405. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  33406. indices.push(current_indice);
  33407. current_indice++;
  33408. };
  33409. for (var i2 = 0; i2 < subdivisions; i2++) {
  33410. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  33411. // face : (i1,i2) for /\ :
  33412. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  33413. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  33414. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  33415. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  33416. if (i1 + i2 + 1 < subdivisions) {
  33417. // face : (i1,i2)' for \/ :
  33418. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  33419. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  33420. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  33421. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  33422. }
  33423. }
  33424. }
  33425. }
  33426. // Sides
  33427. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33428. // Result
  33429. var vertexData = new VertexData();
  33430. vertexData.indices = indices;
  33431. vertexData.positions = positions;
  33432. vertexData.normals = normals;
  33433. vertexData.uvs = uvs;
  33434. return vertexData;
  33435. };
  33436. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  33437. /**
  33438. * Creates the VertexData of the Polyhedron.
  33439. */
  33440. VertexData.CreatePolyhedron = function (options) {
  33441. // provided polyhedron types :
  33442. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  33443. // 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)
  33444. var polyhedra = [];
  33445. 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]] };
  33446. 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]] };
  33447. polyhedra[2] = {
  33448. 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]],
  33449. 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]]
  33450. };
  33451. polyhedra[3] = {
  33452. 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]],
  33453. 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]]
  33454. };
  33455. polyhedra[4] = {
  33456. 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]],
  33457. 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]]
  33458. };
  33459. 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]] };
  33460. 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]] };
  33461. 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]] };
  33462. 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]] };
  33463. 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]] };
  33464. 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]] };
  33465. 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]] };
  33466. 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]] };
  33467. 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]] };
  33468. polyhedra[14] = {
  33469. 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]],
  33470. 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]]
  33471. };
  33472. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  33473. var size = options.size;
  33474. var sizeX = options.sizeX || size || 1;
  33475. var sizeY = options.sizeY || size || 1;
  33476. var sizeZ = options.sizeZ || size || 1;
  33477. var data = options.custom || polyhedra[type];
  33478. var nbfaces = data.face.length;
  33479. var faceUV = options.faceUV || new Array(nbfaces);
  33480. var faceColors = options.faceColors;
  33481. var flat = (options.flat === undefined) ? true : options.flat;
  33482. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33483. var positions = new Array();
  33484. var indices = new Array();
  33485. var normals = new Array();
  33486. var uvs = new Array();
  33487. var colors = new Array();
  33488. var index = 0;
  33489. var faceIdx = 0; // face cursor in the array "indexes"
  33490. var indexes = new Array();
  33491. var i = 0;
  33492. var f = 0;
  33493. var u, v, ang, x, y, tmp;
  33494. // default face colors and UV if undefined
  33495. if (flat) {
  33496. for (f = 0; f < nbfaces; f++) {
  33497. if (faceColors && faceColors[f] === undefined) {
  33498. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  33499. }
  33500. if (faceUV && faceUV[f] === undefined) {
  33501. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  33502. }
  33503. }
  33504. }
  33505. if (!flat) {
  33506. for (i = 0; i < data.vertex.length; i++) {
  33507. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  33508. uvs.push(0, 0);
  33509. }
  33510. for (f = 0; f < nbfaces; f++) {
  33511. for (i = 0; i < data.face[f].length - 2; i++) {
  33512. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  33513. }
  33514. }
  33515. }
  33516. else {
  33517. for (f = 0; f < nbfaces; f++) {
  33518. var fl = data.face[f].length; // number of vertices of the current face
  33519. ang = 2 * Math.PI / fl;
  33520. x = 0.5 * Math.tan(ang / 2);
  33521. y = 0.5;
  33522. // positions, uvs, colors
  33523. for (i = 0; i < fl; i++) {
  33524. // positions
  33525. 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);
  33526. indexes.push(index);
  33527. index++;
  33528. // uvs
  33529. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  33530. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  33531. uvs.push(u, v);
  33532. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  33533. y = x * Math.sin(ang) + y * Math.cos(ang);
  33534. x = tmp;
  33535. // colors
  33536. if (faceColors) {
  33537. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  33538. }
  33539. }
  33540. // indices from indexes
  33541. for (i = 0; i < fl - 2; i++) {
  33542. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  33543. }
  33544. faceIdx += fl;
  33545. }
  33546. }
  33547. VertexData.ComputeNormals(positions, indices, normals);
  33548. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33549. var vertexData = new VertexData();
  33550. vertexData.positions = positions;
  33551. vertexData.indices = indices;
  33552. vertexData.normals = normals;
  33553. vertexData.uvs = uvs;
  33554. if (faceColors && flat) {
  33555. vertexData.colors = colors;
  33556. }
  33557. return vertexData;
  33558. };
  33559. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  33560. /**
  33561. * Creates the VertexData of the Torus Knot.
  33562. */
  33563. VertexData.CreateTorusKnot = function (options) {
  33564. var indices = new Array();
  33565. var positions = new Array();
  33566. var normals = new Array();
  33567. var uvs = new Array();
  33568. var radius = options.radius || 2;
  33569. var tube = options.tube || 0.5;
  33570. var radialSegments = options.radialSegments || 32;
  33571. var tubularSegments = options.tubularSegments || 32;
  33572. var p = options.p || 2;
  33573. var q = options.q || 3;
  33574. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33575. // Helper
  33576. var getPos = function (angle) {
  33577. var cu = Math.cos(angle);
  33578. var su = Math.sin(angle);
  33579. var quOverP = q / p * angle;
  33580. var cs = Math.cos(quOverP);
  33581. var tx = radius * (2 + cs) * 0.5 * cu;
  33582. var ty = radius * (2 + cs) * su * 0.5;
  33583. var tz = radius * Math.sin(quOverP) * 0.5;
  33584. return new BABYLON.Vector3(tx, ty, tz);
  33585. };
  33586. // Vertices
  33587. var i;
  33588. var j;
  33589. for (i = 0; i <= radialSegments; i++) {
  33590. var modI = i % radialSegments;
  33591. var u = modI / radialSegments * 2 * p * Math.PI;
  33592. var p1 = getPos(u);
  33593. var p2 = getPos(u + 0.01);
  33594. var tang = p2.subtract(p1);
  33595. var n = p2.add(p1);
  33596. var bitan = BABYLON.Vector3.Cross(tang, n);
  33597. n = BABYLON.Vector3.Cross(bitan, tang);
  33598. bitan.normalize();
  33599. n.normalize();
  33600. for (j = 0; j < tubularSegments; j++) {
  33601. var modJ = j % tubularSegments;
  33602. var v = modJ / tubularSegments * 2 * Math.PI;
  33603. var cx = -tube * Math.cos(v);
  33604. var cy = tube * Math.sin(v);
  33605. positions.push(p1.x + cx * n.x + cy * bitan.x);
  33606. positions.push(p1.y + cx * n.y + cy * bitan.y);
  33607. positions.push(p1.z + cx * n.z + cy * bitan.z);
  33608. uvs.push(i / radialSegments);
  33609. uvs.push(j / tubularSegments);
  33610. }
  33611. }
  33612. for (i = 0; i < radialSegments; i++) {
  33613. for (j = 0; j < tubularSegments; j++) {
  33614. var jNext = (j + 1) % tubularSegments;
  33615. var a = i * tubularSegments + j;
  33616. var b = (i + 1) * tubularSegments + j;
  33617. var c = (i + 1) * tubularSegments + jNext;
  33618. var d = i * tubularSegments + jNext;
  33619. indices.push(d);
  33620. indices.push(b);
  33621. indices.push(a);
  33622. indices.push(d);
  33623. indices.push(c);
  33624. indices.push(b);
  33625. }
  33626. }
  33627. // Normals
  33628. VertexData.ComputeNormals(positions, indices, normals);
  33629. // Sides
  33630. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33631. // Result
  33632. var vertexData = new VertexData();
  33633. vertexData.indices = indices;
  33634. vertexData.positions = positions;
  33635. vertexData.normals = normals;
  33636. vertexData.uvs = uvs;
  33637. return vertexData;
  33638. };
  33639. // Tools
  33640. /**
  33641. * @param {any} - positions (number[] or Float32Array)
  33642. * @param {any} - indices (number[] or Uint16Array)
  33643. * @param {any} - normals (number[] or Float32Array)
  33644. * options (optional) :
  33645. * facetPositions : optional array of facet positions (vector3)
  33646. * facetNormals : optional array of facet normals (vector3)
  33647. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  33648. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  33649. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  33650. * bbSize : optional bounding box size data, required for facetPartitioning computation
  33651. * bInfo : optional bounding info, required for facetPartitioning computation
  33652. * useRightHandedSystem: optional boolean to for right handed system computation
  33653. * depthSort : optional boolean to enable the facet depth sort computation
  33654. * distanceTo : optional Vector3 to compute the facet depth from this location
  33655. * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  33656. */
  33657. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  33658. // temporary scalar variables
  33659. var index = 0; // facet index
  33660. var p1p2x = 0.0; // p1p2 vector x coordinate
  33661. var p1p2y = 0.0; // p1p2 vector y coordinate
  33662. var p1p2z = 0.0; // p1p2 vector z coordinate
  33663. var p3p2x = 0.0; // p3p2 vector x coordinate
  33664. var p3p2y = 0.0; // p3p2 vector y coordinate
  33665. var p3p2z = 0.0; // p3p2 vector z coordinate
  33666. var faceNormalx = 0.0; // facet normal x coordinate
  33667. var faceNormaly = 0.0; // facet normal y coordinate
  33668. var faceNormalz = 0.0; // facet normal z coordinate
  33669. var length = 0.0; // facet normal length before normalization
  33670. var v1x = 0; // vector1 x index in the positions array
  33671. var v1y = 0; // vector1 y index in the positions array
  33672. var v1z = 0; // vector1 z index in the positions array
  33673. var v2x = 0; // vector2 x index in the positions array
  33674. var v2y = 0; // vector2 y index in the positions array
  33675. var v2z = 0; // vector2 z index in the positions array
  33676. var v3x = 0; // vector3 x index in the positions array
  33677. var v3y = 0; // vector3 y index in the positions array
  33678. var v3z = 0; // vector3 z index in the positions array
  33679. var computeFacetNormals = false;
  33680. var computeFacetPositions = false;
  33681. var computeFacetPartitioning = false;
  33682. var computeDepthSort = false;
  33683. var faceNormalSign = 1;
  33684. var ratio = 0;
  33685. var distanceTo = null;
  33686. if (options) {
  33687. computeFacetNormals = (options.facetNormals) ? true : false;
  33688. computeFacetPositions = (options.facetPositions) ? true : false;
  33689. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  33690. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  33691. ratio = options.ratio || 0;
  33692. computeDepthSort = (options.depthSort) ? true : false;
  33693. distanceTo = (options.distanceTo);
  33694. if (computeDepthSort) {
  33695. if (distanceTo === undefined) {
  33696. distanceTo = BABYLON.Vector3.Zero();
  33697. }
  33698. var depthSortedFacets = options.depthSortedFacets;
  33699. }
  33700. }
  33701. // facetPartitioning reinit if needed
  33702. var xSubRatio = 0;
  33703. var ySubRatio = 0;
  33704. var zSubRatio = 0;
  33705. var subSq = 0;
  33706. if (computeFacetPartitioning && options && options.bbSize) {
  33707. var ox = 0; // X partitioning index for facet position
  33708. var oy = 0; // Y partinioning index for facet position
  33709. var oz = 0; // Z partinioning index for facet position
  33710. var b1x = 0; // X partitioning index for facet v1 vertex
  33711. var b1y = 0; // Y partitioning index for facet v1 vertex
  33712. var b1z = 0; // z partitioning index for facet v1 vertex
  33713. var b2x = 0; // X partitioning index for facet v2 vertex
  33714. var b2y = 0; // Y partitioning index for facet v2 vertex
  33715. var b2z = 0; // Z partitioning index for facet v2 vertex
  33716. var b3x = 0; // X partitioning index for facet v3 vertex
  33717. var b3y = 0; // Y partitioning index for facet v3 vertex
  33718. var b3z = 0; // Z partitioning index for facet v3 vertex
  33719. var block_idx_o = 0; // facet barycenter block index
  33720. var block_idx_v1 = 0; // v1 vertex block index
  33721. var block_idx_v2 = 0; // v2 vertex block index
  33722. var block_idx_v3 = 0; // v3 vertex block index
  33723. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  33724. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  33725. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  33726. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  33727. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  33728. subSq = options.subDiv.max * options.subDiv.max;
  33729. options.facetPartitioning.length = 0;
  33730. }
  33731. // reset the normals
  33732. for (index = 0; index < positions.length; index++) {
  33733. normals[index] = 0.0;
  33734. }
  33735. // Loop : 1 indice triplet = 1 facet
  33736. var nbFaces = (indices.length / 3) | 0;
  33737. for (index = 0; index < nbFaces; index++) {
  33738. // get the indexes of the coordinates of each vertex of the facet
  33739. v1x = indices[index * 3] * 3;
  33740. v1y = v1x + 1;
  33741. v1z = v1x + 2;
  33742. v2x = indices[index * 3 + 1] * 3;
  33743. v2y = v2x + 1;
  33744. v2z = v2x + 2;
  33745. v3x = indices[index * 3 + 2] * 3;
  33746. v3y = v3x + 1;
  33747. v3z = v3x + 2;
  33748. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  33749. p1p2y = positions[v1y] - positions[v2y];
  33750. p1p2z = positions[v1z] - positions[v2z];
  33751. p3p2x = positions[v3x] - positions[v2x];
  33752. p3p2y = positions[v3y] - positions[v2y];
  33753. p3p2z = positions[v3z] - positions[v2z];
  33754. // compute the face normal with the cross product
  33755. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  33756. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  33757. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  33758. // normalize this normal and store it in the array facetData
  33759. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  33760. length = (length === 0) ? 1.0 : length;
  33761. faceNormalx /= length;
  33762. faceNormaly /= length;
  33763. faceNormalz /= length;
  33764. if (computeFacetNormals && options) {
  33765. options.facetNormals[index].x = faceNormalx;
  33766. options.facetNormals[index].y = faceNormaly;
  33767. options.facetNormals[index].z = faceNormalz;
  33768. }
  33769. if (computeFacetPositions && options) {
  33770. // compute and the facet barycenter coordinates in the array facetPositions
  33771. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  33772. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  33773. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  33774. }
  33775. if (computeFacetPartitioning && options) {
  33776. // store the facet indexes in arrays in the main facetPartitioning array :
  33777. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  33778. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  33779. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  33780. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  33781. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  33782. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  33783. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  33784. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  33785. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  33786. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  33787. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  33788. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  33789. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  33790. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  33791. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  33792. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  33793. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  33794. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  33795. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  33796. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  33797. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  33798. // push each facet index in each block containing the vertex
  33799. options.facetPartitioning[block_idx_v1].push(index);
  33800. if (block_idx_v2 != block_idx_v1) {
  33801. options.facetPartitioning[block_idx_v2].push(index);
  33802. }
  33803. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  33804. options.facetPartitioning[block_idx_v3].push(index);
  33805. }
  33806. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  33807. options.facetPartitioning[block_idx_o].push(index);
  33808. }
  33809. }
  33810. if (computeDepthSort && options && options.facetPositions) {
  33811. var dsf = depthSortedFacets[index];
  33812. dsf.ind = index * 3;
  33813. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  33814. }
  33815. // compute the normals anyway
  33816. normals[v1x] += faceNormalx; // accumulate all the normals per face
  33817. normals[v1y] += faceNormaly;
  33818. normals[v1z] += faceNormalz;
  33819. normals[v2x] += faceNormalx;
  33820. normals[v2y] += faceNormaly;
  33821. normals[v2z] += faceNormalz;
  33822. normals[v3x] += faceNormalx;
  33823. normals[v3y] += faceNormaly;
  33824. normals[v3z] += faceNormalz;
  33825. }
  33826. // last normalization of each normal
  33827. for (index = 0; index < normals.length / 3; index++) {
  33828. faceNormalx = normals[index * 3];
  33829. faceNormaly = normals[index * 3 + 1];
  33830. faceNormalz = normals[index * 3 + 2];
  33831. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  33832. length = (length === 0) ? 1.0 : length;
  33833. faceNormalx /= length;
  33834. faceNormaly /= length;
  33835. faceNormalz /= length;
  33836. normals[index * 3] = faceNormalx;
  33837. normals[index * 3 + 1] = faceNormaly;
  33838. normals[index * 3 + 2] = faceNormalz;
  33839. }
  33840. };
  33841. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  33842. var li = indices.length;
  33843. var ln = normals.length;
  33844. var i;
  33845. var n;
  33846. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33847. switch (sideOrientation) {
  33848. case BABYLON.Mesh.FRONTSIDE:
  33849. // nothing changed
  33850. break;
  33851. case BABYLON.Mesh.BACKSIDE:
  33852. var tmp;
  33853. // indices
  33854. for (i = 0; i < li; i += 3) {
  33855. tmp = indices[i];
  33856. indices[i] = indices[i + 2];
  33857. indices[i + 2] = tmp;
  33858. }
  33859. // normals
  33860. for (n = 0; n < ln; n++) {
  33861. normals[n] = -normals[n];
  33862. }
  33863. break;
  33864. case BABYLON.Mesh.DOUBLESIDE:
  33865. // positions
  33866. var lp = positions.length;
  33867. var l = lp / 3;
  33868. for (var p = 0; p < lp; p++) {
  33869. positions[lp + p] = positions[p];
  33870. }
  33871. // indices
  33872. for (i = 0; i < li; i += 3) {
  33873. indices[i + li] = indices[i + 2] + l;
  33874. indices[i + 1 + li] = indices[i + 1] + l;
  33875. indices[i + 2 + li] = indices[i] + l;
  33876. }
  33877. // normals
  33878. for (n = 0; n < ln; n++) {
  33879. normals[ln + n] = -normals[n];
  33880. }
  33881. // uvs
  33882. var lu = uvs.length;
  33883. var u = 0;
  33884. for (u = 0; u < lu; u++) {
  33885. uvs[u + lu] = uvs[u];
  33886. }
  33887. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  33888. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  33889. u = 0;
  33890. for (i = 0; i < lu / 2; i++) {
  33891. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  33892. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  33893. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  33894. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  33895. u += 2;
  33896. }
  33897. break;
  33898. }
  33899. };
  33900. /**
  33901. * Creates a new VertexData from the imported parameters.
  33902. */
  33903. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  33904. var vertexData = new VertexData();
  33905. // positions
  33906. var positions = parsedVertexData.positions;
  33907. if (positions) {
  33908. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  33909. }
  33910. // normals
  33911. var normals = parsedVertexData.normals;
  33912. if (normals) {
  33913. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  33914. }
  33915. // tangents
  33916. var tangents = parsedVertexData.tangents;
  33917. if (tangents) {
  33918. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  33919. }
  33920. // uvs
  33921. var uvs = parsedVertexData.uvs;
  33922. if (uvs) {
  33923. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  33924. }
  33925. // uv2s
  33926. var uv2s = parsedVertexData.uv2s;
  33927. if (uv2s) {
  33928. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  33929. }
  33930. // uv3s
  33931. var uv3s = parsedVertexData.uv3s;
  33932. if (uv3s) {
  33933. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  33934. }
  33935. // uv4s
  33936. var uv4s = parsedVertexData.uv4s;
  33937. if (uv4s) {
  33938. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  33939. }
  33940. // uv5s
  33941. var uv5s = parsedVertexData.uv5s;
  33942. if (uv5s) {
  33943. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  33944. }
  33945. // uv6s
  33946. var uv6s = parsedVertexData.uv6s;
  33947. if (uv6s) {
  33948. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  33949. }
  33950. // colors
  33951. var colors = parsedVertexData.colors;
  33952. if (colors) {
  33953. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  33954. }
  33955. // matricesIndices
  33956. var matricesIndices = parsedVertexData.matricesIndices;
  33957. if (matricesIndices) {
  33958. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  33959. }
  33960. // matricesWeights
  33961. var matricesWeights = parsedVertexData.matricesWeights;
  33962. if (matricesWeights) {
  33963. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  33964. }
  33965. // indices
  33966. var indices = parsedVertexData.indices;
  33967. if (indices) {
  33968. vertexData.indices = indices;
  33969. }
  33970. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  33971. };
  33972. return VertexData;
  33973. }());
  33974. BABYLON.VertexData = VertexData;
  33975. })(BABYLON || (BABYLON = {}));
  33976. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  33977. var BABYLON;
  33978. (function (BABYLON) {
  33979. /**
  33980. * Class used to store geometry data (vertex buffers + index buffer)
  33981. */
  33982. var Geometry = /** @class */ (function () {
  33983. /**
  33984. * Creates a new geometry
  33985. * @param id defines the unique ID
  33986. * @param scene defines the hosting scene
  33987. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  33988. * @param updatable defines if geometry must be updatable (false by default)
  33989. * @param mesh defines the mesh that will be associated with the geometry
  33990. */
  33991. function Geometry(id, scene, vertexData, updatable, mesh) {
  33992. if (updatable === void 0) { updatable = false; }
  33993. if (mesh === void 0) { mesh = null; }
  33994. /**
  33995. * Gets the delay loading state of the geometry (none by default which means not delayed)
  33996. */
  33997. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  33998. this._totalVertices = 0;
  33999. this._isDisposed = false;
  34000. this._indexBufferIsUpdatable = false;
  34001. this.id = id;
  34002. this._engine = scene.getEngine();
  34003. this._meshes = [];
  34004. this._scene = scene;
  34005. //Init vertex buffer cache
  34006. this._vertexBuffers = {};
  34007. this._indices = [];
  34008. this._updatable = updatable;
  34009. // vertexData
  34010. if (vertexData) {
  34011. this.setAllVerticesData(vertexData, updatable);
  34012. }
  34013. else {
  34014. this._totalVertices = 0;
  34015. this._indices = [];
  34016. }
  34017. if (this._engine.getCaps().vertexArrayObject) {
  34018. this._vertexArrayObjects = {};
  34019. }
  34020. // applyToMesh
  34021. if (mesh) {
  34022. if (mesh.getClassName() === "LinesMesh") {
  34023. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  34024. this.updateExtend();
  34025. }
  34026. this.applyToMesh(mesh);
  34027. mesh.computeWorldMatrix(true);
  34028. }
  34029. }
  34030. Object.defineProperty(Geometry.prototype, "boundingBias", {
  34031. /**
  34032. * 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
  34033. */
  34034. get: function () {
  34035. return this._boundingBias;
  34036. },
  34037. /**
  34038. * 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
  34039. */
  34040. set: function (value) {
  34041. if (this._boundingBias && this._boundingBias.equals(value)) {
  34042. return;
  34043. }
  34044. this._boundingBias = value.clone();
  34045. this.updateBoundingInfo(true, null);
  34046. },
  34047. enumerable: true,
  34048. configurable: true
  34049. });
  34050. /**
  34051. * Static function used to attach a new empty geometry to a mesh
  34052. * @param mesh defines the mesh to attach the geometry to
  34053. * @returns the new {BABYLON.Geometry}
  34054. */
  34055. Geometry.CreateGeometryForMesh = function (mesh) {
  34056. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  34057. geometry.applyToMesh(mesh);
  34058. return geometry;
  34059. };
  34060. Object.defineProperty(Geometry.prototype, "extend", {
  34061. /**
  34062. * Gets the current extend of the geometry
  34063. */
  34064. get: function () {
  34065. return this._extend;
  34066. },
  34067. enumerable: true,
  34068. configurable: true
  34069. });
  34070. /**
  34071. * Gets the hosting scene
  34072. * @returns the hosting {BABYLON.Scene}
  34073. */
  34074. Geometry.prototype.getScene = function () {
  34075. return this._scene;
  34076. };
  34077. /**
  34078. * Gets the hosting engine
  34079. * @returns the hosting {BABYLON.Engine}
  34080. */
  34081. Geometry.prototype.getEngine = function () {
  34082. return this._engine;
  34083. };
  34084. /**
  34085. * Defines if the geometry is ready to use
  34086. * @returns true if the geometry is ready to be used
  34087. */
  34088. Geometry.prototype.isReady = function () {
  34089. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  34090. };
  34091. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  34092. /**
  34093. * Gets a value indicating that the geometry should not be serialized
  34094. */
  34095. get: function () {
  34096. for (var index = 0; index < this._meshes.length; index++) {
  34097. if (!this._meshes[index].doNotSerialize) {
  34098. return false;
  34099. }
  34100. }
  34101. return true;
  34102. },
  34103. enumerable: true,
  34104. configurable: true
  34105. });
  34106. /** @ignore */
  34107. Geometry.prototype._rebuild = function () {
  34108. if (this._vertexArrayObjects) {
  34109. this._vertexArrayObjects = {};
  34110. }
  34111. // Index buffer
  34112. if (this._meshes.length !== 0 && this._indices) {
  34113. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  34114. }
  34115. // Vertex buffers
  34116. for (var key in this._vertexBuffers) {
  34117. var vertexBuffer = this._vertexBuffers[key];
  34118. vertexBuffer._rebuild();
  34119. }
  34120. };
  34121. /**
  34122. * Affects all gemetry data in one call
  34123. * @param vertexData defines the geometry data
  34124. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  34125. */
  34126. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  34127. vertexData.applyToGeometry(this, updatable);
  34128. this.notifyUpdate();
  34129. };
  34130. /**
  34131. * Set specific vertex data
  34132. * @param kind defines the data kind (Position, normal, etc...)
  34133. * @param data defines the vertex data to use
  34134. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  34135. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  34136. */
  34137. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  34138. if (updatable === void 0) { updatable = false; }
  34139. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  34140. this.setVerticesBuffer(buffer);
  34141. };
  34142. /**
  34143. * Removes a specific vertex data
  34144. * @param kind defines the data kind (Position, normal, etc...)
  34145. */
  34146. Geometry.prototype.removeVerticesData = function (kind) {
  34147. if (this._vertexBuffers[kind]) {
  34148. this._vertexBuffers[kind].dispose();
  34149. delete this._vertexBuffers[kind];
  34150. }
  34151. };
  34152. /**
  34153. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  34154. * @param buffer defines the vertex buffer to use
  34155. */
  34156. Geometry.prototype.setVerticesBuffer = function (buffer) {
  34157. var kind = buffer.getKind();
  34158. if (this._vertexBuffers[kind]) {
  34159. this._vertexBuffers[kind].dispose();
  34160. }
  34161. this._vertexBuffers[kind] = buffer;
  34162. if (kind === BABYLON.VertexBuffer.PositionKind) {
  34163. var data = buffer.getData();
  34164. var stride = buffer.getStrideSize();
  34165. this._totalVertices = data.length / stride;
  34166. this.updateExtend(data, stride);
  34167. this._resetPointsArrayCache();
  34168. var meshes = this._meshes;
  34169. var numOfMeshes = meshes.length;
  34170. for (var index = 0; index < numOfMeshes; index++) {
  34171. var mesh = meshes[index];
  34172. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  34173. mesh._createGlobalSubMesh(false);
  34174. mesh.computeWorldMatrix(true);
  34175. }
  34176. }
  34177. this.notifyUpdate(kind);
  34178. if (this._vertexArrayObjects) {
  34179. this._disposeVertexArrayObjects();
  34180. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  34181. }
  34182. };
  34183. /**
  34184. * Update a specific vertex buffer
  34185. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  34186. * It will do nothing if the buffer is not updatable
  34187. * @param kind defines the data kind (Position, normal, etc...)
  34188. * @param data defines the data to use
  34189. * @param offset defines the offset in the target buffer where to store the data
  34190. */
  34191. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  34192. var vertexBuffer = this.getVertexBuffer(kind);
  34193. if (!vertexBuffer) {
  34194. return;
  34195. }
  34196. vertexBuffer.updateDirectly(data, offset);
  34197. this.notifyUpdate(kind);
  34198. };
  34199. /**
  34200. * Update a specific vertex buffer
  34201. * This function will create a new buffer if the current one is not updatable
  34202. * @param kind defines the data kind (Position, normal, etc...)
  34203. * @param data defines the data to use
  34204. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  34205. */
  34206. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  34207. if (updateExtends === void 0) { updateExtends = false; }
  34208. var vertexBuffer = this.getVertexBuffer(kind);
  34209. if (!vertexBuffer) {
  34210. return;
  34211. }
  34212. vertexBuffer.update(data);
  34213. if (kind === BABYLON.VertexBuffer.PositionKind) {
  34214. var stride = vertexBuffer.getStrideSize();
  34215. this._totalVertices = data.length / stride;
  34216. this.updateBoundingInfo(updateExtends, data);
  34217. }
  34218. this.notifyUpdate(kind);
  34219. };
  34220. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  34221. if (updateExtends) {
  34222. this.updateExtend(data);
  34223. }
  34224. var meshes = this._meshes;
  34225. var numOfMeshes = meshes.length;
  34226. this._resetPointsArrayCache();
  34227. for (var index = 0; index < numOfMeshes; index++) {
  34228. var mesh = meshes[index];
  34229. if (updateExtends) {
  34230. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  34231. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  34232. var subMesh = mesh.subMeshes[subIndex];
  34233. subMesh.refreshBoundingInfo();
  34234. }
  34235. }
  34236. }
  34237. };
  34238. /** @ignore */
  34239. Geometry.prototype._bind = function (effect, indexToBind) {
  34240. if (!effect) {
  34241. return;
  34242. }
  34243. if (indexToBind === undefined) {
  34244. indexToBind = this._indexBuffer;
  34245. }
  34246. var vbs = this.getVertexBuffers();
  34247. if (!vbs) {
  34248. return;
  34249. }
  34250. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  34251. this._engine.bindBuffers(vbs, indexToBind, effect);
  34252. return;
  34253. }
  34254. // Using VAO
  34255. if (!this._vertexArrayObjects[effect.key]) {
  34256. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  34257. }
  34258. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  34259. };
  34260. /**
  34261. * Gets total number of vertices
  34262. * @returns the total number of vertices
  34263. */
  34264. Geometry.prototype.getTotalVertices = function () {
  34265. if (!this.isReady()) {
  34266. return 0;
  34267. }
  34268. return this._totalVertices;
  34269. };
  34270. /**
  34271. * Gets a specific vertex data attached to this geometry
  34272. * @param kind defines the data kind (Position, normal, etc...)
  34273. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  34274. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  34275. * @returns a float array containing vertex data
  34276. */
  34277. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  34278. var vertexBuffer = this.getVertexBuffer(kind);
  34279. if (!vertexBuffer) {
  34280. return null;
  34281. }
  34282. var orig = vertexBuffer.getData();
  34283. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  34284. return orig;
  34285. }
  34286. else {
  34287. var len = orig.length;
  34288. var copy = [];
  34289. for (var i = 0; i < len; i++) {
  34290. copy.push(orig[i]);
  34291. }
  34292. return copy;
  34293. }
  34294. };
  34295. /**
  34296. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  34297. * @param kind defines the data kind (Position, normal, etc...)
  34298. * @returns true if the vertex buffer with the specified kind is updatable
  34299. */
  34300. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  34301. var vb = this._vertexBuffers[kind];
  34302. if (!vb) {
  34303. return false;
  34304. }
  34305. return vb.isUpdatable();
  34306. };
  34307. /**
  34308. * Gets a specific vertex buffer
  34309. * @param kind defines the data kind (Position, normal, etc...)
  34310. * @returns a {BABYLON.VertexBuffer}
  34311. */
  34312. Geometry.prototype.getVertexBuffer = function (kind) {
  34313. if (!this.isReady()) {
  34314. return null;
  34315. }
  34316. return this._vertexBuffers[kind];
  34317. };
  34318. /**
  34319. * Returns all vertex buffers
  34320. * @return an object holding all vertex buffers indexed by kind
  34321. */
  34322. Geometry.prototype.getVertexBuffers = function () {
  34323. if (!this.isReady()) {
  34324. return null;
  34325. }
  34326. return this._vertexBuffers;
  34327. };
  34328. /**
  34329. * Gets a boolean indicating if specific vertex buffer is present
  34330. * @param kind defines the data kind (Position, normal, etc...)
  34331. * @returns true if data is present
  34332. */
  34333. Geometry.prototype.isVerticesDataPresent = function (kind) {
  34334. if (!this._vertexBuffers) {
  34335. if (this._delayInfo) {
  34336. return this._delayInfo.indexOf(kind) !== -1;
  34337. }
  34338. return false;
  34339. }
  34340. return this._vertexBuffers[kind] !== undefined;
  34341. };
  34342. /**
  34343. * Gets a list of all attached data kinds (Position, normal, etc...)
  34344. * @returns a list of string containing all kinds
  34345. */
  34346. Geometry.prototype.getVerticesDataKinds = function () {
  34347. var result = [];
  34348. var kind;
  34349. if (!this._vertexBuffers && this._delayInfo) {
  34350. for (kind in this._delayInfo) {
  34351. result.push(kind);
  34352. }
  34353. }
  34354. else {
  34355. for (kind in this._vertexBuffers) {
  34356. result.push(kind);
  34357. }
  34358. }
  34359. return result;
  34360. };
  34361. /**
  34362. * Update index buffer
  34363. * @param indices defines the indices to store in the index buffer
  34364. * @param offset defines the offset in the target buffer where to store the data
  34365. */
  34366. Geometry.prototype.updateIndices = function (indices, offset) {
  34367. if (!this._indexBuffer) {
  34368. return;
  34369. }
  34370. if (!this._indexBufferIsUpdatable) {
  34371. this.setIndices(indices, null, true);
  34372. }
  34373. else {
  34374. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  34375. }
  34376. };
  34377. /**
  34378. * Creates a new index buffer
  34379. * @param indices defines the indices to store in the index buffer
  34380. * @param totalVertices defines the total number of vertices (could be null)
  34381. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  34382. */
  34383. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  34384. if (totalVertices === void 0) { totalVertices = null; }
  34385. if (updatable === void 0) { updatable = false; }
  34386. if (this._indexBuffer) {
  34387. this._engine._releaseBuffer(this._indexBuffer);
  34388. }
  34389. this._disposeVertexArrayObjects();
  34390. this._indices = indices;
  34391. this._indexBufferIsUpdatable = updatable;
  34392. if (this._meshes.length !== 0 && this._indices) {
  34393. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  34394. }
  34395. if (totalVertices != undefined) {
  34396. this._totalVertices = totalVertices;
  34397. }
  34398. var meshes = this._meshes;
  34399. var numOfMeshes = meshes.length;
  34400. for (var index = 0; index < numOfMeshes; index++) {
  34401. meshes[index]._createGlobalSubMesh(true);
  34402. }
  34403. this.notifyUpdate();
  34404. };
  34405. /**
  34406. * Return the total number of indices
  34407. * @returns the total number of indices
  34408. */
  34409. Geometry.prototype.getTotalIndices = function () {
  34410. if (!this.isReady()) {
  34411. return 0;
  34412. }
  34413. return this._indices.length;
  34414. };
  34415. /**
  34416. * Gets the index buffer array
  34417. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  34418. * @returns the index buffer array
  34419. */
  34420. Geometry.prototype.getIndices = function (copyWhenShared) {
  34421. if (!this.isReady()) {
  34422. return null;
  34423. }
  34424. var orig = this._indices;
  34425. if (!copyWhenShared || this._meshes.length === 1) {
  34426. return orig;
  34427. }
  34428. else {
  34429. var len = orig.length;
  34430. var copy = [];
  34431. for (var i = 0; i < len; i++) {
  34432. copy.push(orig[i]);
  34433. }
  34434. return copy;
  34435. }
  34436. };
  34437. /**
  34438. * Gets the index buffer
  34439. * @return the index buffer
  34440. */
  34441. Geometry.prototype.getIndexBuffer = function () {
  34442. if (!this.isReady()) {
  34443. return null;
  34444. }
  34445. return this._indexBuffer;
  34446. };
  34447. /** @ignore */
  34448. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  34449. if (effect === void 0) { effect = null; }
  34450. if (!effect || !this._vertexArrayObjects) {
  34451. return;
  34452. }
  34453. if (this._vertexArrayObjects[effect.key]) {
  34454. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  34455. delete this._vertexArrayObjects[effect.key];
  34456. }
  34457. };
  34458. /**
  34459. * Release the associated resources for a specific mesh
  34460. * @param mesh defines the source mesh
  34461. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  34462. */
  34463. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  34464. var meshes = this._meshes;
  34465. var index = meshes.indexOf(mesh);
  34466. if (index === -1) {
  34467. return;
  34468. }
  34469. meshes.splice(index, 1);
  34470. mesh._geometry = null;
  34471. if (meshes.length === 0 && shouldDispose) {
  34472. this.dispose();
  34473. }
  34474. };
  34475. /**
  34476. * Apply current geometry to a given mesh
  34477. * @param mesh defines the mesh to apply geometry to
  34478. */
  34479. Geometry.prototype.applyToMesh = function (mesh) {
  34480. if (mesh._geometry === this) {
  34481. return;
  34482. }
  34483. var previousGeometry = mesh._geometry;
  34484. if (previousGeometry) {
  34485. previousGeometry.releaseForMesh(mesh);
  34486. }
  34487. var meshes = this._meshes;
  34488. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  34489. mesh._geometry = this;
  34490. this._scene.pushGeometry(this);
  34491. meshes.push(mesh);
  34492. if (this.isReady()) {
  34493. this._applyToMesh(mesh);
  34494. }
  34495. else {
  34496. mesh._boundingInfo = this._boundingInfo;
  34497. }
  34498. };
  34499. Geometry.prototype.updateExtend = function (data, stride) {
  34500. if (data === void 0) { data = null; }
  34501. if (!data) {
  34502. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  34503. }
  34504. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  34505. };
  34506. Geometry.prototype._applyToMesh = function (mesh) {
  34507. var numOfMeshes = this._meshes.length;
  34508. // vertexBuffers
  34509. for (var kind in this._vertexBuffers) {
  34510. if (numOfMeshes === 1) {
  34511. this._vertexBuffers[kind].create();
  34512. }
  34513. var buffer = this._vertexBuffers[kind].getBuffer();
  34514. if (buffer)
  34515. buffer.references = numOfMeshes;
  34516. if (kind === BABYLON.VertexBuffer.PositionKind) {
  34517. if (!this._extend) {
  34518. this.updateExtend(this._vertexBuffers[kind].getData());
  34519. }
  34520. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  34521. mesh._createGlobalSubMesh(false);
  34522. //bounding info was just created again, world matrix should be applied again.
  34523. mesh._updateBoundingInfo();
  34524. }
  34525. }
  34526. // indexBuffer
  34527. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  34528. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  34529. }
  34530. if (this._indexBuffer) {
  34531. this._indexBuffer.references = numOfMeshes;
  34532. }
  34533. };
  34534. Geometry.prototype.notifyUpdate = function (kind) {
  34535. if (this.onGeometryUpdated) {
  34536. this.onGeometryUpdated(this, kind);
  34537. }
  34538. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  34539. var mesh = _a[_i];
  34540. mesh._markSubMeshesAsAttributesDirty();
  34541. }
  34542. };
  34543. /**
  34544. * Load the geometry if it was flagged as delay loaded
  34545. * @param scene defines the hosting scene
  34546. * @param onLoaded defines a callback called when the geometry is loaded
  34547. */
  34548. Geometry.prototype.load = function (scene, onLoaded) {
  34549. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  34550. return;
  34551. }
  34552. if (this.isReady()) {
  34553. if (onLoaded) {
  34554. onLoaded();
  34555. }
  34556. return;
  34557. }
  34558. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  34559. this._queueLoad(scene, onLoaded);
  34560. };
  34561. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  34562. var _this = this;
  34563. if (!this.delayLoadingFile) {
  34564. return;
  34565. }
  34566. scene._addPendingData(this);
  34567. scene._loadFile(this.delayLoadingFile, function (data) {
  34568. if (!_this._delayLoadingFunction) {
  34569. return;
  34570. }
  34571. _this._delayLoadingFunction(JSON.parse(data), _this);
  34572. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  34573. _this._delayInfo = [];
  34574. scene._removePendingData(_this);
  34575. var meshes = _this._meshes;
  34576. var numOfMeshes = meshes.length;
  34577. for (var index = 0; index < numOfMeshes; index++) {
  34578. _this._applyToMesh(meshes[index]);
  34579. }
  34580. if (onLoaded) {
  34581. onLoaded();
  34582. }
  34583. }, undefined, true);
  34584. };
  34585. /**
  34586. * Invert the geometry to move from a right handed system to a left handed one.
  34587. */
  34588. Geometry.prototype.toLeftHanded = function () {
  34589. // Flip faces
  34590. var tIndices = this.getIndices(false);
  34591. if (tIndices != null && tIndices.length > 0) {
  34592. for (var i = 0; i < tIndices.length; i += 3) {
  34593. var tTemp = tIndices[i + 0];
  34594. tIndices[i + 0] = tIndices[i + 2];
  34595. tIndices[i + 2] = tTemp;
  34596. }
  34597. this.setIndices(tIndices);
  34598. }
  34599. // Negate position.z
  34600. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  34601. if (tPositions != null && tPositions.length > 0) {
  34602. for (var i = 0; i < tPositions.length; i += 3) {
  34603. tPositions[i + 2] = -tPositions[i + 2];
  34604. }
  34605. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  34606. }
  34607. // Negate normal.z
  34608. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  34609. if (tNormals != null && tNormals.length > 0) {
  34610. for (var i = 0; i < tNormals.length; i += 3) {
  34611. tNormals[i + 2] = -tNormals[i + 2];
  34612. }
  34613. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  34614. }
  34615. };
  34616. // Cache
  34617. /** @ignore */
  34618. Geometry.prototype._resetPointsArrayCache = function () {
  34619. this._positions = null;
  34620. };
  34621. /** @ignore */
  34622. Geometry.prototype._generatePointsArray = function () {
  34623. if (this._positions)
  34624. return true;
  34625. this._positions = [];
  34626. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34627. if (!data) {
  34628. return false;
  34629. }
  34630. for (var index = 0; index < data.length; index += 3) {
  34631. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  34632. }
  34633. return true;
  34634. };
  34635. /**
  34636. * Gets a value indicating if the geometry is disposed
  34637. * @returns true if the geometry was disposed
  34638. */
  34639. Geometry.prototype.isDisposed = function () {
  34640. return this._isDisposed;
  34641. };
  34642. Geometry.prototype._disposeVertexArrayObjects = function () {
  34643. if (this._vertexArrayObjects) {
  34644. for (var kind in this._vertexArrayObjects) {
  34645. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  34646. }
  34647. this._vertexArrayObjects = {};
  34648. }
  34649. };
  34650. /**
  34651. * Free all associated resources
  34652. */
  34653. Geometry.prototype.dispose = function () {
  34654. var meshes = this._meshes;
  34655. var numOfMeshes = meshes.length;
  34656. var index;
  34657. for (index = 0; index < numOfMeshes; index++) {
  34658. this.releaseForMesh(meshes[index]);
  34659. }
  34660. this._meshes = [];
  34661. this._disposeVertexArrayObjects();
  34662. for (var kind in this._vertexBuffers) {
  34663. this._vertexBuffers[kind].dispose();
  34664. }
  34665. this._vertexBuffers = {};
  34666. this._totalVertices = 0;
  34667. if (this._indexBuffer) {
  34668. this._engine._releaseBuffer(this._indexBuffer);
  34669. }
  34670. this._indexBuffer = null;
  34671. this._indices = [];
  34672. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  34673. this.delayLoadingFile = null;
  34674. this._delayLoadingFunction = null;
  34675. this._delayInfo = [];
  34676. this._boundingInfo = null;
  34677. this._scene.removeGeometry(this);
  34678. this._isDisposed = true;
  34679. };
  34680. /**
  34681. * Clone the current geometry into a new geometry
  34682. * @param id defines the unique ID of the new geometry
  34683. * @returns a new geometry object
  34684. */
  34685. Geometry.prototype.copy = function (id) {
  34686. var vertexData = new BABYLON.VertexData();
  34687. vertexData.indices = [];
  34688. var indices = this.getIndices();
  34689. if (indices) {
  34690. for (var index = 0; index < indices.length; index++) {
  34691. vertexData.indices.push(indices[index]);
  34692. }
  34693. }
  34694. var updatable = false;
  34695. var stopChecking = false;
  34696. var kind;
  34697. for (kind in this._vertexBuffers) {
  34698. // using slice() to make a copy of the array and not just reference it
  34699. var data = this.getVerticesData(kind);
  34700. if (data instanceof Float32Array) {
  34701. vertexData.set(new Float32Array(data), kind);
  34702. }
  34703. else {
  34704. vertexData.set(data.slice(0), kind);
  34705. }
  34706. if (!stopChecking) {
  34707. var vb = this.getVertexBuffer(kind);
  34708. if (vb) {
  34709. updatable = vb.isUpdatable();
  34710. stopChecking = !updatable;
  34711. }
  34712. }
  34713. }
  34714. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  34715. geometry.delayLoadState = this.delayLoadState;
  34716. geometry.delayLoadingFile = this.delayLoadingFile;
  34717. geometry._delayLoadingFunction = this._delayLoadingFunction;
  34718. for (kind in this._delayInfo) {
  34719. geometry._delayInfo = geometry._delayInfo || [];
  34720. geometry._delayInfo.push(kind);
  34721. }
  34722. // Bounding info
  34723. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  34724. return geometry;
  34725. };
  34726. /**
  34727. * Serialize the current geometry info (and not the vertices data) into a JSON object
  34728. * @return a JSON representation of the current geometry data (without the vertices data)
  34729. */
  34730. Geometry.prototype.serialize = function () {
  34731. var serializationObject = {};
  34732. serializationObject.id = this.id;
  34733. serializationObject.updatable = this._updatable;
  34734. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  34735. serializationObject.tags = BABYLON.Tags.GetTags(this);
  34736. }
  34737. return serializationObject;
  34738. };
  34739. Geometry.prototype.toNumberArray = function (origin) {
  34740. if (Array.isArray(origin)) {
  34741. return origin;
  34742. }
  34743. else {
  34744. return Array.prototype.slice.call(origin);
  34745. }
  34746. };
  34747. /**
  34748. * Serialize all vertices data into a JSON oject
  34749. * @returns a JSON representation of the current geometry data
  34750. */
  34751. Geometry.prototype.serializeVerticeData = function () {
  34752. var serializationObject = this.serialize();
  34753. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  34754. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  34755. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  34756. serializationObject.positions._updatable = true;
  34757. }
  34758. }
  34759. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  34760. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  34761. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  34762. serializationObject.normals._updatable = true;
  34763. }
  34764. }
  34765. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  34766. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  34767. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  34768. serializationObject.tangets._updatable = true;
  34769. }
  34770. }
  34771. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  34772. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  34773. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  34774. serializationObject.uvs._updatable = true;
  34775. }
  34776. }
  34777. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  34778. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  34779. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  34780. serializationObject.uv2s._updatable = true;
  34781. }
  34782. }
  34783. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  34784. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  34785. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  34786. serializationObject.uv3s._updatable = true;
  34787. }
  34788. }
  34789. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  34790. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  34791. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  34792. serializationObject.uv4s._updatable = true;
  34793. }
  34794. }
  34795. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  34796. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  34797. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  34798. serializationObject.uv5s._updatable = true;
  34799. }
  34800. }
  34801. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  34802. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  34803. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  34804. serializationObject.uv6s._updatable = true;
  34805. }
  34806. }
  34807. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  34808. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  34809. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  34810. serializationObject.colors._updatable = true;
  34811. }
  34812. }
  34813. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  34814. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  34815. serializationObject.matricesIndices._isExpanded = true;
  34816. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  34817. serializationObject.matricesIndices._updatable = true;
  34818. }
  34819. }
  34820. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  34821. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  34822. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  34823. serializationObject.matricesWeights._updatable = true;
  34824. }
  34825. }
  34826. serializationObject.indices = this.toNumberArray(this.getIndices());
  34827. return serializationObject;
  34828. };
  34829. // Statics
  34830. /**
  34831. * Extracts a clone of a mesh geometry
  34832. * @param mesh defines the source mesh
  34833. * @param id defines the unique ID of the new geometry object
  34834. * @returns the new geometry object
  34835. */
  34836. Geometry.ExtractFromMesh = function (mesh, id) {
  34837. var geometry = mesh._geometry;
  34838. if (!geometry) {
  34839. return null;
  34840. }
  34841. return geometry.copy(id);
  34842. };
  34843. /**
  34844. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  34845. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  34846. * Be aware Math.random() could cause collisions, but:
  34847. * "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"
  34848. * @returns a string containing a new GUID
  34849. */
  34850. Geometry.RandomId = function () {
  34851. return BABYLON.Tools.RandomId();
  34852. };
  34853. /** @ignore */
  34854. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  34855. var scene = mesh.getScene();
  34856. // Geometry
  34857. var geometryId = parsedGeometry.geometryId;
  34858. if (geometryId) {
  34859. var geometry = scene.getGeometryByID(geometryId);
  34860. if (geometry) {
  34861. geometry.applyToMesh(mesh);
  34862. }
  34863. }
  34864. else if (parsedGeometry instanceof ArrayBuffer) {
  34865. var binaryInfo = mesh._binaryInfo;
  34866. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  34867. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  34868. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  34869. }
  34870. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  34871. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  34872. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  34873. }
  34874. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  34875. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  34876. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  34877. }
  34878. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  34879. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  34880. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  34881. }
  34882. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  34883. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  34884. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  34885. }
  34886. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  34887. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  34888. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  34889. }
  34890. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  34891. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  34892. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  34893. }
  34894. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  34895. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  34896. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  34897. }
  34898. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  34899. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  34900. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  34901. }
  34902. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  34903. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  34904. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  34905. }
  34906. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  34907. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  34908. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  34909. }
  34910. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  34911. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  34912. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  34913. }
  34914. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  34915. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  34916. mesh.setIndices(indicesData, null);
  34917. }
  34918. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  34919. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  34920. mesh.subMeshes = [];
  34921. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  34922. var materialIndex = subMeshesData[(i * 5) + 0];
  34923. var verticesStart = subMeshesData[(i * 5) + 1];
  34924. var verticesCount = subMeshesData[(i * 5) + 2];
  34925. var indexStart = subMeshesData[(i * 5) + 3];
  34926. var indexCount = subMeshesData[(i * 5) + 4];
  34927. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  34928. }
  34929. }
  34930. }
  34931. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  34932. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  34933. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  34934. if (parsedGeometry.tangents) {
  34935. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  34936. }
  34937. if (parsedGeometry.uvs) {
  34938. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  34939. }
  34940. if (parsedGeometry.uvs2) {
  34941. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  34942. }
  34943. if (parsedGeometry.uvs3) {
  34944. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  34945. }
  34946. if (parsedGeometry.uvs4) {
  34947. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  34948. }
  34949. if (parsedGeometry.uvs5) {
  34950. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  34951. }
  34952. if (parsedGeometry.uvs6) {
  34953. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  34954. }
  34955. if (parsedGeometry.colors) {
  34956. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  34957. }
  34958. if (parsedGeometry.matricesIndices) {
  34959. if (!parsedGeometry.matricesIndices._isExpanded) {
  34960. var floatIndices = [];
  34961. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  34962. var matricesIndex = parsedGeometry.matricesIndices[i];
  34963. floatIndices.push(matricesIndex & 0x000000FF);
  34964. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  34965. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  34966. floatIndices.push(matricesIndex >> 24);
  34967. }
  34968. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  34969. }
  34970. else {
  34971. delete parsedGeometry.matricesIndices._isExpanded;
  34972. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  34973. }
  34974. }
  34975. if (parsedGeometry.matricesIndicesExtra) {
  34976. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  34977. var floatIndices = [];
  34978. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  34979. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  34980. floatIndices.push(matricesIndex & 0x000000FF);
  34981. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  34982. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  34983. floatIndices.push(matricesIndex >> 24);
  34984. }
  34985. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  34986. }
  34987. else {
  34988. delete parsedGeometry.matricesIndices._isExpanded;
  34989. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  34990. }
  34991. }
  34992. if (parsedGeometry.matricesWeights) {
  34993. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  34994. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  34995. }
  34996. if (parsedGeometry.matricesWeightsExtra) {
  34997. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  34998. }
  34999. mesh.setIndices(parsedGeometry.indices, null);
  35000. }
  35001. // SubMeshes
  35002. if (parsedGeometry.subMeshes) {
  35003. mesh.subMeshes = [];
  35004. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  35005. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  35006. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  35007. }
  35008. }
  35009. // Flat shading
  35010. if (mesh._shouldGenerateFlatShading) {
  35011. mesh.convertToFlatShadedMesh();
  35012. delete mesh._shouldGenerateFlatShading;
  35013. }
  35014. // Update
  35015. mesh.computeWorldMatrix(true);
  35016. // Octree
  35017. var sceneOctree = scene.selectionOctree;
  35018. if (sceneOctree !== undefined && sceneOctree !== null) {
  35019. sceneOctree.addMesh(mesh);
  35020. }
  35021. };
  35022. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  35023. var epsilon = 1e-3;
  35024. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  35025. return;
  35026. }
  35027. var noInfluenceBoneIndex = 0.0;
  35028. if (parsedGeometry.skeletonId > -1) {
  35029. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  35030. if (!skeleton) {
  35031. return;
  35032. }
  35033. noInfluenceBoneIndex = skeleton.bones.length;
  35034. }
  35035. else {
  35036. return;
  35037. }
  35038. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  35039. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  35040. var matricesWeights = parsedGeometry.matricesWeights;
  35041. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  35042. var influencers = parsedGeometry.numBoneInfluencer;
  35043. var size = matricesWeights.length;
  35044. for (var i = 0; i < size; i += 4) {
  35045. var weight = 0.0;
  35046. var firstZeroWeight = -1;
  35047. for (var j = 0; j < 4; j++) {
  35048. var w = matricesWeights[i + j];
  35049. weight += w;
  35050. if (w < epsilon && firstZeroWeight < 0) {
  35051. firstZeroWeight = j;
  35052. }
  35053. }
  35054. if (matricesWeightsExtra) {
  35055. for (var j = 0; j < 4; j++) {
  35056. var w = matricesWeightsExtra[i + j];
  35057. weight += w;
  35058. if (w < epsilon && firstZeroWeight < 0) {
  35059. firstZeroWeight = j + 4;
  35060. }
  35061. }
  35062. }
  35063. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  35064. firstZeroWeight = influencers - 1;
  35065. }
  35066. if (weight > epsilon) {
  35067. var mweight = 1.0 / weight;
  35068. for (var j = 0; j < 4; j++) {
  35069. matricesWeights[i + j] *= mweight;
  35070. }
  35071. if (matricesWeightsExtra) {
  35072. for (var j = 0; j < 4; j++) {
  35073. matricesWeightsExtra[i + j] *= mweight;
  35074. }
  35075. }
  35076. }
  35077. else {
  35078. if (firstZeroWeight >= 4) {
  35079. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  35080. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  35081. }
  35082. else {
  35083. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  35084. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  35085. }
  35086. }
  35087. }
  35088. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  35089. if (parsedGeometry.matricesWeightsExtra) {
  35090. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  35091. }
  35092. };
  35093. /**
  35094. * Create a new geometry from persisted data (Using .babylon file format)
  35095. * @param parsedVertexData defines the persisted data
  35096. * @param scene defines the hosting scene
  35097. * @param rootUrl defines the root url to use to load assets (like delayed data)
  35098. * @returns the new geometry object
  35099. */
  35100. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  35101. if (scene.getGeometryByID(parsedVertexData.id)) {
  35102. return null; // null since geometry could be something else than a box...
  35103. }
  35104. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  35105. if (BABYLON.Tags) {
  35106. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  35107. }
  35108. if (parsedVertexData.delayLoadingFile) {
  35109. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  35110. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  35111. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  35112. geometry._delayInfo = [];
  35113. if (parsedVertexData.hasUVs) {
  35114. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  35115. }
  35116. if (parsedVertexData.hasUVs2) {
  35117. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  35118. }
  35119. if (parsedVertexData.hasUVs3) {
  35120. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  35121. }
  35122. if (parsedVertexData.hasUVs4) {
  35123. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  35124. }
  35125. if (parsedVertexData.hasUVs5) {
  35126. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  35127. }
  35128. if (parsedVertexData.hasUVs6) {
  35129. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  35130. }
  35131. if (parsedVertexData.hasColors) {
  35132. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  35133. }
  35134. if (parsedVertexData.hasMatricesIndices) {
  35135. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  35136. }
  35137. if (parsedVertexData.hasMatricesWeights) {
  35138. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  35139. }
  35140. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  35141. }
  35142. else {
  35143. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  35144. }
  35145. scene.pushGeometry(geometry, true);
  35146. return geometry;
  35147. };
  35148. return Geometry;
  35149. }());
  35150. BABYLON.Geometry = Geometry;
  35151. // Primitives
  35152. /// Abstract class
  35153. /**
  35154. * Abstract class used to provide common services for all typed geometries
  35155. */
  35156. var _PrimitiveGeometry = /** @class */ (function (_super) {
  35157. __extends(_PrimitiveGeometry, _super);
  35158. /**
  35159. * Creates a new typed geometry
  35160. * @param id defines the unique ID of the geometry
  35161. * @param scene defines the hosting scene
  35162. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35163. * @param mesh defines the hosting mesh (can be null)
  35164. */
  35165. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  35166. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  35167. if (mesh === void 0) { mesh = null; }
  35168. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  35169. _this._canBeRegenerated = _canBeRegenerated;
  35170. _this._beingRegenerated = true;
  35171. _this.regenerate();
  35172. _this._beingRegenerated = false;
  35173. return _this;
  35174. }
  35175. /**
  35176. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  35177. * @returns true if the geometry can be regenerated
  35178. */
  35179. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  35180. return this._canBeRegenerated;
  35181. };
  35182. /**
  35183. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  35184. */
  35185. _PrimitiveGeometry.prototype.regenerate = function () {
  35186. if (!this._canBeRegenerated) {
  35187. return;
  35188. }
  35189. this._beingRegenerated = true;
  35190. this.setAllVerticesData(this._regenerateVertexData(), false);
  35191. this._beingRegenerated = false;
  35192. };
  35193. /**
  35194. * Clone the geometry
  35195. * @param id defines the unique ID of the new geometry
  35196. * @returns the new geometry
  35197. */
  35198. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  35199. return _super.prototype.copy.call(this, id);
  35200. };
  35201. // overrides
  35202. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  35203. if (!this._beingRegenerated) {
  35204. return;
  35205. }
  35206. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  35207. };
  35208. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  35209. if (!this._beingRegenerated) {
  35210. return;
  35211. }
  35212. _super.prototype.setVerticesData.call(this, kind, data, false);
  35213. };
  35214. // to override
  35215. /** @ignore */
  35216. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  35217. throw new Error("Abstract method");
  35218. };
  35219. _PrimitiveGeometry.prototype.copy = function (id) {
  35220. throw new Error("Must be overriden in sub-classes.");
  35221. };
  35222. _PrimitiveGeometry.prototype.serialize = function () {
  35223. var serializationObject = _super.prototype.serialize.call(this);
  35224. serializationObject.canBeRegenerated = this.canBeRegenerated();
  35225. return serializationObject;
  35226. };
  35227. return _PrimitiveGeometry;
  35228. }(Geometry));
  35229. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  35230. /**
  35231. * Creates a ribbon geometry
  35232. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  35233. */
  35234. var RibbonGeometry = /** @class */ (function (_super) {
  35235. __extends(RibbonGeometry, _super);
  35236. /**
  35237. * Creates a ribbon geometry
  35238. * @param id defines the unique ID of the geometry
  35239. * @param scene defines the hosting scene
  35240. * @param pathArray defines the array of paths to use
  35241. * @param closeArray defines if the last path and the first path must be joined
  35242. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  35243. * @param offset defines the offset between points
  35244. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35245. * @param mesh defines the hosting mesh (can be null)
  35246. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35247. */
  35248. function RibbonGeometry(id, scene,
  35249. /**
  35250. * Defines the array of paths to use
  35251. */
  35252. pathArray,
  35253. /**
  35254. * Defines if the last and first points of each path in your pathArray must be joined
  35255. */
  35256. closeArray,
  35257. /**
  35258. * Defines if the last and first points of each path in your pathArray must be joined
  35259. */
  35260. closePath,
  35261. /**
  35262. * Defines the offset between points
  35263. */
  35264. offset, canBeRegenerated, mesh,
  35265. /**
  35266. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35267. */
  35268. side) {
  35269. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35270. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35271. _this.pathArray = pathArray;
  35272. _this.closeArray = closeArray;
  35273. _this.closePath = closePath;
  35274. _this.offset = offset;
  35275. _this.side = side;
  35276. return _this;
  35277. }
  35278. /** @ignore */
  35279. RibbonGeometry.prototype._regenerateVertexData = function () {
  35280. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  35281. };
  35282. RibbonGeometry.prototype.copy = function (id) {
  35283. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  35284. };
  35285. return RibbonGeometry;
  35286. }(_PrimitiveGeometry));
  35287. BABYLON.RibbonGeometry = RibbonGeometry;
  35288. /**
  35289. * Creates a box geometry
  35290. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  35291. */
  35292. var BoxGeometry = /** @class */ (function (_super) {
  35293. __extends(BoxGeometry, _super);
  35294. /**
  35295. * Creates a box geometry
  35296. * @param id defines the unique ID of the geometry
  35297. * @param scene defines the hosting scene
  35298. * @param size defines the zise of the box (width, height and depth are the same)
  35299. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35300. * @param mesh defines the hosting mesh (can be null)
  35301. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35302. */
  35303. function BoxGeometry(id, scene,
  35304. /**
  35305. * Defines the zise of the box (width, height and depth are the same)
  35306. */
  35307. size, canBeRegenerated, mesh,
  35308. /**
  35309. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35310. */
  35311. side) {
  35312. if (mesh === void 0) { mesh = null; }
  35313. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35314. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35315. _this.size = size;
  35316. _this.side = side;
  35317. return _this;
  35318. }
  35319. BoxGeometry.prototype._regenerateVertexData = function () {
  35320. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  35321. };
  35322. BoxGeometry.prototype.copy = function (id) {
  35323. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  35324. };
  35325. BoxGeometry.prototype.serialize = function () {
  35326. var serializationObject = _super.prototype.serialize.call(this);
  35327. serializationObject.size = this.size;
  35328. return serializationObject;
  35329. };
  35330. BoxGeometry.Parse = function (parsedBox, scene) {
  35331. if (scene.getGeometryByID(parsedBox.id)) {
  35332. return null; // null since geometry could be something else than a box...
  35333. }
  35334. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  35335. if (BABYLON.Tags) {
  35336. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  35337. }
  35338. scene.pushGeometry(box, true);
  35339. return box;
  35340. };
  35341. return BoxGeometry;
  35342. }(_PrimitiveGeometry));
  35343. BABYLON.BoxGeometry = BoxGeometry;
  35344. /**
  35345. * Creates a sphere geometry
  35346. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  35347. */
  35348. var SphereGeometry = /** @class */ (function (_super) {
  35349. __extends(SphereGeometry, _super);
  35350. /**
  35351. * Create a new sphere geometry
  35352. * @param id defines the unique ID of the geometry
  35353. * @param scene defines the hosting scene
  35354. * @param segments defines the number of segments to use to create the sphere
  35355. * @param diameter defines the diameter of the sphere
  35356. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35357. * @param mesh defines the hosting mesh (can be null)
  35358. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35359. */
  35360. function SphereGeometry(id, scene,
  35361. /**
  35362. * Defines the number of segments to use to create the sphere
  35363. */
  35364. segments,
  35365. /**
  35366. * Defines the diameter of the sphere
  35367. */
  35368. diameter, canBeRegenerated, mesh,
  35369. /**
  35370. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35371. */
  35372. side) {
  35373. if (mesh === void 0) { mesh = null; }
  35374. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35375. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35376. _this.segments = segments;
  35377. _this.diameter = diameter;
  35378. _this.side = side;
  35379. return _this;
  35380. }
  35381. SphereGeometry.prototype._regenerateVertexData = function () {
  35382. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  35383. };
  35384. SphereGeometry.prototype.copy = function (id) {
  35385. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  35386. };
  35387. SphereGeometry.prototype.serialize = function () {
  35388. var serializationObject = _super.prototype.serialize.call(this);
  35389. serializationObject.segments = this.segments;
  35390. serializationObject.diameter = this.diameter;
  35391. return serializationObject;
  35392. };
  35393. SphereGeometry.Parse = function (parsedSphere, scene) {
  35394. if (scene.getGeometryByID(parsedSphere.id)) {
  35395. return null; // null since geometry could be something else than a sphere...
  35396. }
  35397. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  35398. if (BABYLON.Tags) {
  35399. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  35400. }
  35401. scene.pushGeometry(sphere, true);
  35402. return sphere;
  35403. };
  35404. return SphereGeometry;
  35405. }(_PrimitiveGeometry));
  35406. BABYLON.SphereGeometry = SphereGeometry;
  35407. /**
  35408. * Creates a disc geometry
  35409. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  35410. */
  35411. var DiscGeometry = /** @class */ (function (_super) {
  35412. __extends(DiscGeometry, _super);
  35413. /**
  35414. * Creates a new disc geometry
  35415. * @param id defines the unique ID of the geometry
  35416. * @param scene defines the hosting scene
  35417. * @param radius defines the radius of the disc
  35418. * @param tessellation defines the tesselation factor to apply to the disc
  35419. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35420. * @param mesh defines the hosting mesh (can be null)
  35421. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35422. */
  35423. function DiscGeometry(id, scene,
  35424. /**
  35425. * Defines the radius of the disc
  35426. */
  35427. radius,
  35428. /**
  35429. * Defines the tesselation factor to apply to the disc
  35430. */
  35431. tessellation, canBeRegenerated, mesh,
  35432. /**
  35433. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35434. */
  35435. side) {
  35436. if (mesh === void 0) { mesh = null; }
  35437. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35438. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35439. _this.radius = radius;
  35440. _this.tessellation = tessellation;
  35441. _this.side = side;
  35442. return _this;
  35443. }
  35444. DiscGeometry.prototype._regenerateVertexData = function () {
  35445. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  35446. };
  35447. DiscGeometry.prototype.copy = function (id) {
  35448. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  35449. };
  35450. return DiscGeometry;
  35451. }(_PrimitiveGeometry));
  35452. BABYLON.DiscGeometry = DiscGeometry;
  35453. /**
  35454. * Creates a new cylinder geometry
  35455. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  35456. */
  35457. var CylinderGeometry = /** @class */ (function (_super) {
  35458. __extends(CylinderGeometry, _super);
  35459. /**
  35460. * Creates a new cylinder geometry
  35461. * @param id defines the unique ID of the geometry
  35462. * @param scene defines the hosting scene
  35463. * @param height defines the height of the cylinder
  35464. * @param diameterTop defines the diameter of the cylinder's top cap
  35465. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  35466. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  35467. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  35468. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35469. * @param mesh defines the hosting mesh (can be null)
  35470. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35471. */
  35472. function CylinderGeometry(id, scene,
  35473. /**
  35474. * Defines the height of the cylinder
  35475. */
  35476. height,
  35477. /**
  35478. * Defines the diameter of the cylinder's top cap
  35479. */
  35480. diameterTop,
  35481. /**
  35482. * Defines the diameter of the cylinder's bottom cap
  35483. */
  35484. diameterBottom,
  35485. /**
  35486. * Defines the tessellation factor to apply to the cylinder
  35487. */
  35488. tessellation,
  35489. /**
  35490. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  35491. */
  35492. subdivisions, canBeRegenerated, mesh,
  35493. /**
  35494. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35495. */
  35496. side) {
  35497. if (subdivisions === void 0) { subdivisions = 1; }
  35498. if (mesh === void 0) { mesh = null; }
  35499. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35500. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35501. _this.height = height;
  35502. _this.diameterTop = diameterTop;
  35503. _this.diameterBottom = diameterBottom;
  35504. _this.tessellation = tessellation;
  35505. _this.subdivisions = subdivisions;
  35506. _this.side = side;
  35507. return _this;
  35508. }
  35509. CylinderGeometry.prototype._regenerateVertexData = function () {
  35510. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  35511. };
  35512. CylinderGeometry.prototype.copy = function (id) {
  35513. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  35514. };
  35515. CylinderGeometry.prototype.serialize = function () {
  35516. var serializationObject = _super.prototype.serialize.call(this);
  35517. serializationObject.height = this.height;
  35518. serializationObject.diameterTop = this.diameterTop;
  35519. serializationObject.diameterBottom = this.diameterBottom;
  35520. serializationObject.tessellation = this.tessellation;
  35521. return serializationObject;
  35522. };
  35523. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  35524. if (scene.getGeometryByID(parsedCylinder.id)) {
  35525. return null; // null since geometry could be something else than a cylinder...
  35526. }
  35527. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  35528. if (BABYLON.Tags) {
  35529. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  35530. }
  35531. scene.pushGeometry(cylinder, true);
  35532. return cylinder;
  35533. };
  35534. return CylinderGeometry;
  35535. }(_PrimitiveGeometry));
  35536. BABYLON.CylinderGeometry = CylinderGeometry;
  35537. /**
  35538. * Creates a new torus geometry
  35539. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  35540. */
  35541. var TorusGeometry = /** @class */ (function (_super) {
  35542. __extends(TorusGeometry, _super);
  35543. /**
  35544. * Creates a new torus geometry
  35545. * @param id defines the unique ID of the geometry
  35546. * @param scene defines the hosting scene
  35547. * @param diameter defines the diameter of the torus
  35548. * @param thickness defines the thickness of the torus (ie. internal diameter)
  35549. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  35550. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35551. * @param mesh defines the hosting mesh (can be null)
  35552. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35553. */
  35554. function TorusGeometry(id, scene,
  35555. /**
  35556. * Defines the diameter of the torus
  35557. */
  35558. diameter,
  35559. /**
  35560. * Defines the thickness of the torus (ie. internal diameter)
  35561. */
  35562. thickness,
  35563. /**
  35564. * Defines the tesselation factor to apply to the torus
  35565. */
  35566. tessellation, canBeRegenerated, mesh,
  35567. /**
  35568. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35569. */
  35570. side) {
  35571. if (mesh === void 0) { mesh = null; }
  35572. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35573. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35574. _this.diameter = diameter;
  35575. _this.thickness = thickness;
  35576. _this.tessellation = tessellation;
  35577. _this.side = side;
  35578. return _this;
  35579. }
  35580. TorusGeometry.prototype._regenerateVertexData = function () {
  35581. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  35582. };
  35583. TorusGeometry.prototype.copy = function (id) {
  35584. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  35585. };
  35586. TorusGeometry.prototype.serialize = function () {
  35587. var serializationObject = _super.prototype.serialize.call(this);
  35588. serializationObject.diameter = this.diameter;
  35589. serializationObject.thickness = this.thickness;
  35590. serializationObject.tessellation = this.tessellation;
  35591. return serializationObject;
  35592. };
  35593. TorusGeometry.Parse = function (parsedTorus, scene) {
  35594. if (scene.getGeometryByID(parsedTorus.id)) {
  35595. return null; // null since geometry could be something else than a torus...
  35596. }
  35597. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  35598. if (BABYLON.Tags) {
  35599. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  35600. }
  35601. scene.pushGeometry(torus, true);
  35602. return torus;
  35603. };
  35604. return TorusGeometry;
  35605. }(_PrimitiveGeometry));
  35606. BABYLON.TorusGeometry = TorusGeometry;
  35607. /**
  35608. * Creates a new ground geometry
  35609. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  35610. */
  35611. var GroundGeometry = /** @class */ (function (_super) {
  35612. __extends(GroundGeometry, _super);
  35613. /**
  35614. * Creates a new ground geometry
  35615. * @param id defines the unique ID of the geometry
  35616. * @param scene defines the hosting scene
  35617. * @param width defines the width of the ground
  35618. * @param height defines the height of the ground
  35619. * @param subdivisions defines the subdivisions to apply to the ground
  35620. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35621. * @param mesh defines the hosting mesh (can be null)
  35622. */
  35623. function GroundGeometry(id, scene,
  35624. /**
  35625. * Defines the width of the ground
  35626. */
  35627. width,
  35628. /**
  35629. * Defines the height of the ground
  35630. */
  35631. height,
  35632. /**
  35633. * Defines the subdivisions to apply to the ground
  35634. */
  35635. subdivisions, canBeRegenerated, mesh) {
  35636. if (mesh === void 0) { mesh = null; }
  35637. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35638. _this.width = width;
  35639. _this.height = height;
  35640. _this.subdivisions = subdivisions;
  35641. return _this;
  35642. }
  35643. GroundGeometry.prototype._regenerateVertexData = function () {
  35644. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  35645. };
  35646. GroundGeometry.prototype.copy = function (id) {
  35647. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  35648. };
  35649. GroundGeometry.prototype.serialize = function () {
  35650. var serializationObject = _super.prototype.serialize.call(this);
  35651. serializationObject.width = this.width;
  35652. serializationObject.height = this.height;
  35653. serializationObject.subdivisions = this.subdivisions;
  35654. return serializationObject;
  35655. };
  35656. GroundGeometry.Parse = function (parsedGround, scene) {
  35657. if (scene.getGeometryByID(parsedGround.id)) {
  35658. return null; // null since geometry could be something else than a ground...
  35659. }
  35660. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  35661. if (BABYLON.Tags) {
  35662. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  35663. }
  35664. scene.pushGeometry(ground, true);
  35665. return ground;
  35666. };
  35667. return GroundGeometry;
  35668. }(_PrimitiveGeometry));
  35669. BABYLON.GroundGeometry = GroundGeometry;
  35670. /**
  35671. * Creates a tiled ground geometry
  35672. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  35673. */
  35674. var TiledGroundGeometry = /** @class */ (function (_super) {
  35675. __extends(TiledGroundGeometry, _super);
  35676. /**
  35677. * Creates a tiled ground geometry
  35678. * @param id defines the unique ID of the geometry
  35679. * @param scene defines the hosting scene
  35680. * @param xmin defines the minimum value on X axis
  35681. * @param zmin defines the minimum value on Z axis
  35682. * @param xmax defines the maximum value on X axis
  35683. * @param zmax defines the maximum value on Z axis
  35684. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  35685. * @param precision defines the precision to use when computing the tiles
  35686. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35687. * @param mesh defines the hosting mesh (can be null)
  35688. */
  35689. function TiledGroundGeometry(id, scene,
  35690. /**
  35691. * Defines the minimum value on X axis
  35692. */
  35693. xmin,
  35694. /**
  35695. * Defines the minimum value on Z axis
  35696. */
  35697. zmin,
  35698. /**
  35699. * Defines the maximum value on X axis
  35700. */
  35701. xmax,
  35702. /**
  35703. * Defines the maximum value on Z axis
  35704. */
  35705. zmax,
  35706. /**
  35707. * Defines the subdivisions to apply to the ground
  35708. */
  35709. subdivisions,
  35710. /**
  35711. * Defines the precision to use when computing the tiles
  35712. */
  35713. precision, canBeRegenerated, mesh) {
  35714. if (mesh === void 0) { mesh = null; }
  35715. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35716. _this.xmin = xmin;
  35717. _this.zmin = zmin;
  35718. _this.xmax = xmax;
  35719. _this.zmax = zmax;
  35720. _this.subdivisions = subdivisions;
  35721. _this.precision = precision;
  35722. return _this;
  35723. }
  35724. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  35725. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  35726. };
  35727. TiledGroundGeometry.prototype.copy = function (id) {
  35728. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  35729. };
  35730. return TiledGroundGeometry;
  35731. }(_PrimitiveGeometry));
  35732. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  35733. /**
  35734. * Creates a plane geometry
  35735. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  35736. */
  35737. var PlaneGeometry = /** @class */ (function (_super) {
  35738. __extends(PlaneGeometry, _super);
  35739. /**
  35740. * Creates a plane geometry
  35741. * @param id defines the unique ID of the geometry
  35742. * @param scene defines the hosting scene
  35743. * @param size defines the size of the plane (width === height)
  35744. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35745. * @param mesh defines the hosting mesh (can be null)
  35746. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35747. */
  35748. function PlaneGeometry(id, scene,
  35749. /**
  35750. * Defines the size of the plane (width === height)
  35751. */
  35752. size, canBeRegenerated, mesh,
  35753. /**
  35754. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35755. */
  35756. side) {
  35757. if (mesh === void 0) { mesh = null; }
  35758. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35759. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35760. _this.size = size;
  35761. _this.side = side;
  35762. return _this;
  35763. }
  35764. PlaneGeometry.prototype._regenerateVertexData = function () {
  35765. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  35766. };
  35767. PlaneGeometry.prototype.copy = function (id) {
  35768. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  35769. };
  35770. PlaneGeometry.prototype.serialize = function () {
  35771. var serializationObject = _super.prototype.serialize.call(this);
  35772. serializationObject.size = this.size;
  35773. return serializationObject;
  35774. };
  35775. PlaneGeometry.Parse = function (parsedPlane, scene) {
  35776. if (scene.getGeometryByID(parsedPlane.id)) {
  35777. return null; // null since geometry could be something else than a ground...
  35778. }
  35779. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  35780. if (BABYLON.Tags) {
  35781. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  35782. }
  35783. scene.pushGeometry(plane, true);
  35784. return plane;
  35785. };
  35786. return PlaneGeometry;
  35787. }(_PrimitiveGeometry));
  35788. BABYLON.PlaneGeometry = PlaneGeometry;
  35789. /**
  35790. * Creates a torus knot geometry
  35791. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  35792. */
  35793. var TorusKnotGeometry = /** @class */ (function (_super) {
  35794. __extends(TorusKnotGeometry, _super);
  35795. /**
  35796. * Creates a torus knot geometry
  35797. * @param id defines the unique ID of the geometry
  35798. * @param scene defines the hosting scene
  35799. * @param radius defines the radius of the torus knot
  35800. * @param tube defines the thickness of the torus knot tube
  35801. * @param radialSegments defines the number of radial segments
  35802. * @param tubularSegments defines the number of tubular segments
  35803. * @param p defines the first number of windings
  35804. * @param q defines the second number of windings
  35805. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35806. * @param mesh defines the hosting mesh (can be null)
  35807. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35808. */
  35809. function TorusKnotGeometry(id, scene,
  35810. /**
  35811. * Defines the radius of the torus knot
  35812. */
  35813. radius,
  35814. /**
  35815. * Defines the thickness of the torus knot tube
  35816. */
  35817. tube,
  35818. /**
  35819. * Defines the number of radial segments
  35820. */
  35821. radialSegments,
  35822. /**
  35823. * Defines the number of tubular segments
  35824. */
  35825. tubularSegments,
  35826. /**
  35827. * Defines the first number of windings
  35828. */
  35829. p,
  35830. /**
  35831. * Defines the second number of windings
  35832. */
  35833. q, canBeRegenerated, mesh,
  35834. /**
  35835. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35836. */
  35837. side) {
  35838. if (mesh === void 0) { mesh = null; }
  35839. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35840. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35841. _this.radius = radius;
  35842. _this.tube = tube;
  35843. _this.radialSegments = radialSegments;
  35844. _this.tubularSegments = tubularSegments;
  35845. _this.p = p;
  35846. _this.q = q;
  35847. _this.side = side;
  35848. return _this;
  35849. }
  35850. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  35851. 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 });
  35852. };
  35853. TorusKnotGeometry.prototype.copy = function (id) {
  35854. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  35855. };
  35856. TorusKnotGeometry.prototype.serialize = function () {
  35857. var serializationObject = _super.prototype.serialize.call(this);
  35858. serializationObject.radius = this.radius;
  35859. serializationObject.tube = this.tube;
  35860. serializationObject.radialSegments = this.radialSegments;
  35861. serializationObject.tubularSegments = this.tubularSegments;
  35862. serializationObject.p = this.p;
  35863. serializationObject.q = this.q;
  35864. return serializationObject;
  35865. };
  35866. ;
  35867. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  35868. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  35869. return null; // null since geometry could be something else than a ground...
  35870. }
  35871. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  35872. if (BABYLON.Tags) {
  35873. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  35874. }
  35875. scene.pushGeometry(torusKnot, true);
  35876. return torusKnot;
  35877. };
  35878. return TorusKnotGeometry;
  35879. }(_PrimitiveGeometry));
  35880. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  35881. //}
  35882. })(BABYLON || (BABYLON = {}));
  35883. //# sourceMappingURL=babylon.geometry.js.map
  35884. var BABYLON;
  35885. (function (BABYLON) {
  35886. /**
  35887. * PostProcessManager is used to manage one or more post processes or post process pipelines
  35888. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  35889. */
  35890. var PostProcessManager = /** @class */ (function () {
  35891. /**
  35892. * Creates a new instance of @see PostProcess
  35893. * @param scene The scene that the post process is associated with.
  35894. */
  35895. function PostProcessManager(scene) {
  35896. this._vertexBuffers = {};
  35897. this._scene = scene;
  35898. }
  35899. PostProcessManager.prototype._prepareBuffers = function () {
  35900. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  35901. return;
  35902. }
  35903. // VBO
  35904. var vertices = [];
  35905. vertices.push(1, 1);
  35906. vertices.push(-1, 1);
  35907. vertices.push(-1, -1);
  35908. vertices.push(1, -1);
  35909. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  35910. this._buildIndexBuffer();
  35911. };
  35912. PostProcessManager.prototype._buildIndexBuffer = function () {
  35913. // Indices
  35914. var indices = [];
  35915. indices.push(0);
  35916. indices.push(1);
  35917. indices.push(2);
  35918. indices.push(0);
  35919. indices.push(2);
  35920. indices.push(3);
  35921. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  35922. };
  35923. /**
  35924. * Rebuilds the vertex buffers of the manager.
  35925. */
  35926. PostProcessManager.prototype._rebuild = function () {
  35927. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  35928. if (!vb) {
  35929. return;
  35930. }
  35931. vb._rebuild();
  35932. this._buildIndexBuffer();
  35933. };
  35934. // Methods
  35935. /**
  35936. * Prepares a frame to be run through a post process.
  35937. * @param sourceTexture The input texture to the post procesess. (default: null)
  35938. * @param postProcesses An array of post processes to be run. (default: null)
  35939. * @returns True if the post processes were able to be run.
  35940. */
  35941. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  35942. if (sourceTexture === void 0) { sourceTexture = null; }
  35943. if (postProcesses === void 0) { postProcesses = null; }
  35944. var camera = this._scene.activeCamera;
  35945. if (!camera) {
  35946. return false;
  35947. }
  35948. var postProcesses = postProcesses || camera._postProcesses;
  35949. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  35950. return false;
  35951. }
  35952. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  35953. return true;
  35954. };
  35955. /**
  35956. * Manually render a set of post processes to a texture.
  35957. * @param postProcesses An array of post processes to be run.
  35958. * @param targetTexture The target texture to render to.
  35959. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  35960. */
  35961. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  35962. if (targetTexture === void 0) { targetTexture = null; }
  35963. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  35964. var engine = this._scene.getEngine();
  35965. for (var index = 0; index < postProcesses.length; index++) {
  35966. if (index < postProcesses.length - 1) {
  35967. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  35968. }
  35969. else {
  35970. if (targetTexture) {
  35971. engine.bindFramebuffer(targetTexture, 0, undefined, undefined, forceFullscreenViewport);
  35972. }
  35973. else {
  35974. engine.restoreDefaultFramebuffer();
  35975. }
  35976. }
  35977. var pp = postProcesses[index];
  35978. var effect = pp.apply();
  35979. if (effect) {
  35980. pp.onBeforeRenderObservable.notifyObservers(effect);
  35981. // VBOs
  35982. this._prepareBuffers();
  35983. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  35984. // Draw order
  35985. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  35986. pp.onAfterRenderObservable.notifyObservers(effect);
  35987. }
  35988. }
  35989. // Restore depth buffer
  35990. engine.setDepthBuffer(true);
  35991. engine.setDepthWrite(true);
  35992. };
  35993. /**
  35994. * Finalize the result of the output of the postprocesses.
  35995. * @param doNotPresent If true the result will not be displayed to the screen.
  35996. * @param targetTexture The target texture to render to.
  35997. * @param faceIndex The index of the face to bind the target texture to.
  35998. * @param postProcesses The array of post processes to render.
  35999. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  36000. */
  36001. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  36002. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  36003. var camera = this._scene.activeCamera;
  36004. if (!camera) {
  36005. return;
  36006. }
  36007. postProcesses = postProcesses || camera._postProcesses;
  36008. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  36009. return;
  36010. }
  36011. var engine = this._scene.getEngine();
  36012. for (var index = 0, len = postProcesses.length; index < len; index++) {
  36013. if (index < len - 1) {
  36014. postProcesses[index + 1].activate(camera, targetTexture);
  36015. }
  36016. else {
  36017. if (targetTexture) {
  36018. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  36019. }
  36020. else {
  36021. engine.restoreDefaultFramebuffer();
  36022. }
  36023. }
  36024. if (doNotPresent) {
  36025. break;
  36026. }
  36027. var pp = postProcesses[index];
  36028. var effect = pp.apply();
  36029. if (effect) {
  36030. pp.onBeforeRenderObservable.notifyObservers(effect);
  36031. // VBOs
  36032. this._prepareBuffers();
  36033. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  36034. // Draw order
  36035. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  36036. pp.onAfterRenderObservable.notifyObservers(effect);
  36037. }
  36038. }
  36039. // Restore states
  36040. engine.setDepthBuffer(true);
  36041. engine.setDepthWrite(true);
  36042. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  36043. };
  36044. /**
  36045. * Disposes of the post process manager.
  36046. */
  36047. PostProcessManager.prototype.dispose = function () {
  36048. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  36049. if (buffer) {
  36050. buffer.dispose();
  36051. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  36052. }
  36053. if (this._indexBuffer) {
  36054. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  36055. this._indexBuffer = null;
  36056. }
  36057. };
  36058. return PostProcessManager;
  36059. }());
  36060. BABYLON.PostProcessManager = PostProcessManager;
  36061. })(BABYLON || (BABYLON = {}));
  36062. //# sourceMappingURL=babylon.postProcessManager.js.map
  36063. var BABYLON;
  36064. (function (BABYLON) {
  36065. /**
  36066. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  36067. */
  36068. var PerformanceMonitor = /** @class */ (function () {
  36069. /**
  36070. * constructor
  36071. * @param frameSampleSize The number of samples required to saturate the sliding window
  36072. */
  36073. function PerformanceMonitor(frameSampleSize) {
  36074. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  36075. this._enabled = true;
  36076. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  36077. }
  36078. /**
  36079. * Samples current frame
  36080. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  36081. */
  36082. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  36083. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  36084. if (!this._enabled)
  36085. return;
  36086. if (this._lastFrameTimeMs != null) {
  36087. var dt = timeMs - this._lastFrameTimeMs;
  36088. this._rollingFrameTime.add(dt);
  36089. }
  36090. this._lastFrameTimeMs = timeMs;
  36091. };
  36092. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  36093. /**
  36094. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  36095. * @return Average frame time in milliseconds
  36096. */
  36097. get: function () {
  36098. return this._rollingFrameTime.average;
  36099. },
  36100. enumerable: true,
  36101. configurable: true
  36102. });
  36103. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  36104. /**
  36105. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  36106. * @return Frame time variance in milliseconds squared
  36107. */
  36108. get: function () {
  36109. return this._rollingFrameTime.variance;
  36110. },
  36111. enumerable: true,
  36112. configurable: true
  36113. });
  36114. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  36115. /**
  36116. * Returns the frame time of the most recent frame
  36117. * @return Frame time in milliseconds
  36118. */
  36119. get: function () {
  36120. return this._rollingFrameTime.history(0);
  36121. },
  36122. enumerable: true,
  36123. configurable: true
  36124. });
  36125. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  36126. /**
  36127. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  36128. * @return Framerate in frames per second
  36129. */
  36130. get: function () {
  36131. return 1000.0 / this._rollingFrameTime.average;
  36132. },
  36133. enumerable: true,
  36134. configurable: true
  36135. });
  36136. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  36137. /**
  36138. * Returns the average framerate in frames per second using the most recent frame time
  36139. * @return Framerate in frames per second
  36140. */
  36141. get: function () {
  36142. var history = this._rollingFrameTime.history(0);
  36143. if (history === 0) {
  36144. return 0;
  36145. }
  36146. return 1000.0 / history;
  36147. },
  36148. enumerable: true,
  36149. configurable: true
  36150. });
  36151. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  36152. /**
  36153. * Returns true if enough samples have been taken to completely fill the sliding window
  36154. * @return true if saturated
  36155. */
  36156. get: function () {
  36157. return this._rollingFrameTime.isSaturated();
  36158. },
  36159. enumerable: true,
  36160. configurable: true
  36161. });
  36162. /**
  36163. * Enables contributions to the sliding window sample set
  36164. */
  36165. PerformanceMonitor.prototype.enable = function () {
  36166. this._enabled = true;
  36167. };
  36168. /**
  36169. * Disables contributions to the sliding window sample set
  36170. * Samples will not be interpolated over the disabled period
  36171. */
  36172. PerformanceMonitor.prototype.disable = function () {
  36173. this._enabled = false;
  36174. //clear last sample to avoid interpolating over the disabled period when next enabled
  36175. this._lastFrameTimeMs = null;
  36176. };
  36177. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  36178. /**
  36179. * Returns true if sampling is enabled
  36180. * @return true if enabled
  36181. */
  36182. get: function () {
  36183. return this._enabled;
  36184. },
  36185. enumerable: true,
  36186. configurable: true
  36187. });
  36188. /**
  36189. * Resets performance monitor
  36190. */
  36191. PerformanceMonitor.prototype.reset = function () {
  36192. //clear last sample to avoid interpolating over the disabled period when next enabled
  36193. this._lastFrameTimeMs = null;
  36194. //wipe record
  36195. this._rollingFrameTime.reset();
  36196. };
  36197. return PerformanceMonitor;
  36198. }());
  36199. BABYLON.PerformanceMonitor = PerformanceMonitor;
  36200. /**
  36201. * RollingAverage
  36202. *
  36203. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  36204. */
  36205. var RollingAverage = /** @class */ (function () {
  36206. /**
  36207. * constructor
  36208. * @param length The number of samples required to saturate the sliding window
  36209. */
  36210. function RollingAverage(length) {
  36211. this._samples = new Array(length);
  36212. this.reset();
  36213. }
  36214. /**
  36215. * Adds a sample to the sample set
  36216. * @param v The sample value
  36217. */
  36218. RollingAverage.prototype.add = function (v) {
  36219. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  36220. var delta;
  36221. //we need to check if we've already wrapped round
  36222. if (this.isSaturated()) {
  36223. //remove bottom of stack from mean
  36224. var bottomValue = this._samples[this._pos];
  36225. delta = bottomValue - this.average;
  36226. this.average -= delta / (this._sampleCount - 1);
  36227. this._m2 -= delta * (bottomValue - this.average);
  36228. }
  36229. else {
  36230. this._sampleCount++;
  36231. }
  36232. //add new value to mean
  36233. delta = v - this.average;
  36234. this.average += delta / (this._sampleCount);
  36235. this._m2 += delta * (v - this.average);
  36236. //set the new variance
  36237. this.variance = this._m2 / (this._sampleCount - 1);
  36238. this._samples[this._pos] = v;
  36239. this._pos++;
  36240. this._pos %= this._samples.length; //positive wrap around
  36241. };
  36242. /**
  36243. * Returns previously added values or null if outside of history or outside the sliding window domain
  36244. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  36245. * @return Value previously recorded with add() or null if outside of range
  36246. */
  36247. RollingAverage.prototype.history = function (i) {
  36248. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  36249. return 0;
  36250. }
  36251. var i0 = this._wrapPosition(this._pos - 1.0);
  36252. return this._samples[this._wrapPosition(i0 - i)];
  36253. };
  36254. /**
  36255. * Returns true if enough samples have been taken to completely fill the sliding window
  36256. * @return true if sample-set saturated
  36257. */
  36258. RollingAverage.prototype.isSaturated = function () {
  36259. return this._sampleCount >= this._samples.length;
  36260. };
  36261. /**
  36262. * Resets the rolling average (equivalent to 0 samples taken so far)
  36263. */
  36264. RollingAverage.prototype.reset = function () {
  36265. this.average = 0;
  36266. this.variance = 0;
  36267. this._sampleCount = 0;
  36268. this._pos = 0;
  36269. this._m2 = 0;
  36270. };
  36271. /**
  36272. * Wraps a value around the sample range boundaries
  36273. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  36274. * @return Wrapped position in sample range
  36275. */
  36276. RollingAverage.prototype._wrapPosition = function (i) {
  36277. var max = this._samples.length;
  36278. return ((i % max) + max) % max;
  36279. };
  36280. return RollingAverage;
  36281. }());
  36282. BABYLON.RollingAverage = RollingAverage;
  36283. })(BABYLON || (BABYLON = {}));
  36284. //# sourceMappingURL=babylon.performanceMonitor.js.map
  36285. var BABYLON;
  36286. (function (BABYLON) {
  36287. /**
  36288. * This groups together the common properties used for image processing either in direct forward pass
  36289. * or through post processing effect depending on the use of the image processing pipeline in your scene
  36290. * or not.
  36291. */
  36292. var ImageProcessingConfiguration = /** @class */ (function () {
  36293. function ImageProcessingConfiguration() {
  36294. /**
  36295. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  36296. */
  36297. this.colorCurves = new BABYLON.ColorCurves();
  36298. this._colorCurvesEnabled = false;
  36299. this._colorGradingEnabled = false;
  36300. this._colorGradingWithGreenDepth = true;
  36301. this._colorGradingBGR = true;
  36302. this._exposure = 1.0;
  36303. this._toneMappingEnabled = false;
  36304. this._contrast = 1.0;
  36305. /**
  36306. * Vignette stretch size.
  36307. */
  36308. this.vignetteStretch = 0;
  36309. /**
  36310. * Vignette centre X Offset.
  36311. */
  36312. this.vignetteCentreX = 0;
  36313. /**
  36314. * Vignette centre Y Offset.
  36315. */
  36316. this.vignetteCentreY = 0;
  36317. /**
  36318. * Vignette weight or intensity of the vignette effect.
  36319. */
  36320. this.vignetteWeight = 1.5;
  36321. /**
  36322. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  36323. * if vignetteEnabled is set to true.
  36324. */
  36325. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  36326. /**
  36327. * Camera field of view used by the Vignette effect.
  36328. */
  36329. this.vignetteCameraFov = 0.5;
  36330. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  36331. this._vignetteEnabled = false;
  36332. this._applyByPostProcess = false;
  36333. this._isEnabled = true;
  36334. /**
  36335. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  36336. * @type {BABYLON.Observable}
  36337. */
  36338. this.onUpdateParameters = new BABYLON.Observable();
  36339. }
  36340. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  36341. /**
  36342. * Gets wether the color curves effect is enabled.
  36343. */
  36344. get: function () {
  36345. return this._colorCurvesEnabled;
  36346. },
  36347. /**
  36348. * Sets wether the color curves effect is enabled.
  36349. */
  36350. set: function (value) {
  36351. if (this._colorCurvesEnabled === value) {
  36352. return;
  36353. }
  36354. this._colorCurvesEnabled = value;
  36355. this._updateParameters();
  36356. },
  36357. enumerable: true,
  36358. configurable: true
  36359. });
  36360. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  36361. /**
  36362. * Gets wether the color grading effect is enabled.
  36363. */
  36364. get: function () {
  36365. return this._colorGradingEnabled;
  36366. },
  36367. /**
  36368. * Sets wether the color grading effect is enabled.
  36369. */
  36370. set: function (value) {
  36371. if (this._colorGradingEnabled === value) {
  36372. return;
  36373. }
  36374. this._colorGradingEnabled = value;
  36375. this._updateParameters();
  36376. },
  36377. enumerable: true,
  36378. configurable: true
  36379. });
  36380. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  36381. /**
  36382. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  36383. */
  36384. get: function () {
  36385. return this._colorGradingWithGreenDepth;
  36386. },
  36387. /**
  36388. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  36389. */
  36390. set: function (value) {
  36391. if (this._colorGradingWithGreenDepth === value) {
  36392. return;
  36393. }
  36394. this._colorGradingWithGreenDepth = value;
  36395. this._updateParameters();
  36396. },
  36397. enumerable: true,
  36398. configurable: true
  36399. });
  36400. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  36401. /**
  36402. * Gets wether the color grading texture contains BGR values.
  36403. */
  36404. get: function () {
  36405. return this._colorGradingBGR;
  36406. },
  36407. /**
  36408. * Sets wether the color grading texture contains BGR values.
  36409. */
  36410. set: function (value) {
  36411. if (this._colorGradingBGR === value) {
  36412. return;
  36413. }
  36414. this._colorGradingBGR = value;
  36415. this._updateParameters();
  36416. },
  36417. enumerable: true,
  36418. configurable: true
  36419. });
  36420. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  36421. /**
  36422. * Gets the Exposure used in the effect.
  36423. */
  36424. get: function () {
  36425. return this._exposure;
  36426. },
  36427. /**
  36428. * Sets the Exposure used in the effect.
  36429. */
  36430. set: function (value) {
  36431. if (this._exposure === value) {
  36432. return;
  36433. }
  36434. this._exposure = value;
  36435. this._updateParameters();
  36436. },
  36437. enumerable: true,
  36438. configurable: true
  36439. });
  36440. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  36441. /**
  36442. * Gets wether the tone mapping effect is enabled.
  36443. */
  36444. get: function () {
  36445. return this._toneMappingEnabled;
  36446. },
  36447. /**
  36448. * Sets wether the tone mapping effect is enabled.
  36449. */
  36450. set: function (value) {
  36451. if (this._toneMappingEnabled === value) {
  36452. return;
  36453. }
  36454. this._toneMappingEnabled = value;
  36455. this._updateParameters();
  36456. },
  36457. enumerable: true,
  36458. configurable: true
  36459. });
  36460. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  36461. /**
  36462. * Gets the contrast used in the effect.
  36463. */
  36464. get: function () {
  36465. return this._contrast;
  36466. },
  36467. /**
  36468. * Sets the contrast used in the effect.
  36469. */
  36470. set: function (value) {
  36471. if (this._contrast === value) {
  36472. return;
  36473. }
  36474. this._contrast = value;
  36475. this._updateParameters();
  36476. },
  36477. enumerable: true,
  36478. configurable: true
  36479. });
  36480. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  36481. /**
  36482. * Gets the vignette blend mode allowing different kind of effect.
  36483. */
  36484. get: function () {
  36485. return this._vignetteBlendMode;
  36486. },
  36487. /**
  36488. * Sets the vignette blend mode allowing different kind of effect.
  36489. */
  36490. set: function (value) {
  36491. if (this._vignetteBlendMode === value) {
  36492. return;
  36493. }
  36494. this._vignetteBlendMode = value;
  36495. this._updateParameters();
  36496. },
  36497. enumerable: true,
  36498. configurable: true
  36499. });
  36500. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  36501. /**
  36502. * Gets wether the vignette effect is enabled.
  36503. */
  36504. get: function () {
  36505. return this._vignetteEnabled;
  36506. },
  36507. /**
  36508. * Sets wether the vignette effect is enabled.
  36509. */
  36510. set: function (value) {
  36511. if (this._vignetteEnabled === value) {
  36512. return;
  36513. }
  36514. this._vignetteEnabled = value;
  36515. this._updateParameters();
  36516. },
  36517. enumerable: true,
  36518. configurable: true
  36519. });
  36520. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  36521. /**
  36522. * Gets wether the image processing is applied through a post process or not.
  36523. */
  36524. get: function () {
  36525. return this._applyByPostProcess;
  36526. },
  36527. /**
  36528. * Sets wether the image processing is applied through a post process or not.
  36529. */
  36530. set: function (value) {
  36531. if (this._applyByPostProcess === value) {
  36532. return;
  36533. }
  36534. this._applyByPostProcess = value;
  36535. this._updateParameters();
  36536. },
  36537. enumerable: true,
  36538. configurable: true
  36539. });
  36540. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  36541. /**
  36542. * Gets wether the image processing is enabled or not.
  36543. */
  36544. get: function () {
  36545. return this._isEnabled;
  36546. },
  36547. /**
  36548. * Sets wether the image processing is enabled or not.
  36549. */
  36550. set: function (value) {
  36551. if (this._isEnabled === value) {
  36552. return;
  36553. }
  36554. this._isEnabled = value;
  36555. this._updateParameters();
  36556. },
  36557. enumerable: true,
  36558. configurable: true
  36559. });
  36560. /**
  36561. * Method called each time the image processing information changes requires to recompile the effect.
  36562. */
  36563. ImageProcessingConfiguration.prototype._updateParameters = function () {
  36564. this.onUpdateParameters.notifyObservers(this);
  36565. };
  36566. ImageProcessingConfiguration.prototype.getClassName = function () {
  36567. return "ImageProcessingConfiguration";
  36568. };
  36569. /**
  36570. * Prepare the list of uniforms associated with the Image Processing effects.
  36571. * @param uniformsList The list of uniforms used in the effect
  36572. * @param defines the list of defines currently in use
  36573. */
  36574. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  36575. if (defines.EXPOSURE) {
  36576. uniforms.push("exposureLinear");
  36577. }
  36578. if (defines.CONTRAST) {
  36579. uniforms.push("contrast");
  36580. }
  36581. if (defines.COLORGRADING) {
  36582. uniforms.push("colorTransformSettings");
  36583. }
  36584. if (defines.VIGNETTE) {
  36585. uniforms.push("vInverseScreenSize");
  36586. uniforms.push("vignetteSettings1");
  36587. uniforms.push("vignetteSettings2");
  36588. }
  36589. if (defines.COLORCURVES) {
  36590. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  36591. }
  36592. };
  36593. /**
  36594. * Prepare the list of samplers associated with the Image Processing effects.
  36595. * @param uniformsList The list of uniforms used in the effect
  36596. * @param defines the list of defines currently in use
  36597. */
  36598. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  36599. if (defines.COLORGRADING) {
  36600. samplersList.push("txColorTransform");
  36601. }
  36602. };
  36603. /**
  36604. * Prepare the list of defines associated to the shader.
  36605. * @param defines the list of defines to complete
  36606. */
  36607. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  36608. if (forPostProcess === void 0) { forPostProcess = false; }
  36609. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  36610. defines.VIGNETTE = false;
  36611. defines.TONEMAPPING = false;
  36612. defines.CONTRAST = false;
  36613. defines.EXPOSURE = false;
  36614. defines.COLORCURVES = false;
  36615. defines.COLORGRADING = false;
  36616. defines.COLORGRADING3D = false;
  36617. defines.IMAGEPROCESSING = false;
  36618. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  36619. return;
  36620. }
  36621. defines.VIGNETTE = this.vignetteEnabled;
  36622. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  36623. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  36624. defines.TONEMAPPING = this.toneMappingEnabled;
  36625. defines.CONTRAST = (this.contrast !== 1.0);
  36626. defines.EXPOSURE = (this.exposure !== 1.0);
  36627. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  36628. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  36629. if (defines.COLORGRADING) {
  36630. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  36631. }
  36632. else {
  36633. defines.COLORGRADING3D = false;
  36634. }
  36635. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  36636. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  36637. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  36638. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  36639. };
  36640. /**
  36641. * Returns true if all the image processing information are ready.
  36642. */
  36643. ImageProcessingConfiguration.prototype.isReady = function () {
  36644. // Color Grading texure can not be none blocking.
  36645. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  36646. };
  36647. /**
  36648. * Binds the image processing to the shader.
  36649. * @param effect The effect to bind to
  36650. */
  36651. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  36652. if (aspectRatio === void 0) { aspectRatio = 1; }
  36653. // Color Curves
  36654. if (this._colorCurvesEnabled && this.colorCurves) {
  36655. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  36656. }
  36657. // Vignette
  36658. if (this._vignetteEnabled) {
  36659. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  36660. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  36661. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  36662. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  36663. var vignetteScaleX = vignetteScaleY * aspectRatio;
  36664. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  36665. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  36666. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  36667. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  36668. var vignettePower = -2.0 * this.vignetteWeight;
  36669. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  36670. }
  36671. // Exposure
  36672. effect.setFloat("exposureLinear", this.exposure);
  36673. // Contrast
  36674. effect.setFloat("contrast", this.contrast);
  36675. // Color transform settings
  36676. if (this.colorGradingTexture) {
  36677. effect.setTexture("txColorTransform", this.colorGradingTexture);
  36678. var textureSize = this.colorGradingTexture.getSize().height;
  36679. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  36680. 0.5 / textureSize, // textureOffset
  36681. textureSize, // textureSize
  36682. this.colorGradingTexture.level // weight
  36683. );
  36684. }
  36685. };
  36686. /**
  36687. * Clones the current image processing instance.
  36688. * @return The cloned image processing
  36689. */
  36690. ImageProcessingConfiguration.prototype.clone = function () {
  36691. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  36692. };
  36693. /**
  36694. * Serializes the current image processing instance to a json representation.
  36695. * @return a JSON representation
  36696. */
  36697. ImageProcessingConfiguration.prototype.serialize = function () {
  36698. return BABYLON.SerializationHelper.Serialize(this);
  36699. };
  36700. /**
  36701. * Parses the image processing from a json representation.
  36702. * @param source the JSON source to parse
  36703. * @return The parsed image processing
  36704. */
  36705. ImageProcessingConfiguration.Parse = function (source) {
  36706. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  36707. };
  36708. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  36709. /**
  36710. * Used to apply the vignette as a mix with the pixel color.
  36711. */
  36712. get: function () {
  36713. return this._VIGNETTEMODE_MULTIPLY;
  36714. },
  36715. enumerable: true,
  36716. configurable: true
  36717. });
  36718. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  36719. /**
  36720. * Used to apply the vignette as a replacement of the pixel color.
  36721. */
  36722. get: function () {
  36723. return this._VIGNETTEMODE_OPAQUE;
  36724. },
  36725. enumerable: true,
  36726. configurable: true
  36727. });
  36728. // Static constants associated to the image processing.
  36729. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  36730. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  36731. __decorate([
  36732. BABYLON.serializeAsColorCurves()
  36733. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  36734. __decorate([
  36735. BABYLON.serialize()
  36736. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  36737. __decorate([
  36738. BABYLON.serializeAsTexture()
  36739. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  36740. __decorate([
  36741. BABYLON.serialize()
  36742. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  36743. __decorate([
  36744. BABYLON.serialize()
  36745. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  36746. __decorate([
  36747. BABYLON.serialize()
  36748. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  36749. __decorate([
  36750. BABYLON.serialize()
  36751. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  36752. __decorate([
  36753. BABYLON.serialize()
  36754. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  36755. __decorate([
  36756. BABYLON.serialize()
  36757. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  36758. __decorate([
  36759. BABYLON.serialize()
  36760. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  36761. __decorate([
  36762. BABYLON.serialize()
  36763. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  36764. __decorate([
  36765. BABYLON.serialize()
  36766. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  36767. __decorate([
  36768. BABYLON.serialize()
  36769. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  36770. __decorate([
  36771. BABYLON.serializeAsColor4()
  36772. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  36773. __decorate([
  36774. BABYLON.serialize()
  36775. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  36776. __decorate([
  36777. BABYLON.serialize()
  36778. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  36779. __decorate([
  36780. BABYLON.serialize()
  36781. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  36782. __decorate([
  36783. BABYLON.serialize()
  36784. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  36785. __decorate([
  36786. BABYLON.serialize()
  36787. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  36788. return ImageProcessingConfiguration;
  36789. }());
  36790. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  36791. })(BABYLON || (BABYLON = {}));
  36792. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  36793. var BABYLON;
  36794. (function (BABYLON) {
  36795. /**
  36796. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  36797. * It can help converting any input color in a desired output one. This can then be used to create effects
  36798. * from sepia, black and white to sixties or futuristic rendering...
  36799. *
  36800. * The only supported format is currently 3dl.
  36801. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  36802. */
  36803. var ColorGradingTexture = /** @class */ (function (_super) {
  36804. __extends(ColorGradingTexture, _super);
  36805. /**
  36806. * Instantiates a ColorGradingTexture from the following parameters.
  36807. *
  36808. * @param url The location of the color gradind data (currently only supporting 3dl)
  36809. * @param scene The scene the texture will be used in
  36810. */
  36811. function ColorGradingTexture(url, scene) {
  36812. var _this = _super.call(this, scene) || this;
  36813. if (!url) {
  36814. return _this;
  36815. }
  36816. _this._engine = scene.getEngine();
  36817. _this._textureMatrix = BABYLON.Matrix.Identity();
  36818. _this.name = url;
  36819. _this.url = url;
  36820. _this.hasAlpha = false;
  36821. _this.isCube = false;
  36822. _this.is3D = _this._engine.webGLVersion > 1;
  36823. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  36824. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  36825. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  36826. _this.anisotropicFilteringLevel = 1;
  36827. _this._texture = _this._getFromCache(url, true);
  36828. if (!_this._texture) {
  36829. if (!scene.useDelayedTextureLoading) {
  36830. _this.loadTexture();
  36831. }
  36832. else {
  36833. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  36834. }
  36835. }
  36836. return _this;
  36837. }
  36838. /**
  36839. * Returns the texture matrix used in most of the material.
  36840. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  36841. */
  36842. ColorGradingTexture.prototype.getTextureMatrix = function () {
  36843. return this._textureMatrix;
  36844. };
  36845. /**
  36846. * Occurs when the file being loaded is a .3dl LUT file.
  36847. */
  36848. ColorGradingTexture.prototype.load3dlTexture = function () {
  36849. var engine = this._engine;
  36850. var texture;
  36851. if (engine.webGLVersion === 1) {
  36852. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  36853. }
  36854. else {
  36855. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  36856. }
  36857. this._texture = texture;
  36858. var callback = function (text) {
  36859. if (typeof text !== "string") {
  36860. return;
  36861. }
  36862. var data = null;
  36863. var tempData = null;
  36864. var line;
  36865. var lines = text.split('\n');
  36866. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  36867. var maxColor = 0;
  36868. for (var i = 0; i < lines.length; i++) {
  36869. line = lines[i];
  36870. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  36871. continue;
  36872. if (line.indexOf('#') === 0)
  36873. continue;
  36874. var words = line.split(" ");
  36875. if (size === 0) {
  36876. // Number of space + one
  36877. size = words.length;
  36878. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  36879. tempData = new Float32Array(size * size * size * 4);
  36880. continue;
  36881. }
  36882. if (size != 0) {
  36883. var r = Math.max(parseInt(words[0]), 0);
  36884. var g = Math.max(parseInt(words[1]), 0);
  36885. var b = Math.max(parseInt(words[2]), 0);
  36886. maxColor = Math.max(r, maxColor);
  36887. maxColor = Math.max(g, maxColor);
  36888. maxColor = Math.max(b, maxColor);
  36889. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  36890. if (tempData) {
  36891. tempData[pixelStorageIndex + 0] = r;
  36892. tempData[pixelStorageIndex + 1] = g;
  36893. tempData[pixelStorageIndex + 2] = b;
  36894. }
  36895. pixelIndexSlice++;
  36896. if (pixelIndexSlice % size == 0) {
  36897. pixelIndexH++;
  36898. pixelIndexSlice = 0;
  36899. if (pixelIndexH % size == 0) {
  36900. pixelIndexW++;
  36901. pixelIndexH = 0;
  36902. }
  36903. }
  36904. }
  36905. }
  36906. if (tempData && data) {
  36907. for (var i = 0; i < tempData.length; i++) {
  36908. if (i > 0 && (i + 1) % 4 === 0) {
  36909. data[i] = 255;
  36910. }
  36911. else {
  36912. var value = tempData[i];
  36913. data[i] = (value / maxColor * 255);
  36914. }
  36915. }
  36916. }
  36917. if (texture.is3D) {
  36918. texture.updateSize(size, size, size);
  36919. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  36920. }
  36921. else {
  36922. texture.updateSize(size * size, size);
  36923. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  36924. }
  36925. };
  36926. var scene = this.getScene();
  36927. if (scene) {
  36928. scene._loadFile(this.url, callback);
  36929. }
  36930. else {
  36931. this._engine._loadFile(this.url, callback);
  36932. }
  36933. return this._texture;
  36934. };
  36935. /**
  36936. * Starts the loading process of the texture.
  36937. */
  36938. ColorGradingTexture.prototype.loadTexture = function () {
  36939. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  36940. this.load3dlTexture();
  36941. }
  36942. };
  36943. /**
  36944. * Clones the color gradind texture.
  36945. */
  36946. ColorGradingTexture.prototype.clone = function () {
  36947. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  36948. // Base texture
  36949. newTexture.level = this.level;
  36950. return newTexture;
  36951. };
  36952. /**
  36953. * Called during delayed load for textures.
  36954. */
  36955. ColorGradingTexture.prototype.delayLoad = function () {
  36956. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  36957. return;
  36958. }
  36959. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  36960. this._texture = this._getFromCache(this.url, true);
  36961. if (!this._texture) {
  36962. this.loadTexture();
  36963. }
  36964. };
  36965. /**
  36966. * Parses a color grading texture serialized by Babylon.
  36967. * @param parsedTexture The texture information being parsedTexture
  36968. * @param scene The scene to load the texture in
  36969. * @param rootUrl The root url of the data assets to load
  36970. * @return A color gradind texture
  36971. */
  36972. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  36973. var texture = null;
  36974. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  36975. texture = new ColorGradingTexture(parsedTexture.name, scene);
  36976. texture.name = parsedTexture.name;
  36977. texture.level = parsedTexture.level;
  36978. }
  36979. return texture;
  36980. };
  36981. /**
  36982. * Serializes the LUT texture to json format.
  36983. */
  36984. ColorGradingTexture.prototype.serialize = function () {
  36985. if (!this.name) {
  36986. return null;
  36987. }
  36988. var serializationObject = {};
  36989. serializationObject.name = this.name;
  36990. serializationObject.level = this.level;
  36991. serializationObject.customType = "BABYLON.ColorGradingTexture";
  36992. return serializationObject;
  36993. };
  36994. /**
  36995. * Empty line regex stored for GC.
  36996. */
  36997. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  36998. return ColorGradingTexture;
  36999. }(BABYLON.BaseTexture));
  37000. BABYLON.ColorGradingTexture = ColorGradingTexture;
  37001. })(BABYLON || (BABYLON = {}));
  37002. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  37003. var BABYLON;
  37004. (function (BABYLON) {
  37005. /**
  37006. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  37007. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  37008. * 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;
  37009. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  37010. */
  37011. var ColorCurves = /** @class */ (function () {
  37012. function ColorCurves() {
  37013. this._dirty = true;
  37014. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  37015. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  37016. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  37017. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  37018. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  37019. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  37020. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  37021. this._globalHue = 30;
  37022. this._globalDensity = 0;
  37023. this._globalSaturation = 0;
  37024. this._globalExposure = 0;
  37025. this._highlightsHue = 30;
  37026. this._highlightsDensity = 0;
  37027. this._highlightsSaturation = 0;
  37028. this._highlightsExposure = 0;
  37029. this._midtonesHue = 30;
  37030. this._midtonesDensity = 0;
  37031. this._midtonesSaturation = 0;
  37032. this._midtonesExposure = 0;
  37033. this._shadowsHue = 30;
  37034. this._shadowsDensity = 0;
  37035. this._shadowsSaturation = 0;
  37036. this._shadowsExposure = 0;
  37037. }
  37038. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  37039. /**
  37040. * Gets the global Hue value.
  37041. * 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).
  37042. */
  37043. get: function () {
  37044. return this._globalHue;
  37045. },
  37046. /**
  37047. * Sets the global Hue value.
  37048. * 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).
  37049. */
  37050. set: function (value) {
  37051. this._globalHue = value;
  37052. this._dirty = true;
  37053. },
  37054. enumerable: true,
  37055. configurable: true
  37056. });
  37057. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  37058. /**
  37059. * Gets the global Density value.
  37060. * 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.
  37061. * Values less than zero provide a filter of opposite hue.
  37062. */
  37063. get: function () {
  37064. return this._globalDensity;
  37065. },
  37066. /**
  37067. * Sets the global Density value.
  37068. * 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.
  37069. * Values less than zero provide a filter of opposite hue.
  37070. */
  37071. set: function (value) {
  37072. this._globalDensity = value;
  37073. this._dirty = true;
  37074. },
  37075. enumerable: true,
  37076. configurable: true
  37077. });
  37078. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  37079. /**
  37080. * Gets the global Saturation value.
  37081. * 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.
  37082. */
  37083. get: function () {
  37084. return this._globalSaturation;
  37085. },
  37086. /**
  37087. * Sets the global Saturation value.
  37088. * 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.
  37089. */
  37090. set: function (value) {
  37091. this._globalSaturation = value;
  37092. this._dirty = true;
  37093. },
  37094. enumerable: true,
  37095. configurable: true
  37096. });
  37097. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  37098. /**
  37099. * Gets the highlights Hue value.
  37100. * 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).
  37101. */
  37102. get: function () {
  37103. return this._highlightsHue;
  37104. },
  37105. /**
  37106. * Sets the highlights Hue value.
  37107. * 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).
  37108. */
  37109. set: function (value) {
  37110. this._highlightsHue = value;
  37111. this._dirty = true;
  37112. },
  37113. enumerable: true,
  37114. configurable: true
  37115. });
  37116. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  37117. /**
  37118. * Gets the highlights Density value.
  37119. * 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.
  37120. * Values less than zero provide a filter of opposite hue.
  37121. */
  37122. get: function () {
  37123. return this._highlightsDensity;
  37124. },
  37125. /**
  37126. * Sets the highlights Density value.
  37127. * 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.
  37128. * Values less than zero provide a filter of opposite hue.
  37129. */
  37130. set: function (value) {
  37131. this._highlightsDensity = value;
  37132. this._dirty = true;
  37133. },
  37134. enumerable: true,
  37135. configurable: true
  37136. });
  37137. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  37138. /**
  37139. * Gets the highlights Saturation value.
  37140. * 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.
  37141. */
  37142. get: function () {
  37143. return this._highlightsSaturation;
  37144. },
  37145. /**
  37146. * Sets the highlights Saturation value.
  37147. * 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.
  37148. */
  37149. set: function (value) {
  37150. this._highlightsSaturation = value;
  37151. this._dirty = true;
  37152. },
  37153. enumerable: true,
  37154. configurable: true
  37155. });
  37156. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  37157. /**
  37158. * Gets the highlights Exposure value.
  37159. * 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.
  37160. */
  37161. get: function () {
  37162. return this._highlightsExposure;
  37163. },
  37164. /**
  37165. * Sets the highlights Exposure value.
  37166. * 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.
  37167. */
  37168. set: function (value) {
  37169. this._highlightsExposure = value;
  37170. this._dirty = true;
  37171. },
  37172. enumerable: true,
  37173. configurable: true
  37174. });
  37175. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  37176. /**
  37177. * Gets the midtones Hue value.
  37178. * 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).
  37179. */
  37180. get: function () {
  37181. return this._midtonesHue;
  37182. },
  37183. /**
  37184. * Sets the midtones Hue value.
  37185. * 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).
  37186. */
  37187. set: function (value) {
  37188. this._midtonesHue = value;
  37189. this._dirty = true;
  37190. },
  37191. enumerable: true,
  37192. configurable: true
  37193. });
  37194. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  37195. /**
  37196. * Gets the midtones Density value.
  37197. * 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.
  37198. * Values less than zero provide a filter of opposite hue.
  37199. */
  37200. get: function () {
  37201. return this._midtonesDensity;
  37202. },
  37203. /**
  37204. * Sets the midtones Density value.
  37205. * 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.
  37206. * Values less than zero provide a filter of opposite hue.
  37207. */
  37208. set: function (value) {
  37209. this._midtonesDensity = value;
  37210. this._dirty = true;
  37211. },
  37212. enumerable: true,
  37213. configurable: true
  37214. });
  37215. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  37216. /**
  37217. * Gets the midtones Saturation value.
  37218. * 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.
  37219. */
  37220. get: function () {
  37221. return this._midtonesSaturation;
  37222. },
  37223. /**
  37224. * Sets the midtones Saturation value.
  37225. * 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.
  37226. */
  37227. set: function (value) {
  37228. this._midtonesSaturation = value;
  37229. this._dirty = true;
  37230. },
  37231. enumerable: true,
  37232. configurable: true
  37233. });
  37234. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  37235. /**
  37236. * Gets the midtones Exposure value.
  37237. * 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.
  37238. */
  37239. get: function () {
  37240. return this._midtonesExposure;
  37241. },
  37242. /**
  37243. * Sets the midtones Exposure value.
  37244. * 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.
  37245. */
  37246. set: function (value) {
  37247. this._midtonesExposure = value;
  37248. this._dirty = true;
  37249. },
  37250. enumerable: true,
  37251. configurable: true
  37252. });
  37253. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  37254. /**
  37255. * Gets the shadows Hue value.
  37256. * 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).
  37257. */
  37258. get: function () {
  37259. return this._shadowsHue;
  37260. },
  37261. /**
  37262. * Sets the shadows Hue value.
  37263. * 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).
  37264. */
  37265. set: function (value) {
  37266. this._shadowsHue = value;
  37267. this._dirty = true;
  37268. },
  37269. enumerable: true,
  37270. configurable: true
  37271. });
  37272. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  37273. /**
  37274. * Gets the shadows Density value.
  37275. * 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.
  37276. * Values less than zero provide a filter of opposite hue.
  37277. */
  37278. get: function () {
  37279. return this._shadowsDensity;
  37280. },
  37281. /**
  37282. * Sets the shadows Density value.
  37283. * 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.
  37284. * Values less than zero provide a filter of opposite hue.
  37285. */
  37286. set: function (value) {
  37287. this._shadowsDensity = value;
  37288. this._dirty = true;
  37289. },
  37290. enumerable: true,
  37291. configurable: true
  37292. });
  37293. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  37294. /**
  37295. * Gets the shadows Saturation value.
  37296. * 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.
  37297. */
  37298. get: function () {
  37299. return this._shadowsSaturation;
  37300. },
  37301. /**
  37302. * Sets the shadows Saturation value.
  37303. * 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.
  37304. */
  37305. set: function (value) {
  37306. this._shadowsSaturation = value;
  37307. this._dirty = true;
  37308. },
  37309. enumerable: true,
  37310. configurable: true
  37311. });
  37312. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  37313. /**
  37314. * Gets the shadows Exposure value.
  37315. * 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.
  37316. */
  37317. get: function () {
  37318. return this._shadowsExposure;
  37319. },
  37320. /**
  37321. * Sets the shadows Exposure value.
  37322. * 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.
  37323. */
  37324. set: function (value) {
  37325. this._shadowsExposure = value;
  37326. this._dirty = true;
  37327. },
  37328. enumerable: true,
  37329. configurable: true
  37330. });
  37331. ColorCurves.prototype.getClassName = function () {
  37332. return "ColorCurves";
  37333. };
  37334. /**
  37335. * Binds the color curves to the shader.
  37336. * @param colorCurves The color curve to bind
  37337. * @param effect The effect to bind to
  37338. */
  37339. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  37340. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  37341. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  37342. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  37343. if (colorCurves._dirty) {
  37344. colorCurves._dirty = false;
  37345. // Fill in global info.
  37346. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  37347. // Compute highlights info.
  37348. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  37349. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  37350. // Compute midtones info.
  37351. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  37352. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  37353. // Compute shadows info.
  37354. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  37355. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  37356. // Compute deltas (neutral is midtones).
  37357. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  37358. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  37359. }
  37360. if (effect) {
  37361. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  37362. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  37363. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  37364. }
  37365. };
  37366. /**
  37367. * Prepare the list of uniforms associated with the ColorCurves effects.
  37368. * @param uniformsList The list of uniforms used in the effect
  37369. */
  37370. ColorCurves.PrepareUniforms = function (uniformsList) {
  37371. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  37372. };
  37373. /**
  37374. * Returns color grading data based on a hue, density, saturation and exposure value.
  37375. * @param filterHue The hue of the color filter.
  37376. * @param filterDensity The density of the color filter.
  37377. * @param saturation The saturation.
  37378. * @param exposure The exposure.
  37379. * @param result The result data container.
  37380. */
  37381. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  37382. if (hue == null) {
  37383. return;
  37384. }
  37385. hue = ColorCurves.clamp(hue, 0, 360);
  37386. density = ColorCurves.clamp(density, -100, 100);
  37387. saturation = ColorCurves.clamp(saturation, -100, 100);
  37388. exposure = ColorCurves.clamp(exposure, -100, 100);
  37389. // Remap the slider/config filter density with non-linear mapping and also scale by half
  37390. // so that the maximum filter density is only 50% control. This provides fine control
  37391. // for small values and reasonable range.
  37392. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  37393. density *= 0.5;
  37394. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  37395. if (density < 0) {
  37396. density *= -1;
  37397. hue = (hue + 180) % 360;
  37398. }
  37399. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  37400. result.scaleToRef(2, result);
  37401. result.a = 1 + 0.01 * saturation;
  37402. };
  37403. /**
  37404. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  37405. * @param value The input slider value in range [-100,100].
  37406. * @returns Adjusted value.
  37407. */
  37408. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  37409. value /= 100;
  37410. var x = Math.abs(value);
  37411. x = Math.pow(x, 2);
  37412. if (value < 0) {
  37413. x *= -1;
  37414. }
  37415. x *= 100;
  37416. return x;
  37417. };
  37418. /**
  37419. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  37420. * @param hue The hue (H) input.
  37421. * @param saturation The saturation (S) input.
  37422. * @param brightness The brightness (B) input.
  37423. * @result An RGBA color represented as Vector4.
  37424. */
  37425. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  37426. var h = ColorCurves.clamp(hue, 0, 360);
  37427. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  37428. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  37429. if (s === 0) {
  37430. result.r = v;
  37431. result.g = v;
  37432. result.b = v;
  37433. }
  37434. else {
  37435. // sector 0 to 5
  37436. h /= 60;
  37437. var i = Math.floor(h);
  37438. // fractional part of h
  37439. var f = h - i;
  37440. var p = v * (1 - s);
  37441. var q = v * (1 - s * f);
  37442. var t = v * (1 - s * (1 - f));
  37443. switch (i) {
  37444. case 0:
  37445. result.r = v;
  37446. result.g = t;
  37447. result.b = p;
  37448. break;
  37449. case 1:
  37450. result.r = q;
  37451. result.g = v;
  37452. result.b = p;
  37453. break;
  37454. case 2:
  37455. result.r = p;
  37456. result.g = v;
  37457. result.b = t;
  37458. break;
  37459. case 3:
  37460. result.r = p;
  37461. result.g = q;
  37462. result.b = v;
  37463. break;
  37464. case 4:
  37465. result.r = t;
  37466. result.g = p;
  37467. result.b = v;
  37468. break;
  37469. default:// case 5:
  37470. result.r = v;
  37471. result.g = p;
  37472. result.b = q;
  37473. break;
  37474. }
  37475. }
  37476. result.a = 1;
  37477. };
  37478. /**
  37479. * Returns a value clamped between min and max
  37480. * @param value The value to clamp
  37481. * @param min The minimum of value
  37482. * @param max The maximum of value
  37483. * @returns The clamped value.
  37484. */
  37485. ColorCurves.clamp = function (value, min, max) {
  37486. return Math.min(Math.max(value, min), max);
  37487. };
  37488. /**
  37489. * Clones the current color curve instance.
  37490. * @return The cloned curves
  37491. */
  37492. ColorCurves.prototype.clone = function () {
  37493. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  37494. };
  37495. /**
  37496. * Serializes the current color curve instance to a json representation.
  37497. * @return a JSON representation
  37498. */
  37499. ColorCurves.prototype.serialize = function () {
  37500. return BABYLON.SerializationHelper.Serialize(this);
  37501. };
  37502. /**
  37503. * Parses the color curve from a json representation.
  37504. * @param source the JSON source to parse
  37505. * @return The parsed curves
  37506. */
  37507. ColorCurves.Parse = function (source) {
  37508. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  37509. };
  37510. __decorate([
  37511. BABYLON.serialize()
  37512. ], ColorCurves.prototype, "_globalHue", void 0);
  37513. __decorate([
  37514. BABYLON.serialize()
  37515. ], ColorCurves.prototype, "_globalDensity", void 0);
  37516. __decorate([
  37517. BABYLON.serialize()
  37518. ], ColorCurves.prototype, "_globalSaturation", void 0);
  37519. __decorate([
  37520. BABYLON.serialize()
  37521. ], ColorCurves.prototype, "_globalExposure", void 0);
  37522. __decorate([
  37523. BABYLON.serialize()
  37524. ], ColorCurves.prototype, "_highlightsHue", void 0);
  37525. __decorate([
  37526. BABYLON.serialize()
  37527. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  37528. __decorate([
  37529. BABYLON.serialize()
  37530. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  37531. __decorate([
  37532. BABYLON.serialize()
  37533. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  37534. __decorate([
  37535. BABYLON.serialize()
  37536. ], ColorCurves.prototype, "_midtonesHue", void 0);
  37537. __decorate([
  37538. BABYLON.serialize()
  37539. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  37540. __decorate([
  37541. BABYLON.serialize()
  37542. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  37543. __decorate([
  37544. BABYLON.serialize()
  37545. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  37546. return ColorCurves;
  37547. }());
  37548. BABYLON.ColorCurves = ColorCurves;
  37549. })(BABYLON || (BABYLON = {}));
  37550. //# sourceMappingURL=babylon.colorCurves.js.map
  37551. //# sourceMappingURL=babylon.behavior.js.map
  37552. var BABYLON;
  37553. (function (BABYLON) {
  37554. /**
  37555. * "Static Class" containing the most commonly used helper while dealing with material for
  37556. * rendering purpose.
  37557. *
  37558. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  37559. *
  37560. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  37561. */
  37562. var MaterialHelper = /** @class */ (function () {
  37563. function MaterialHelper() {
  37564. }
  37565. /**
  37566. * Bind the current view position to an effect.
  37567. * @param effect The effect to be bound
  37568. * @param scene The scene the eyes position is used from
  37569. */
  37570. MaterialHelper.BindEyePosition = function (effect, scene) {
  37571. if (scene._forcedViewPosition) {
  37572. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  37573. return;
  37574. }
  37575. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  37576. };
  37577. /**
  37578. * Helps preparing the defines values about the UVs in used in the effect.
  37579. * UVs are shared as much as we can accross chanels in the shaders.
  37580. * @param texture The texture we are preparing the UVs for
  37581. * @param defines The defines to update
  37582. * @param key The chanel key "diffuse", "specular"... used in the shader
  37583. */
  37584. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  37585. defines._needUVs = true;
  37586. defines[key] = true;
  37587. if (texture.getTextureMatrix().isIdentity(true)) {
  37588. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  37589. if (texture.coordinatesIndex === 0) {
  37590. defines["MAINUV1"] = true;
  37591. }
  37592. else {
  37593. defines["MAINUV2"] = true;
  37594. }
  37595. }
  37596. else {
  37597. defines[key + "DIRECTUV"] = 0;
  37598. }
  37599. };
  37600. /**
  37601. * Binds a texture matrix value to its corrsponding uniform
  37602. * @param texture The texture to bind the matrix for
  37603. * @param uniformBuffer The uniform buffer receivin the data
  37604. * @param key The chanel key "diffuse", "specular"... used in the shader
  37605. */
  37606. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  37607. var matrix = texture.getTextureMatrix();
  37608. if (!matrix.isIdentity(true)) {
  37609. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  37610. }
  37611. };
  37612. /**
  37613. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  37614. * @param mesh defines the current mesh
  37615. * @param scene defines the current scene
  37616. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  37617. * @param pointsCloud defines if point cloud rendering has to be turned on
  37618. * @param fogEnabled defines if fog has to be turned on
  37619. * @param alphaTest defines if alpha testing has to be turned on
  37620. * @param defines defines the current list of defines
  37621. */
  37622. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  37623. if (defines._areMiscDirty) {
  37624. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  37625. defines["POINTSIZE"] = (pointsCloud || scene.forcePointsCloud);
  37626. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  37627. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  37628. defines["ALPHATEST"] = alphaTest;
  37629. }
  37630. };
  37631. /**
  37632. * Helper used to prepare the list of defines associated with frame values for shader compilation
  37633. * @param scene defines the current scene
  37634. * @param engine defines the current engine
  37635. * @param defines specifies the list of active defines
  37636. * @param useInstances defines if instances have to be turned on
  37637. * @param useClipPlane defines if clip plane have to be turned on
  37638. */
  37639. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  37640. if (useClipPlane === void 0) { useClipPlane = null; }
  37641. var changed = false;
  37642. if (useClipPlane == null) {
  37643. useClipPlane = (scene.clipPlane !== undefined && scene.clipPlane !== null);
  37644. }
  37645. if (defines["CLIPPLANE"] !== useClipPlane) {
  37646. defines["CLIPPLANE"] = useClipPlane;
  37647. changed = true;
  37648. }
  37649. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  37650. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  37651. changed = true;
  37652. }
  37653. if (defines["INSTANCES"] !== useInstances) {
  37654. defines["INSTANCES"] = useInstances;
  37655. changed = true;
  37656. }
  37657. if (changed) {
  37658. defines.markAsUnprocessed();
  37659. }
  37660. };
  37661. /**
  37662. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  37663. * @param mesh The mesh containing the geometry data we will draw
  37664. * @param defines The defines to update
  37665. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  37666. * @param useBones Precise whether bones should be used or not (override mesh info)
  37667. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  37668. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  37669. * @returns false if defines are considered not dirty and have not been checked
  37670. */
  37671. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  37672. if (useMorphTargets === void 0) { useMorphTargets = false; }
  37673. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  37674. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  37675. return false;
  37676. }
  37677. defines._normals = defines._needNormals;
  37678. defines._uvs = defines._needUVs;
  37679. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  37680. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  37681. defines["TANGENT"] = true;
  37682. }
  37683. if (defines._needUVs) {
  37684. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  37685. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  37686. }
  37687. else {
  37688. defines["UV1"] = false;
  37689. defines["UV2"] = false;
  37690. }
  37691. if (useVertexColor) {
  37692. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  37693. defines["VERTEXCOLOR"] = hasVertexColors;
  37694. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  37695. }
  37696. if (useBones) {
  37697. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  37698. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  37699. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  37700. }
  37701. else {
  37702. defines["NUM_BONE_INFLUENCERS"] = 0;
  37703. defines["BonesPerMesh"] = 0;
  37704. }
  37705. }
  37706. if (useMorphTargets) {
  37707. var manager = mesh.morphTargetManager;
  37708. if (manager) {
  37709. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  37710. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  37711. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  37712. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  37713. }
  37714. else {
  37715. defines["MORPHTARGETS_TANGENT"] = false;
  37716. defines["MORPHTARGETS_NORMAL"] = false;
  37717. defines["MORPHTARGETS"] = false;
  37718. defines["NUM_MORPH_INFLUENCERS"] = 0;
  37719. }
  37720. }
  37721. return true;
  37722. };
  37723. /**
  37724. * Prepares the defines related to the light information passed in parameter
  37725. * @param scene The scene we are intending to draw
  37726. * @param mesh The mesh the effect is compiling for
  37727. * @param defines The defines to update
  37728. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  37729. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  37730. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  37731. * @returns true if normals will be required for the rest of the effect
  37732. */
  37733. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  37734. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  37735. if (disableLighting === void 0) { disableLighting = false; }
  37736. if (!defines._areLightsDirty) {
  37737. return defines._needNormals;
  37738. }
  37739. var lightIndex = 0;
  37740. var needNormals = false;
  37741. var needRebuild = false;
  37742. var lightmapMode = false;
  37743. var shadowEnabled = false;
  37744. var specularEnabled = false;
  37745. if (scene.lightsEnabled && !disableLighting) {
  37746. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  37747. var light = _a[_i];
  37748. needNormals = true;
  37749. if (defines["LIGHT" + lightIndex] === undefined) {
  37750. needRebuild = true;
  37751. }
  37752. defines["LIGHT" + lightIndex] = true;
  37753. defines["SPOTLIGHT" + lightIndex] = false;
  37754. defines["HEMILIGHT" + lightIndex] = false;
  37755. defines["POINTLIGHT" + lightIndex] = false;
  37756. defines["DIRLIGHT" + lightIndex] = false;
  37757. var type;
  37758. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  37759. type = "SPOTLIGHT" + lightIndex;
  37760. var spotLight = light;
  37761. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = spotLight.projectionTexture ? spotLight.projectionTexture.isReady() : false;
  37762. }
  37763. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  37764. type = "HEMILIGHT" + lightIndex;
  37765. }
  37766. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  37767. type = "POINTLIGHT" + lightIndex;
  37768. }
  37769. else {
  37770. type = "DIRLIGHT" + lightIndex;
  37771. }
  37772. defines[type] = true;
  37773. // Specular
  37774. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  37775. specularEnabled = true;
  37776. }
  37777. // Shadows
  37778. defines["SHADOW" + lightIndex] = false;
  37779. defines["SHADOWPCF" + lightIndex] = false;
  37780. defines["SHADOWESM" + lightIndex] = false;
  37781. defines["SHADOWCUBE" + lightIndex] = false;
  37782. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  37783. var shadowGenerator = light.getShadowGenerator();
  37784. if (shadowGenerator) {
  37785. shadowEnabled = true;
  37786. shadowGenerator.prepareDefines(defines, lightIndex);
  37787. }
  37788. }
  37789. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  37790. lightmapMode = true;
  37791. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  37792. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  37793. }
  37794. else {
  37795. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  37796. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  37797. }
  37798. lightIndex++;
  37799. if (lightIndex === maxSimultaneousLights)
  37800. break;
  37801. }
  37802. }
  37803. defines["SPECULARTERM"] = specularEnabled;
  37804. defines["SHADOWS"] = shadowEnabled;
  37805. // Resetting all other lights if any
  37806. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  37807. if (defines["LIGHT" + index] !== undefined) {
  37808. defines["LIGHT" + index] = false;
  37809. defines["HEMILIGHT" + lightIndex] = false;
  37810. defines["POINTLIGHT" + lightIndex] = false;
  37811. defines["DIRLIGHT" + lightIndex] = false;
  37812. defines["SPOTLIGHT" + lightIndex] = false;
  37813. defines["SHADOW" + lightIndex] = false;
  37814. }
  37815. }
  37816. var caps = scene.getEngine().getCaps();
  37817. if (defines["SHADOWFLOAT"] === undefined) {
  37818. needRebuild = true;
  37819. }
  37820. defines["SHADOWFLOAT"] = shadowEnabled &&
  37821. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  37822. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  37823. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  37824. if (needRebuild) {
  37825. defines.rebuild();
  37826. }
  37827. return needNormals;
  37828. };
  37829. /**
  37830. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  37831. * that won t be acctive due to defines being turned off.
  37832. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  37833. * @param samplersList The samplers list
  37834. * @param defines The defines helping in the list generation
  37835. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  37836. */
  37837. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  37838. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  37839. var uniformsList;
  37840. var uniformBuffersList = null;
  37841. if (uniformsListOrOptions.uniformsNames) {
  37842. var options = uniformsListOrOptions;
  37843. uniformsList = options.uniformsNames;
  37844. uniformBuffersList = options.uniformBuffersNames;
  37845. samplersList = options.samplers;
  37846. defines = options.defines;
  37847. maxSimultaneousLights = options.maxSimultaneousLights;
  37848. }
  37849. else {
  37850. uniformsList = uniformsListOrOptions;
  37851. if (!samplersList) {
  37852. samplersList = [];
  37853. }
  37854. }
  37855. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  37856. if (!defines["LIGHT" + lightIndex]) {
  37857. break;
  37858. }
  37859. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  37860. if (uniformBuffersList) {
  37861. uniformBuffersList.push("Light" + lightIndex);
  37862. }
  37863. samplersList.push("shadowSampler" + lightIndex);
  37864. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  37865. samplersList.push("projectionLightSampler" + lightIndex);
  37866. uniformsList.push("textureProjectionMatrix" + lightIndex);
  37867. }
  37868. }
  37869. if (defines["NUM_MORPH_INFLUENCERS"]) {
  37870. uniformsList.push("morphTargetInfluences");
  37871. }
  37872. };
  37873. /**
  37874. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  37875. * @param defines The defines to update while falling back
  37876. * @param fallbacks The authorized effect fallbacks
  37877. * @param maxSimultaneousLights The maximum number of lights allowed
  37878. * @param rank the current rank of the Effect
  37879. * @returns The newly affected rank
  37880. */
  37881. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  37882. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  37883. if (rank === void 0) { rank = 0; }
  37884. var lightFallbackRank = 0;
  37885. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  37886. if (!defines["LIGHT" + lightIndex]) {
  37887. break;
  37888. }
  37889. if (lightIndex > 0) {
  37890. lightFallbackRank = rank + lightIndex;
  37891. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  37892. }
  37893. if (!defines["SHADOWS"]) {
  37894. if (defines["SHADOW" + lightIndex]) {
  37895. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  37896. }
  37897. if (defines["SHADOWPCF" + lightIndex]) {
  37898. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  37899. }
  37900. if (defines["SHADOWESM" + lightIndex]) {
  37901. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  37902. }
  37903. }
  37904. }
  37905. return lightFallbackRank++;
  37906. };
  37907. /**
  37908. * Prepares the list of attributes required for morph targets according to the effect defines.
  37909. * @param attribs The current list of supported attribs
  37910. * @param mesh The mesh to prepare the morph targets attributes for
  37911. * @param defines The current Defines of the effect
  37912. */
  37913. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  37914. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  37915. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  37916. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  37917. var manager = mesh.morphTargetManager;
  37918. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  37919. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  37920. for (var index = 0; index < influencers; index++) {
  37921. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  37922. if (normal) {
  37923. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  37924. }
  37925. if (tangent) {
  37926. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  37927. }
  37928. if (attribs.length > maxAttributesCount) {
  37929. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  37930. }
  37931. }
  37932. }
  37933. };
  37934. /**
  37935. * Prepares the list of attributes required for bones according to the effect defines.
  37936. * @param attribs The current list of supported attribs
  37937. * @param mesh The mesh to prepare the bones attributes for
  37938. * @param defines The current Defines of the effect
  37939. * @param fallbacks The current efffect fallback strategy
  37940. */
  37941. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  37942. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  37943. fallbacks.addCPUSkinningFallback(0, mesh);
  37944. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  37945. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  37946. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  37947. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  37948. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  37949. }
  37950. }
  37951. };
  37952. /**
  37953. * Prepares the list of attributes required for instances according to the effect defines.
  37954. * @param attribs The current list of supported attribs
  37955. * @param defines The current Defines of the effect
  37956. */
  37957. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  37958. if (defines["INSTANCES"]) {
  37959. attribs.push("world0");
  37960. attribs.push("world1");
  37961. attribs.push("world2");
  37962. attribs.push("world3");
  37963. }
  37964. };
  37965. /**
  37966. * Binds the light shadow information to the effect for the given mesh.
  37967. * @param light The light containing the generator
  37968. * @param scene The scene the lights belongs to
  37969. * @param mesh The mesh we are binding the information to render
  37970. * @param lightIndex The light index in the effect used to render the mesh
  37971. * @param effect The effect we are binding the data to
  37972. */
  37973. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  37974. if (light.shadowEnabled && mesh.receiveShadows) {
  37975. var shadowGenerator = light.getShadowGenerator();
  37976. if (shadowGenerator) {
  37977. shadowGenerator.bindShadowLight(lightIndex, effect);
  37978. }
  37979. }
  37980. };
  37981. /**
  37982. * Binds the light information to the effect.
  37983. * @param light The light containing the generator
  37984. * @param effect The effect we are binding the data to
  37985. * @param lightIndex The light index in the effect used to render
  37986. */
  37987. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  37988. light.transferToEffect(effect, lightIndex + "");
  37989. };
  37990. /**
  37991. * Binds the lights information from the scene to the effect for the given mesh.
  37992. * @param scene The scene the lights belongs to
  37993. * @param mesh The mesh we are binding the information to render
  37994. * @param effect The effect we are binding the data to
  37995. * @param defines The generated defines for the effect
  37996. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  37997. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  37998. */
  37999. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  38000. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  38001. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  38002. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  38003. for (var i = 0; i < len; i++) {
  38004. var light = mesh._lightSources[i];
  38005. var iAsString = i.toString();
  38006. var scaledIntensity = light.getScaledIntensity();
  38007. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  38008. MaterialHelper.BindLightProperties(light, effect, i);
  38009. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  38010. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  38011. if (defines["SPECULARTERM"]) {
  38012. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  38013. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  38014. }
  38015. // Shadows
  38016. if (scene.shadowsEnabled) {
  38017. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  38018. }
  38019. light._uniformBuffer.update();
  38020. }
  38021. };
  38022. /**
  38023. * Binds the fog information from the scene to the effect for the given mesh.
  38024. * @param scene The scene the lights belongs to
  38025. * @param mesh The mesh we are binding the information to render
  38026. * @param effect The effect we are binding the data to
  38027. */
  38028. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  38029. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  38030. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  38031. effect.setColor3("vFogColor", scene.fogColor);
  38032. }
  38033. };
  38034. /**
  38035. * Binds the bones information from the mesh to the effect.
  38036. * @param mesh The mesh we are binding the information to render
  38037. * @param effect The effect we are binding the data to
  38038. */
  38039. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  38040. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  38041. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  38042. if (matrices && effect) {
  38043. effect.setMatrices("mBones", matrices);
  38044. }
  38045. }
  38046. };
  38047. /**
  38048. * Binds the morph targets information from the mesh to the effect.
  38049. * @param abstractMesh The mesh we are binding the information to render
  38050. * @param effect The effect we are binding the data to
  38051. */
  38052. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  38053. var manager = abstractMesh.morphTargetManager;
  38054. if (!abstractMesh || !manager) {
  38055. return;
  38056. }
  38057. effect.setFloatArray("morphTargetInfluences", manager.influences);
  38058. };
  38059. /**
  38060. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  38061. * @param defines The generated defines used in the effect
  38062. * @param effect The effect we are binding the data to
  38063. * @param scene The scene we are willing to render with logarithmic scale for
  38064. */
  38065. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  38066. if (defines["LOGARITHMICDEPTH"]) {
  38067. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  38068. }
  38069. };
  38070. /**
  38071. * Binds the clip plane information from the scene to the effect.
  38072. * @param scene The scene the clip plane information are extracted from
  38073. * @param effect The effect we are binding the data to
  38074. */
  38075. MaterialHelper.BindClipPlane = function (effect, scene) {
  38076. if (scene.clipPlane) {
  38077. var clipPlane = scene.clipPlane;
  38078. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  38079. }
  38080. };
  38081. return MaterialHelper;
  38082. }());
  38083. BABYLON.MaterialHelper = MaterialHelper;
  38084. })(BABYLON || (BABYLON = {}));
  38085. //# sourceMappingURL=babylon.materialHelper.js.map
  38086. var BABYLON;
  38087. (function (BABYLON) {
  38088. var PushMaterial = /** @class */ (function (_super) {
  38089. __extends(PushMaterial, _super);
  38090. function PushMaterial(name, scene) {
  38091. var _this = _super.call(this, name, scene) || this;
  38092. _this.storeEffectOnSubMeshes = true;
  38093. return _this;
  38094. }
  38095. PushMaterial.prototype.getEffect = function () {
  38096. return this._activeEffect;
  38097. };
  38098. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  38099. if (!mesh) {
  38100. return false;
  38101. }
  38102. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  38103. return true;
  38104. }
  38105. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  38106. };
  38107. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  38108. this._activeEffect.setMatrix("world", world);
  38109. };
  38110. PushMaterial.prototype.bind = function (world, mesh) {
  38111. if (!mesh) {
  38112. return;
  38113. }
  38114. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  38115. };
  38116. PushMaterial.prototype._afterBind = function (mesh, effect) {
  38117. if (effect === void 0) { effect = null; }
  38118. _super.prototype._afterBind.call(this, mesh);
  38119. this.getScene()._cachedEffect = effect;
  38120. };
  38121. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  38122. if (visibility === void 0) { visibility = 1; }
  38123. return scene.isCachedMaterialInvalid(this, effect, visibility);
  38124. };
  38125. return PushMaterial;
  38126. }(BABYLON.Material));
  38127. BABYLON.PushMaterial = PushMaterial;
  38128. })(BABYLON || (BABYLON = {}));
  38129. //# sourceMappingURL=babylon.pushMaterial.js.map
  38130. var BABYLON;
  38131. (function (BABYLON) {
  38132. /** @ignore */
  38133. var StandardMaterialDefines = /** @class */ (function (_super) {
  38134. __extends(StandardMaterialDefines, _super);
  38135. function StandardMaterialDefines() {
  38136. var _this = _super.call(this) || this;
  38137. _this.MAINUV1 = false;
  38138. _this.MAINUV2 = false;
  38139. _this.DIFFUSE = false;
  38140. _this.DIFFUSEDIRECTUV = 0;
  38141. _this.AMBIENT = false;
  38142. _this.AMBIENTDIRECTUV = 0;
  38143. _this.OPACITY = false;
  38144. _this.OPACITYDIRECTUV = 0;
  38145. _this.OPACITYRGB = false;
  38146. _this.REFLECTION = false;
  38147. _this.EMISSIVE = false;
  38148. _this.EMISSIVEDIRECTUV = 0;
  38149. _this.SPECULAR = false;
  38150. _this.SPECULARDIRECTUV = 0;
  38151. _this.BUMP = false;
  38152. _this.BUMPDIRECTUV = 0;
  38153. _this.PARALLAX = false;
  38154. _this.PARALLAXOCCLUSION = false;
  38155. _this.SPECULAROVERALPHA = false;
  38156. _this.CLIPPLANE = false;
  38157. _this.ALPHATEST = false;
  38158. _this.DEPTHPREPASS = false;
  38159. _this.ALPHAFROMDIFFUSE = false;
  38160. _this.POINTSIZE = false;
  38161. _this.FOG = false;
  38162. _this.SPECULARTERM = false;
  38163. _this.DIFFUSEFRESNEL = false;
  38164. _this.OPACITYFRESNEL = false;
  38165. _this.REFLECTIONFRESNEL = false;
  38166. _this.REFRACTIONFRESNEL = false;
  38167. _this.EMISSIVEFRESNEL = false;
  38168. _this.FRESNEL = false;
  38169. _this.NORMAL = false;
  38170. _this.UV1 = false;
  38171. _this.UV2 = false;
  38172. _this.VERTEXCOLOR = false;
  38173. _this.VERTEXALPHA = false;
  38174. _this.NUM_BONE_INFLUENCERS = 0;
  38175. _this.BonesPerMesh = 0;
  38176. _this.INSTANCES = false;
  38177. _this.GLOSSINESS = false;
  38178. _this.ROUGHNESS = false;
  38179. _this.EMISSIVEASILLUMINATION = false;
  38180. _this.LINKEMISSIVEWITHDIFFUSE = false;
  38181. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  38182. _this.LIGHTMAP = false;
  38183. _this.LIGHTMAPDIRECTUV = 0;
  38184. _this.USELIGHTMAPASSHADOWMAP = false;
  38185. _this.REFLECTIONMAP_3D = false;
  38186. _this.REFLECTIONMAP_SPHERICAL = false;
  38187. _this.REFLECTIONMAP_PLANAR = false;
  38188. _this.REFLECTIONMAP_CUBIC = false;
  38189. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  38190. _this.REFLECTIONMAP_PROJECTION = false;
  38191. _this.REFLECTIONMAP_SKYBOX = false;
  38192. _this.REFLECTIONMAP_EXPLICIT = false;
  38193. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  38194. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  38195. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  38196. _this.INVERTCUBICMAP = false;
  38197. _this.LOGARITHMICDEPTH = false;
  38198. _this.REFRACTION = false;
  38199. _this.REFRACTIONMAP_3D = false;
  38200. _this.REFLECTIONOVERALPHA = false;
  38201. _this.TWOSIDEDLIGHTING = false;
  38202. _this.SHADOWFLOAT = false;
  38203. _this.MORPHTARGETS = false;
  38204. _this.MORPHTARGETS_NORMAL = false;
  38205. _this.MORPHTARGETS_TANGENT = false;
  38206. _this.NUM_MORPH_INFLUENCERS = 0;
  38207. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  38208. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  38209. _this.IMAGEPROCESSING = false;
  38210. _this.VIGNETTE = false;
  38211. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  38212. _this.VIGNETTEBLENDMODEOPAQUE = false;
  38213. _this.TONEMAPPING = false;
  38214. _this.CONTRAST = false;
  38215. _this.COLORCURVES = false;
  38216. _this.COLORGRADING = false;
  38217. _this.COLORGRADING3D = false;
  38218. _this.SAMPLER3DGREENDEPTH = false;
  38219. _this.SAMPLER3DBGRMAP = false;
  38220. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  38221. _this.EXPOSURE = false;
  38222. _this.rebuild();
  38223. return _this;
  38224. }
  38225. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  38226. var modes = [
  38227. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  38228. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  38229. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  38230. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  38231. ];
  38232. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  38233. var mode = modes_1[_i];
  38234. this[mode] = (mode === modeToEnable);
  38235. }
  38236. };
  38237. return StandardMaterialDefines;
  38238. }(BABYLON.MaterialDefines));
  38239. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  38240. var StandardMaterial = /** @class */ (function (_super) {
  38241. __extends(StandardMaterial, _super);
  38242. function StandardMaterial(name, scene) {
  38243. var _this = _super.call(this, name, scene) || this;
  38244. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  38245. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  38246. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  38247. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  38248. _this.specularPower = 64;
  38249. _this._useAlphaFromDiffuseTexture = false;
  38250. _this._useEmissiveAsIllumination = false;
  38251. _this._linkEmissiveWithDiffuse = false;
  38252. _this._useSpecularOverAlpha = false;
  38253. _this._useReflectionOverAlpha = false;
  38254. _this._disableLighting = false;
  38255. _this._useParallax = false;
  38256. _this._useParallaxOcclusion = false;
  38257. _this.parallaxScaleBias = 0.05;
  38258. _this._roughness = 0;
  38259. _this.indexOfRefraction = 0.98;
  38260. _this.invertRefractionY = true;
  38261. _this._useLightmapAsShadowmap = false;
  38262. _this._useReflectionFresnelFromSpecular = false;
  38263. _this._useGlossinessFromSpecularMapAlpha = false;
  38264. _this._maxSimultaneousLights = 4;
  38265. /**
  38266. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  38267. */
  38268. _this._invertNormalMapX = false;
  38269. /**
  38270. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  38271. */
  38272. _this._invertNormalMapY = false;
  38273. /**
  38274. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  38275. */
  38276. _this._twoSidedLighting = false;
  38277. _this._renderTargets = new BABYLON.SmartArray(16);
  38278. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  38279. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  38280. // Setup the default processing configuration to the scene.
  38281. _this._attachImageProcessingConfiguration(null);
  38282. _this.getRenderTargetTextures = function () {
  38283. _this._renderTargets.reset();
  38284. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  38285. _this._renderTargets.push(_this._reflectionTexture);
  38286. }
  38287. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  38288. _this._renderTargets.push(_this._refractionTexture);
  38289. }
  38290. return _this._renderTargets;
  38291. };
  38292. return _this;
  38293. }
  38294. ;
  38295. ;
  38296. ;
  38297. ;
  38298. ;
  38299. ;
  38300. ;
  38301. ;
  38302. ;
  38303. ;
  38304. ;
  38305. ;
  38306. ;
  38307. ;
  38308. ;
  38309. ;
  38310. ;
  38311. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  38312. /**
  38313. * Gets the image processing configuration used either in this material.
  38314. */
  38315. get: function () {
  38316. return this._imageProcessingConfiguration;
  38317. },
  38318. /**
  38319. * Sets the Default image processing configuration used either in the this material.
  38320. *
  38321. * If sets to null, the scene one is in use.
  38322. */
  38323. set: function (value) {
  38324. this._attachImageProcessingConfiguration(value);
  38325. // Ensure the effect will be rebuilt.
  38326. this._markAllSubMeshesAsTexturesDirty();
  38327. },
  38328. enumerable: true,
  38329. configurable: true
  38330. });
  38331. /**
  38332. * Attaches a new image processing configuration to the Standard Material.
  38333. * @param configuration
  38334. */
  38335. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  38336. var _this = this;
  38337. if (configuration === this._imageProcessingConfiguration) {
  38338. return;
  38339. }
  38340. // Detaches observer.
  38341. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  38342. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  38343. }
  38344. // Pick the scene configuration if needed.
  38345. if (!configuration) {
  38346. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  38347. }
  38348. else {
  38349. this._imageProcessingConfiguration = configuration;
  38350. }
  38351. // Attaches observer.
  38352. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  38353. _this._markAllSubMeshesAsImageProcessingDirty();
  38354. });
  38355. };
  38356. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  38357. /**
  38358. * Gets wether the color curves effect is enabled.
  38359. */
  38360. get: function () {
  38361. return this.imageProcessingConfiguration.colorCurvesEnabled;
  38362. },
  38363. /**
  38364. * Sets wether the color curves effect is enabled.
  38365. */
  38366. set: function (value) {
  38367. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  38368. },
  38369. enumerable: true,
  38370. configurable: true
  38371. });
  38372. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  38373. /**
  38374. * Gets wether the color grading effect is enabled.
  38375. */
  38376. get: function () {
  38377. return this.imageProcessingConfiguration.colorGradingEnabled;
  38378. },
  38379. /**
  38380. * Gets wether the color grading effect is enabled.
  38381. */
  38382. set: function (value) {
  38383. this.imageProcessingConfiguration.colorGradingEnabled = value;
  38384. },
  38385. enumerable: true,
  38386. configurable: true
  38387. });
  38388. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  38389. /**
  38390. * Gets wether tonemapping is enabled or not.
  38391. */
  38392. get: function () {
  38393. return this._imageProcessingConfiguration.toneMappingEnabled;
  38394. },
  38395. /**
  38396. * Sets wether tonemapping is enabled or not
  38397. */
  38398. set: function (value) {
  38399. this._imageProcessingConfiguration.toneMappingEnabled = value;
  38400. },
  38401. enumerable: true,
  38402. configurable: true
  38403. });
  38404. ;
  38405. ;
  38406. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  38407. /**
  38408. * The camera exposure used on this material.
  38409. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  38410. * This corresponds to a photographic exposure.
  38411. */
  38412. get: function () {
  38413. return this._imageProcessingConfiguration.exposure;
  38414. },
  38415. /**
  38416. * The camera exposure used on this material.
  38417. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  38418. * This corresponds to a photographic exposure.
  38419. */
  38420. set: function (value) {
  38421. this._imageProcessingConfiguration.exposure = value;
  38422. },
  38423. enumerable: true,
  38424. configurable: true
  38425. });
  38426. ;
  38427. ;
  38428. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  38429. /**
  38430. * Gets The camera contrast used on this material.
  38431. */
  38432. get: function () {
  38433. return this._imageProcessingConfiguration.contrast;
  38434. },
  38435. /**
  38436. * Sets The camera contrast used on this material.
  38437. */
  38438. set: function (value) {
  38439. this._imageProcessingConfiguration.contrast = value;
  38440. },
  38441. enumerable: true,
  38442. configurable: true
  38443. });
  38444. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  38445. /**
  38446. * Gets the Color Grading 2D Lookup Texture.
  38447. */
  38448. get: function () {
  38449. return this._imageProcessingConfiguration.colorGradingTexture;
  38450. },
  38451. /**
  38452. * Sets the Color Grading 2D Lookup Texture.
  38453. */
  38454. set: function (value) {
  38455. this._imageProcessingConfiguration.colorGradingTexture = value;
  38456. },
  38457. enumerable: true,
  38458. configurable: true
  38459. });
  38460. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  38461. /**
  38462. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  38463. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  38464. * 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;
  38465. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  38466. */
  38467. get: function () {
  38468. return this._imageProcessingConfiguration.colorCurves;
  38469. },
  38470. /**
  38471. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  38472. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  38473. * 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;
  38474. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  38475. */
  38476. set: function (value) {
  38477. this._imageProcessingConfiguration.colorCurves = value;
  38478. },
  38479. enumerable: true,
  38480. configurable: true
  38481. });
  38482. StandardMaterial.prototype.getClassName = function () {
  38483. return "StandardMaterial";
  38484. };
  38485. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  38486. get: function () {
  38487. return this._useLogarithmicDepth;
  38488. },
  38489. set: function (value) {
  38490. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  38491. this._markAllSubMeshesAsMiscDirty();
  38492. },
  38493. enumerable: true,
  38494. configurable: true
  38495. });
  38496. StandardMaterial.prototype.needAlphaBlending = function () {
  38497. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  38498. };
  38499. StandardMaterial.prototype.needAlphaTesting = function () {
  38500. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  38501. };
  38502. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  38503. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  38504. };
  38505. StandardMaterial.prototype.getAlphaTestTexture = function () {
  38506. return this._diffuseTexture;
  38507. };
  38508. /**
  38509. * Child classes can use it to update shaders
  38510. */
  38511. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  38512. if (useInstances === void 0) { useInstances = false; }
  38513. if (subMesh.effect && this.isFrozen) {
  38514. if (this._wasPreviouslyReady && subMesh.effect) {
  38515. return true;
  38516. }
  38517. }
  38518. if (!subMesh._materialDefines) {
  38519. subMesh._materialDefines = new StandardMaterialDefines();
  38520. }
  38521. var scene = this.getScene();
  38522. var defines = subMesh._materialDefines;
  38523. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  38524. if (defines._renderId === scene.getRenderId()) {
  38525. return true;
  38526. }
  38527. }
  38528. var engine = scene.getEngine();
  38529. // Lights
  38530. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  38531. // Textures
  38532. if (defines._areTexturesDirty) {
  38533. defines._needUVs = false;
  38534. defines.MAINUV1 = false;
  38535. defines.MAINUV2 = false;
  38536. if (scene.texturesEnabled) {
  38537. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  38538. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  38539. return false;
  38540. }
  38541. else {
  38542. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  38543. }
  38544. }
  38545. else {
  38546. defines.DIFFUSE = false;
  38547. }
  38548. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  38549. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  38550. return false;
  38551. }
  38552. else {
  38553. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  38554. }
  38555. }
  38556. else {
  38557. defines.AMBIENT = false;
  38558. }
  38559. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  38560. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  38561. return false;
  38562. }
  38563. else {
  38564. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  38565. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  38566. }
  38567. }
  38568. else {
  38569. defines.OPACITY = false;
  38570. }
  38571. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  38572. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  38573. return false;
  38574. }
  38575. else {
  38576. defines._needNormals = true;
  38577. defines.REFLECTION = true;
  38578. defines.ROUGHNESS = (this._roughness > 0);
  38579. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  38580. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  38581. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  38582. switch (this._reflectionTexture.coordinatesMode) {
  38583. case BABYLON.Texture.CUBIC_MODE:
  38584. case BABYLON.Texture.INVCUBIC_MODE:
  38585. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  38586. break;
  38587. case BABYLON.Texture.EXPLICIT_MODE:
  38588. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  38589. break;
  38590. case BABYLON.Texture.PLANAR_MODE:
  38591. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  38592. break;
  38593. case BABYLON.Texture.PROJECTION_MODE:
  38594. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  38595. break;
  38596. case BABYLON.Texture.SKYBOX_MODE:
  38597. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  38598. break;
  38599. case BABYLON.Texture.SPHERICAL_MODE:
  38600. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  38601. break;
  38602. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  38603. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  38604. break;
  38605. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  38606. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  38607. break;
  38608. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  38609. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  38610. break;
  38611. }
  38612. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  38613. }
  38614. }
  38615. else {
  38616. defines.REFLECTION = false;
  38617. }
  38618. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  38619. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  38620. return false;
  38621. }
  38622. else {
  38623. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  38624. }
  38625. }
  38626. else {
  38627. defines.EMISSIVE = false;
  38628. }
  38629. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  38630. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  38631. return false;
  38632. }
  38633. else {
  38634. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  38635. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  38636. }
  38637. }
  38638. else {
  38639. defines.LIGHTMAP = false;
  38640. }
  38641. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  38642. if (!this._specularTexture.isReadyOrNotBlocking()) {
  38643. return false;
  38644. }
  38645. else {
  38646. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  38647. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  38648. }
  38649. }
  38650. else {
  38651. defines.SPECULAR = false;
  38652. }
  38653. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  38654. // Bump texure can not be not blocking.
  38655. if (!this._bumpTexture.isReady()) {
  38656. return false;
  38657. }
  38658. else {
  38659. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  38660. defines.PARALLAX = this._useParallax;
  38661. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  38662. }
  38663. }
  38664. else {
  38665. defines.BUMP = false;
  38666. }
  38667. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  38668. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  38669. return false;
  38670. }
  38671. else {
  38672. defines._needUVs = true;
  38673. defines.REFRACTION = true;
  38674. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  38675. }
  38676. }
  38677. else {
  38678. defines.REFRACTION = false;
  38679. }
  38680. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  38681. }
  38682. else {
  38683. defines.DIFFUSE = false;
  38684. defines.AMBIENT = false;
  38685. defines.OPACITY = false;
  38686. defines.REFLECTION = false;
  38687. defines.EMISSIVE = false;
  38688. defines.LIGHTMAP = false;
  38689. defines.BUMP = false;
  38690. defines.REFRACTION = false;
  38691. }
  38692. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  38693. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  38694. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  38695. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  38696. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  38697. }
  38698. if (defines._areImageProcessingDirty) {
  38699. if (!this._imageProcessingConfiguration.isReady()) {
  38700. return false;
  38701. }
  38702. this._imageProcessingConfiguration.prepareDefines(defines);
  38703. }
  38704. if (defines._areFresnelDirty) {
  38705. if (StandardMaterial.FresnelEnabled) {
  38706. // Fresnel
  38707. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  38708. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  38709. this._reflectionFresnelParameters) {
  38710. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  38711. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  38712. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  38713. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  38714. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  38715. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  38716. defines._needNormals = true;
  38717. defines.FRESNEL = true;
  38718. }
  38719. }
  38720. else {
  38721. defines.FRESNEL = false;
  38722. }
  38723. }
  38724. // Misc.
  38725. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  38726. // Attribs
  38727. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  38728. // Values that need to be evaluated on every frame
  38729. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  38730. // Get correct effect
  38731. if (defines.isDirty) {
  38732. defines.markAsProcessed();
  38733. scene.resetCachedMaterial();
  38734. // Fallbacks
  38735. var fallbacks = new BABYLON.EffectFallbacks();
  38736. if (defines.REFLECTION) {
  38737. fallbacks.addFallback(0, "REFLECTION");
  38738. }
  38739. if (defines.SPECULAR) {
  38740. fallbacks.addFallback(0, "SPECULAR");
  38741. }
  38742. if (defines.BUMP) {
  38743. fallbacks.addFallback(0, "BUMP");
  38744. }
  38745. if (defines.PARALLAX) {
  38746. fallbacks.addFallback(1, "PARALLAX");
  38747. }
  38748. if (defines.PARALLAXOCCLUSION) {
  38749. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  38750. }
  38751. if (defines.SPECULAROVERALPHA) {
  38752. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  38753. }
  38754. if (defines.FOG) {
  38755. fallbacks.addFallback(1, "FOG");
  38756. }
  38757. if (defines.POINTSIZE) {
  38758. fallbacks.addFallback(0, "POINTSIZE");
  38759. }
  38760. if (defines.LOGARITHMICDEPTH) {
  38761. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  38762. }
  38763. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  38764. if (defines.SPECULARTERM) {
  38765. fallbacks.addFallback(0, "SPECULARTERM");
  38766. }
  38767. if (defines.DIFFUSEFRESNEL) {
  38768. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  38769. }
  38770. if (defines.OPACITYFRESNEL) {
  38771. fallbacks.addFallback(2, "OPACITYFRESNEL");
  38772. }
  38773. if (defines.REFLECTIONFRESNEL) {
  38774. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  38775. }
  38776. if (defines.EMISSIVEFRESNEL) {
  38777. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  38778. }
  38779. if (defines.FRESNEL) {
  38780. fallbacks.addFallback(4, "FRESNEL");
  38781. }
  38782. //Attributes
  38783. var attribs = [BABYLON.VertexBuffer.PositionKind];
  38784. if (defines.NORMAL) {
  38785. attribs.push(BABYLON.VertexBuffer.NormalKind);
  38786. }
  38787. if (defines.UV1) {
  38788. attribs.push(BABYLON.VertexBuffer.UVKind);
  38789. }
  38790. if (defines.UV2) {
  38791. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  38792. }
  38793. if (defines.VERTEXCOLOR) {
  38794. attribs.push(BABYLON.VertexBuffer.ColorKind);
  38795. }
  38796. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  38797. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  38798. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  38799. var shaderName = "default";
  38800. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  38801. "vFogInfos", "vFogColor", "pointSize",
  38802. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  38803. "mBones",
  38804. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  38805. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  38806. "vReflectionPosition", "vReflectionSize",
  38807. "logarithmicDepthConstant", "vTangentSpaceParams"
  38808. ];
  38809. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  38810. var uniformBuffers = ["Material", "Scene"];
  38811. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  38812. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  38813. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  38814. uniformsNames: uniforms,
  38815. uniformBuffersNames: uniformBuffers,
  38816. samplers: samplers,
  38817. defines: defines,
  38818. maxSimultaneousLights: this._maxSimultaneousLights
  38819. });
  38820. if (this.customShaderNameResolve) {
  38821. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  38822. }
  38823. var join = defines.toString();
  38824. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  38825. attributes: attribs,
  38826. uniformsNames: uniforms,
  38827. uniformBuffersNames: uniformBuffers,
  38828. samplers: samplers,
  38829. defines: join,
  38830. fallbacks: fallbacks,
  38831. onCompiled: this.onCompiled,
  38832. onError: this.onError,
  38833. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  38834. }, engine), defines);
  38835. this.buildUniformLayout();
  38836. }
  38837. if (!subMesh.effect || !subMesh.effect.isReady()) {
  38838. return false;
  38839. }
  38840. defines._renderId = scene.getRenderId();
  38841. this._wasPreviouslyReady = true;
  38842. return true;
  38843. };
  38844. StandardMaterial.prototype.buildUniformLayout = function () {
  38845. // Order is important !
  38846. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  38847. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  38848. this._uniformBuffer.addUniform("opacityParts", 4);
  38849. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  38850. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  38851. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  38852. this._uniformBuffer.addUniform("refractionRightColor", 4);
  38853. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  38854. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  38855. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  38856. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  38857. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  38858. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  38859. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  38860. this._uniformBuffer.addUniform("vReflectionSize", 3);
  38861. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  38862. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  38863. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  38864. this._uniformBuffer.addUniform("vBumpInfos", 3);
  38865. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  38866. this._uniformBuffer.addUniform("ambientMatrix", 16);
  38867. this._uniformBuffer.addUniform("opacityMatrix", 16);
  38868. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  38869. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  38870. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  38871. this._uniformBuffer.addUniform("specularMatrix", 16);
  38872. this._uniformBuffer.addUniform("bumpMatrix", 16);
  38873. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  38874. this._uniformBuffer.addUniform("refractionMatrix", 16);
  38875. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  38876. this._uniformBuffer.addUniform("vSpecularColor", 4);
  38877. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  38878. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  38879. this._uniformBuffer.addUniform("pointSize", 1);
  38880. this._uniformBuffer.create();
  38881. };
  38882. StandardMaterial.prototype.unbind = function () {
  38883. if (this._activeEffect) {
  38884. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  38885. this._activeEffect.setTexture("reflection2DSampler", null);
  38886. }
  38887. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  38888. this._activeEffect.setTexture("refraction2DSampler", null);
  38889. }
  38890. }
  38891. _super.prototype.unbind.call(this);
  38892. };
  38893. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  38894. var scene = this.getScene();
  38895. var defines = subMesh._materialDefines;
  38896. if (!defines) {
  38897. return;
  38898. }
  38899. var effect = subMesh.effect;
  38900. if (!effect) {
  38901. return;
  38902. }
  38903. this._activeEffect = effect;
  38904. // Matrices
  38905. this.bindOnlyWorldMatrix(world);
  38906. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  38907. // Bones
  38908. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  38909. if (mustRebind) {
  38910. this._uniformBuffer.bindToEffect(effect, "Material");
  38911. this.bindViewProjection(effect);
  38912. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  38913. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  38914. // Fresnel
  38915. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  38916. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  38917. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  38918. }
  38919. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  38920. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  38921. }
  38922. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  38923. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  38924. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  38925. }
  38926. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  38927. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  38928. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  38929. }
  38930. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  38931. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  38932. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  38933. }
  38934. }
  38935. // Textures
  38936. if (scene.texturesEnabled) {
  38937. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  38938. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  38939. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  38940. }
  38941. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  38942. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  38943. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  38944. }
  38945. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  38946. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  38947. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  38948. }
  38949. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  38950. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  38951. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  38952. if (this._reflectionTexture.boundingBoxSize) {
  38953. var cubeTexture = this._reflectionTexture;
  38954. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  38955. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  38956. }
  38957. }
  38958. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  38959. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  38960. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  38961. }
  38962. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  38963. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  38964. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  38965. }
  38966. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  38967. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  38968. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  38969. }
  38970. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  38971. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  38972. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  38973. if (scene._mirroredCameraPosition) {
  38974. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  38975. }
  38976. else {
  38977. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  38978. }
  38979. }
  38980. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  38981. var depth = 1.0;
  38982. if (!this._refractionTexture.isCube) {
  38983. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  38984. if (this._refractionTexture.depth) {
  38985. depth = this._refractionTexture.depth;
  38986. }
  38987. }
  38988. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  38989. }
  38990. }
  38991. // Point size
  38992. if (this.pointsCloud) {
  38993. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  38994. }
  38995. if (defines.SPECULARTERM) {
  38996. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  38997. }
  38998. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  38999. // Diffuse
  39000. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  39001. }
  39002. // Textures
  39003. if (scene.texturesEnabled) {
  39004. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  39005. effect.setTexture("diffuseSampler", this._diffuseTexture);
  39006. }
  39007. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  39008. effect.setTexture("ambientSampler", this._ambientTexture);
  39009. }
  39010. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  39011. effect.setTexture("opacitySampler", this._opacityTexture);
  39012. }
  39013. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  39014. if (this._reflectionTexture.isCube) {
  39015. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  39016. }
  39017. else {
  39018. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  39019. }
  39020. }
  39021. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  39022. effect.setTexture("emissiveSampler", this._emissiveTexture);
  39023. }
  39024. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  39025. effect.setTexture("lightmapSampler", this._lightmapTexture);
  39026. }
  39027. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  39028. effect.setTexture("specularSampler", this._specularTexture);
  39029. }
  39030. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  39031. effect.setTexture("bumpSampler", this._bumpTexture);
  39032. }
  39033. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  39034. var depth = 1.0;
  39035. if (this._refractionTexture.isCube) {
  39036. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  39037. }
  39038. else {
  39039. effect.setTexture("refraction2DSampler", this._refractionTexture);
  39040. }
  39041. }
  39042. }
  39043. // Clip plane
  39044. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  39045. // Colors
  39046. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  39047. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  39048. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  39049. }
  39050. if (mustRebind || !this.isFrozen) {
  39051. // Lights
  39052. if (scene.lightsEnabled && !this._disableLighting) {
  39053. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  39054. }
  39055. // View
  39056. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  39057. this.bindView(effect);
  39058. }
  39059. // Fog
  39060. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  39061. // Morph targets
  39062. if (defines.NUM_MORPH_INFLUENCERS) {
  39063. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  39064. }
  39065. // Log. depth
  39066. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  39067. // image processing
  39068. if (!this._imageProcessingConfiguration.applyByPostProcess) {
  39069. this._imageProcessingConfiguration.bind(this._activeEffect);
  39070. }
  39071. }
  39072. this._uniformBuffer.update();
  39073. this._afterBind(mesh, this._activeEffect);
  39074. };
  39075. StandardMaterial.prototype.getAnimatables = function () {
  39076. var results = [];
  39077. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  39078. results.push(this._diffuseTexture);
  39079. }
  39080. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  39081. results.push(this._ambientTexture);
  39082. }
  39083. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  39084. results.push(this._opacityTexture);
  39085. }
  39086. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  39087. results.push(this._reflectionTexture);
  39088. }
  39089. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  39090. results.push(this._emissiveTexture);
  39091. }
  39092. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  39093. results.push(this._specularTexture);
  39094. }
  39095. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  39096. results.push(this._bumpTexture);
  39097. }
  39098. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  39099. results.push(this._lightmapTexture);
  39100. }
  39101. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  39102. results.push(this._refractionTexture);
  39103. }
  39104. return results;
  39105. };
  39106. StandardMaterial.prototype.getActiveTextures = function () {
  39107. var activeTextures = _super.prototype.getActiveTextures.call(this);
  39108. if (this._diffuseTexture) {
  39109. activeTextures.push(this._diffuseTexture);
  39110. }
  39111. if (this._ambientTexture) {
  39112. activeTextures.push(this._ambientTexture);
  39113. }
  39114. if (this._opacityTexture) {
  39115. activeTextures.push(this._opacityTexture);
  39116. }
  39117. if (this._reflectionTexture) {
  39118. activeTextures.push(this._reflectionTexture);
  39119. }
  39120. if (this._emissiveTexture) {
  39121. activeTextures.push(this._emissiveTexture);
  39122. }
  39123. if (this._specularTexture) {
  39124. activeTextures.push(this._specularTexture);
  39125. }
  39126. if (this._bumpTexture) {
  39127. activeTextures.push(this._bumpTexture);
  39128. }
  39129. if (this._lightmapTexture) {
  39130. activeTextures.push(this._lightmapTexture);
  39131. }
  39132. if (this._refractionTexture) {
  39133. activeTextures.push(this._refractionTexture);
  39134. }
  39135. return activeTextures;
  39136. };
  39137. StandardMaterial.prototype.hasTexture = function (texture) {
  39138. if (_super.prototype.hasTexture.call(this, texture)) {
  39139. return true;
  39140. }
  39141. if (this._diffuseTexture === texture) {
  39142. return true;
  39143. }
  39144. if (this._ambientTexture === texture) {
  39145. return true;
  39146. }
  39147. if (this._opacityTexture === texture) {
  39148. return true;
  39149. }
  39150. if (this._reflectionTexture === texture) {
  39151. return true;
  39152. }
  39153. if (this._emissiveTexture === texture) {
  39154. return true;
  39155. }
  39156. if (this._specularTexture === texture) {
  39157. return true;
  39158. }
  39159. if (this._bumpTexture === texture) {
  39160. return true;
  39161. }
  39162. if (this._lightmapTexture === texture) {
  39163. return true;
  39164. }
  39165. if (this._refractionTexture === texture) {
  39166. return true;
  39167. }
  39168. return false;
  39169. };
  39170. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  39171. if (forceDisposeTextures) {
  39172. if (this._diffuseTexture) {
  39173. this._diffuseTexture.dispose();
  39174. }
  39175. if (this._ambientTexture) {
  39176. this._ambientTexture.dispose();
  39177. }
  39178. if (this._opacityTexture) {
  39179. this._opacityTexture.dispose();
  39180. }
  39181. if (this._reflectionTexture) {
  39182. this._reflectionTexture.dispose();
  39183. }
  39184. if (this._emissiveTexture) {
  39185. this._emissiveTexture.dispose();
  39186. }
  39187. if (this._specularTexture) {
  39188. this._specularTexture.dispose();
  39189. }
  39190. if (this._bumpTexture) {
  39191. this._bumpTexture.dispose();
  39192. }
  39193. if (this._lightmapTexture) {
  39194. this._lightmapTexture.dispose();
  39195. }
  39196. if (this._refractionTexture) {
  39197. this._refractionTexture.dispose();
  39198. }
  39199. }
  39200. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  39201. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  39202. }
  39203. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  39204. };
  39205. StandardMaterial.prototype.clone = function (name) {
  39206. var _this = this;
  39207. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  39208. result.name = name;
  39209. result.id = name;
  39210. return result;
  39211. };
  39212. StandardMaterial.prototype.serialize = function () {
  39213. return BABYLON.SerializationHelper.Serialize(this);
  39214. };
  39215. // Statics
  39216. StandardMaterial.Parse = function (source, scene, rootUrl) {
  39217. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  39218. };
  39219. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  39220. get: function () {
  39221. return StandardMaterial._DiffuseTextureEnabled;
  39222. },
  39223. set: function (value) {
  39224. if (StandardMaterial._DiffuseTextureEnabled === value) {
  39225. return;
  39226. }
  39227. StandardMaterial._DiffuseTextureEnabled = value;
  39228. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39229. },
  39230. enumerable: true,
  39231. configurable: true
  39232. });
  39233. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  39234. get: function () {
  39235. return StandardMaterial._AmbientTextureEnabled;
  39236. },
  39237. set: function (value) {
  39238. if (StandardMaterial._AmbientTextureEnabled === value) {
  39239. return;
  39240. }
  39241. StandardMaterial._AmbientTextureEnabled = value;
  39242. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39243. },
  39244. enumerable: true,
  39245. configurable: true
  39246. });
  39247. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  39248. get: function () {
  39249. return StandardMaterial._OpacityTextureEnabled;
  39250. },
  39251. set: function (value) {
  39252. if (StandardMaterial._OpacityTextureEnabled === value) {
  39253. return;
  39254. }
  39255. StandardMaterial._OpacityTextureEnabled = value;
  39256. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39257. },
  39258. enumerable: true,
  39259. configurable: true
  39260. });
  39261. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  39262. get: function () {
  39263. return StandardMaterial._ReflectionTextureEnabled;
  39264. },
  39265. set: function (value) {
  39266. if (StandardMaterial._ReflectionTextureEnabled === value) {
  39267. return;
  39268. }
  39269. StandardMaterial._ReflectionTextureEnabled = value;
  39270. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39271. },
  39272. enumerable: true,
  39273. configurable: true
  39274. });
  39275. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  39276. get: function () {
  39277. return StandardMaterial._EmissiveTextureEnabled;
  39278. },
  39279. set: function (value) {
  39280. if (StandardMaterial._EmissiveTextureEnabled === value) {
  39281. return;
  39282. }
  39283. StandardMaterial._EmissiveTextureEnabled = value;
  39284. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39285. },
  39286. enumerable: true,
  39287. configurable: true
  39288. });
  39289. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  39290. get: function () {
  39291. return StandardMaterial._SpecularTextureEnabled;
  39292. },
  39293. set: function (value) {
  39294. if (StandardMaterial._SpecularTextureEnabled === value) {
  39295. return;
  39296. }
  39297. StandardMaterial._SpecularTextureEnabled = value;
  39298. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39299. },
  39300. enumerable: true,
  39301. configurable: true
  39302. });
  39303. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  39304. get: function () {
  39305. return StandardMaterial._BumpTextureEnabled;
  39306. },
  39307. set: function (value) {
  39308. if (StandardMaterial._BumpTextureEnabled === value) {
  39309. return;
  39310. }
  39311. StandardMaterial._BumpTextureEnabled = value;
  39312. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39313. },
  39314. enumerable: true,
  39315. configurable: true
  39316. });
  39317. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  39318. get: function () {
  39319. return StandardMaterial._LightmapTextureEnabled;
  39320. },
  39321. set: function (value) {
  39322. if (StandardMaterial._LightmapTextureEnabled === value) {
  39323. return;
  39324. }
  39325. StandardMaterial._LightmapTextureEnabled = value;
  39326. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39327. },
  39328. enumerable: true,
  39329. configurable: true
  39330. });
  39331. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  39332. get: function () {
  39333. return StandardMaterial._RefractionTextureEnabled;
  39334. },
  39335. set: function (value) {
  39336. if (StandardMaterial._RefractionTextureEnabled === value) {
  39337. return;
  39338. }
  39339. StandardMaterial._RefractionTextureEnabled = value;
  39340. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39341. },
  39342. enumerable: true,
  39343. configurable: true
  39344. });
  39345. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  39346. get: function () {
  39347. return StandardMaterial._ColorGradingTextureEnabled;
  39348. },
  39349. set: function (value) {
  39350. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  39351. return;
  39352. }
  39353. StandardMaterial._ColorGradingTextureEnabled = value;
  39354. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39355. },
  39356. enumerable: true,
  39357. configurable: true
  39358. });
  39359. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  39360. get: function () {
  39361. return StandardMaterial._FresnelEnabled;
  39362. },
  39363. set: function (value) {
  39364. if (StandardMaterial._FresnelEnabled === value) {
  39365. return;
  39366. }
  39367. StandardMaterial._FresnelEnabled = value;
  39368. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  39369. },
  39370. enumerable: true,
  39371. configurable: true
  39372. });
  39373. // Flags used to enable or disable a type of texture for all Standard Materials
  39374. StandardMaterial._DiffuseTextureEnabled = true;
  39375. StandardMaterial._AmbientTextureEnabled = true;
  39376. StandardMaterial._OpacityTextureEnabled = true;
  39377. StandardMaterial._ReflectionTextureEnabled = true;
  39378. StandardMaterial._EmissiveTextureEnabled = true;
  39379. StandardMaterial._SpecularTextureEnabled = true;
  39380. StandardMaterial._BumpTextureEnabled = true;
  39381. StandardMaterial._LightmapTextureEnabled = true;
  39382. StandardMaterial._RefractionTextureEnabled = true;
  39383. StandardMaterial._ColorGradingTextureEnabled = true;
  39384. StandardMaterial._FresnelEnabled = true;
  39385. __decorate([
  39386. BABYLON.serializeAsTexture("diffuseTexture")
  39387. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  39388. __decorate([
  39389. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  39390. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  39391. __decorate([
  39392. BABYLON.serializeAsTexture("ambientTexture")
  39393. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  39394. __decorate([
  39395. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39396. ], StandardMaterial.prototype, "ambientTexture", void 0);
  39397. __decorate([
  39398. BABYLON.serializeAsTexture("opacityTexture")
  39399. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  39400. __decorate([
  39401. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  39402. ], StandardMaterial.prototype, "opacityTexture", void 0);
  39403. __decorate([
  39404. BABYLON.serializeAsTexture("reflectionTexture")
  39405. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  39406. __decorate([
  39407. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39408. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  39409. __decorate([
  39410. BABYLON.serializeAsTexture("emissiveTexture")
  39411. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  39412. __decorate([
  39413. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39414. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  39415. __decorate([
  39416. BABYLON.serializeAsTexture("specularTexture")
  39417. ], StandardMaterial.prototype, "_specularTexture", void 0);
  39418. __decorate([
  39419. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39420. ], StandardMaterial.prototype, "specularTexture", void 0);
  39421. __decorate([
  39422. BABYLON.serializeAsTexture("bumpTexture")
  39423. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  39424. __decorate([
  39425. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39426. ], StandardMaterial.prototype, "bumpTexture", void 0);
  39427. __decorate([
  39428. BABYLON.serializeAsTexture("lightmapTexture")
  39429. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  39430. __decorate([
  39431. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39432. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  39433. __decorate([
  39434. BABYLON.serializeAsTexture("refractionTexture")
  39435. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  39436. __decorate([
  39437. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39438. ], StandardMaterial.prototype, "refractionTexture", void 0);
  39439. __decorate([
  39440. BABYLON.serializeAsColor3("ambient")
  39441. ], StandardMaterial.prototype, "ambientColor", void 0);
  39442. __decorate([
  39443. BABYLON.serializeAsColor3("diffuse")
  39444. ], StandardMaterial.prototype, "diffuseColor", void 0);
  39445. __decorate([
  39446. BABYLON.serializeAsColor3("specular")
  39447. ], StandardMaterial.prototype, "specularColor", void 0);
  39448. __decorate([
  39449. BABYLON.serializeAsColor3("emissive")
  39450. ], StandardMaterial.prototype, "emissiveColor", void 0);
  39451. __decorate([
  39452. BABYLON.serialize()
  39453. ], StandardMaterial.prototype, "specularPower", void 0);
  39454. __decorate([
  39455. BABYLON.serialize("useAlphaFromDiffuseTexture")
  39456. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  39457. __decorate([
  39458. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39459. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  39460. __decorate([
  39461. BABYLON.serialize("useEmissiveAsIllumination")
  39462. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  39463. __decorate([
  39464. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39465. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  39466. __decorate([
  39467. BABYLON.serialize("linkEmissiveWithDiffuse")
  39468. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  39469. __decorate([
  39470. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39471. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  39472. __decorate([
  39473. BABYLON.serialize("useSpecularOverAlpha")
  39474. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  39475. __decorate([
  39476. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39477. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  39478. __decorate([
  39479. BABYLON.serialize("useReflectionOverAlpha")
  39480. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  39481. __decorate([
  39482. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39483. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  39484. __decorate([
  39485. BABYLON.serialize("disableLighting")
  39486. ], StandardMaterial.prototype, "_disableLighting", void 0);
  39487. __decorate([
  39488. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  39489. ], StandardMaterial.prototype, "disableLighting", void 0);
  39490. __decorate([
  39491. BABYLON.serialize("useParallax")
  39492. ], StandardMaterial.prototype, "_useParallax", void 0);
  39493. __decorate([
  39494. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39495. ], StandardMaterial.prototype, "useParallax", void 0);
  39496. __decorate([
  39497. BABYLON.serialize("useParallaxOcclusion")
  39498. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  39499. __decorate([
  39500. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39501. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  39502. __decorate([
  39503. BABYLON.serialize()
  39504. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  39505. __decorate([
  39506. BABYLON.serialize("roughness")
  39507. ], StandardMaterial.prototype, "_roughness", void 0);
  39508. __decorate([
  39509. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39510. ], StandardMaterial.prototype, "roughness", void 0);
  39511. __decorate([
  39512. BABYLON.serialize()
  39513. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  39514. __decorate([
  39515. BABYLON.serialize()
  39516. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  39517. __decorate([
  39518. BABYLON.serialize("useLightmapAsShadowmap")
  39519. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  39520. __decorate([
  39521. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39522. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  39523. __decorate([
  39524. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  39525. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  39526. __decorate([
  39527. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  39528. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  39529. __decorate([
  39530. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  39531. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  39532. __decorate([
  39533. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  39534. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  39535. __decorate([
  39536. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  39537. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  39538. __decorate([
  39539. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  39540. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  39541. __decorate([
  39542. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  39543. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  39544. __decorate([
  39545. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  39546. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  39547. __decorate([
  39548. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  39549. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  39550. __decorate([
  39551. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  39552. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  39553. __decorate([
  39554. BABYLON.serialize("useReflectionFresnelFromSpecular")
  39555. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  39556. __decorate([
  39557. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  39558. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  39559. __decorate([
  39560. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  39561. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  39562. __decorate([
  39563. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39564. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  39565. __decorate([
  39566. BABYLON.serialize("maxSimultaneousLights")
  39567. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  39568. __decorate([
  39569. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  39570. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  39571. __decorate([
  39572. BABYLON.serialize("invertNormalMapX")
  39573. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  39574. __decorate([
  39575. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39576. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  39577. __decorate([
  39578. BABYLON.serialize("invertNormalMapY")
  39579. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  39580. __decorate([
  39581. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39582. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  39583. __decorate([
  39584. BABYLON.serialize("twoSidedLighting")
  39585. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  39586. __decorate([
  39587. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39588. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  39589. __decorate([
  39590. BABYLON.serialize()
  39591. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  39592. return StandardMaterial;
  39593. }(BABYLON.PushMaterial));
  39594. BABYLON.StandardMaterial = StandardMaterial;
  39595. })(BABYLON || (BABYLON = {}));
  39596. //# sourceMappingURL=babylon.standardMaterial.js.map
  39597. var BABYLON;
  39598. (function (BABYLON) {
  39599. /**
  39600. * Manages the defines for the PBR Material.
  39601. */
  39602. var PBRMaterialDefines = /** @class */ (function (_super) {
  39603. __extends(PBRMaterialDefines, _super);
  39604. /**
  39605. * Initializes the PBR Material defines.
  39606. */
  39607. function PBRMaterialDefines() {
  39608. var _this = _super.call(this) || this;
  39609. _this.PBR = true;
  39610. _this.MAINUV1 = false;
  39611. _this.MAINUV2 = false;
  39612. _this.UV1 = false;
  39613. _this.UV2 = false;
  39614. _this.ALBEDO = false;
  39615. _this.ALBEDODIRECTUV = 0;
  39616. _this.VERTEXCOLOR = false;
  39617. _this.AMBIENT = false;
  39618. _this.AMBIENTDIRECTUV = 0;
  39619. _this.AMBIENTINGRAYSCALE = false;
  39620. _this.OPACITY = false;
  39621. _this.VERTEXALPHA = false;
  39622. _this.OPACITYDIRECTUV = 0;
  39623. _this.OPACITYRGB = false;
  39624. _this.ALPHATEST = false;
  39625. _this.DEPTHPREPASS = false;
  39626. _this.ALPHABLEND = false;
  39627. _this.ALPHAFROMALBEDO = false;
  39628. _this.ALPHATESTVALUE = 0.5;
  39629. _this.SPECULAROVERALPHA = false;
  39630. _this.RADIANCEOVERALPHA = false;
  39631. _this.ALPHAFRESNEL = false;
  39632. _this.LINEARALPHAFRESNEL = false;
  39633. _this.PREMULTIPLYALPHA = false;
  39634. _this.EMISSIVE = false;
  39635. _this.EMISSIVEDIRECTUV = 0;
  39636. _this.REFLECTIVITY = false;
  39637. _this.REFLECTIVITYDIRECTUV = 0;
  39638. _this.SPECULARTERM = false;
  39639. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  39640. _this.MICROSURFACEAUTOMATIC = false;
  39641. _this.LODBASEDMICROSFURACE = false;
  39642. _this.MICROSURFACEMAP = false;
  39643. _this.MICROSURFACEMAPDIRECTUV = 0;
  39644. _this.METALLICWORKFLOW = false;
  39645. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  39646. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  39647. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  39648. _this.AOSTOREINMETALMAPRED = false;
  39649. _this.ENVIRONMENTBRDF = false;
  39650. _this.NORMAL = false;
  39651. _this.TANGENT = false;
  39652. _this.BUMP = false;
  39653. _this.BUMPDIRECTUV = 0;
  39654. _this.PARALLAX = false;
  39655. _this.PARALLAXOCCLUSION = false;
  39656. _this.NORMALXYSCALE = true;
  39657. _this.LIGHTMAP = false;
  39658. _this.LIGHTMAPDIRECTUV = 0;
  39659. _this.USELIGHTMAPASSHADOWMAP = false;
  39660. _this.REFLECTION = false;
  39661. _this.REFLECTIONMAP_3D = false;
  39662. _this.REFLECTIONMAP_SPHERICAL = false;
  39663. _this.REFLECTIONMAP_PLANAR = false;
  39664. _this.REFLECTIONMAP_CUBIC = false;
  39665. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  39666. _this.REFLECTIONMAP_PROJECTION = false;
  39667. _this.REFLECTIONMAP_SKYBOX = false;
  39668. _this.REFLECTIONMAP_EXPLICIT = false;
  39669. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  39670. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  39671. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  39672. _this.INVERTCUBICMAP = false;
  39673. _this.USESPHERICALFROMREFLECTIONMAP = false;
  39674. _this.USESPHERICALINVERTEX = false;
  39675. _this.REFLECTIONMAP_OPPOSITEZ = false;
  39676. _this.LODINREFLECTIONALPHA = false;
  39677. _this.GAMMAREFLECTION = false;
  39678. _this.RADIANCEOCCLUSION = false;
  39679. _this.HORIZONOCCLUSION = false;
  39680. _this.REFRACTION = false;
  39681. _this.REFRACTIONMAP_3D = false;
  39682. _this.REFRACTIONMAP_OPPOSITEZ = false;
  39683. _this.LODINREFRACTIONALPHA = false;
  39684. _this.GAMMAREFRACTION = false;
  39685. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  39686. _this.INSTANCES = false;
  39687. _this.NUM_BONE_INFLUENCERS = 0;
  39688. _this.BonesPerMesh = 0;
  39689. _this.NONUNIFORMSCALING = false;
  39690. _this.MORPHTARGETS = false;
  39691. _this.MORPHTARGETS_NORMAL = false;
  39692. _this.MORPHTARGETS_TANGENT = false;
  39693. _this.NUM_MORPH_INFLUENCERS = 0;
  39694. _this.IMAGEPROCESSING = false;
  39695. _this.VIGNETTE = false;
  39696. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  39697. _this.VIGNETTEBLENDMODEOPAQUE = false;
  39698. _this.TONEMAPPING = false;
  39699. _this.CONTRAST = false;
  39700. _this.COLORCURVES = false;
  39701. _this.COLORGRADING = false;
  39702. _this.COLORGRADING3D = false;
  39703. _this.SAMPLER3DGREENDEPTH = false;
  39704. _this.SAMPLER3DBGRMAP = false;
  39705. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  39706. _this.EXPOSURE = false;
  39707. _this.USEPHYSICALLIGHTFALLOFF = false;
  39708. _this.TWOSIDEDLIGHTING = false;
  39709. _this.SHADOWFLOAT = false;
  39710. _this.CLIPPLANE = false;
  39711. _this.POINTSIZE = false;
  39712. _this.FOG = false;
  39713. _this.LOGARITHMICDEPTH = false;
  39714. _this.FORCENORMALFORWARD = false;
  39715. _this.rebuild();
  39716. return _this;
  39717. }
  39718. /**
  39719. * Resets the PBR Material defines.
  39720. */
  39721. PBRMaterialDefines.prototype.reset = function () {
  39722. _super.prototype.reset.call(this);
  39723. this.ALPHATESTVALUE = 0.5;
  39724. this.PBR = true;
  39725. };
  39726. return PBRMaterialDefines;
  39727. }(BABYLON.MaterialDefines));
  39728. /**
  39729. * The Physically based material base class of BJS.
  39730. *
  39731. * This offers the main features of a standard PBR material.
  39732. * For more information, please refer to the documentation :
  39733. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  39734. */
  39735. var PBRBaseMaterial = /** @class */ (function (_super) {
  39736. __extends(PBRBaseMaterial, _super);
  39737. /**
  39738. * Instantiates a new PBRMaterial instance.
  39739. *
  39740. * @param name The material name
  39741. * @param scene The scene the material will be use in.
  39742. */
  39743. function PBRBaseMaterial(name, scene) {
  39744. var _this = _super.call(this, name, scene) || this;
  39745. /**
  39746. * Intensity of the direct lights e.g. the four lights available in your scene.
  39747. * This impacts both the direct diffuse and specular highlights.
  39748. */
  39749. _this._directIntensity = 1.0;
  39750. /**
  39751. * Intensity of the emissive part of the material.
  39752. * This helps controlling the emissive effect without modifying the emissive color.
  39753. */
  39754. _this._emissiveIntensity = 1.0;
  39755. /**
  39756. * Intensity of the environment e.g. how much the environment will light the object
  39757. * either through harmonics for rough material or through the refelction for shiny ones.
  39758. */
  39759. _this._environmentIntensity = 1.0;
  39760. /**
  39761. * This is a special control allowing the reduction of the specular highlights coming from the
  39762. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  39763. */
  39764. _this._specularIntensity = 1.0;
  39765. /**
  39766. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  39767. */
  39768. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  39769. /**
  39770. * Debug Control allowing disabling the bump map on this material.
  39771. */
  39772. _this._disableBumpMap = false;
  39773. /**
  39774. * AKA Occlusion Texture Intensity in other nomenclature.
  39775. */
  39776. _this._ambientTextureStrength = 1.0;
  39777. /**
  39778. * The color of a material in ambient lighting.
  39779. */
  39780. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  39781. /**
  39782. * AKA Diffuse Color in other nomenclature.
  39783. */
  39784. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  39785. /**
  39786. * AKA Specular Color in other nomenclature.
  39787. */
  39788. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  39789. /**
  39790. * The color applied when light is reflected from a material.
  39791. */
  39792. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  39793. /**
  39794. * The color applied when light is emitted from a material.
  39795. */
  39796. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  39797. /**
  39798. * AKA Glossiness in other nomenclature.
  39799. */
  39800. _this._microSurface = 0.9;
  39801. /**
  39802. * source material index of refraction (IOR)' / 'destination material IOR.
  39803. */
  39804. _this._indexOfRefraction = 0.66;
  39805. /**
  39806. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  39807. */
  39808. _this._invertRefractionY = false;
  39809. /**
  39810. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  39811. * Materials half opaque for instance using refraction could benefit from this control.
  39812. */
  39813. _this._linkRefractionWithTransparency = false;
  39814. /**
  39815. * Specifies that the material will use the light map as a show map.
  39816. */
  39817. _this._useLightmapAsShadowmap = false;
  39818. /**
  39819. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  39820. * makes the reflect vector face the model (under horizon).
  39821. */
  39822. _this._useHorizonOcclusion = true;
  39823. /**
  39824. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  39825. * too much the area relying on ambient texture to define their ambient occlusion.
  39826. */
  39827. _this._useRadianceOcclusion = true;
  39828. /**
  39829. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  39830. */
  39831. _this._useAlphaFromAlbedoTexture = false;
  39832. /**
  39833. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  39834. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  39835. */
  39836. _this._useSpecularOverAlpha = true;
  39837. /**
  39838. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  39839. */
  39840. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  39841. /**
  39842. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  39843. */
  39844. _this._useRoughnessFromMetallicTextureAlpha = true;
  39845. /**
  39846. * Specifies if the metallic texture contains the roughness information in its green channel.
  39847. */
  39848. _this._useRoughnessFromMetallicTextureGreen = false;
  39849. /**
  39850. * Specifies if the metallic texture contains the metallness information in its blue channel.
  39851. */
  39852. _this._useMetallnessFromMetallicTextureBlue = false;
  39853. /**
  39854. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  39855. */
  39856. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  39857. /**
  39858. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  39859. */
  39860. _this._useAmbientInGrayScale = false;
  39861. /**
  39862. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  39863. * The material will try to infer what glossiness each pixel should be.
  39864. */
  39865. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  39866. /**
  39867. * BJS is using an harcoded light falloff based on a manually sets up range.
  39868. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  39869. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  39870. */
  39871. _this._usePhysicalLightFalloff = true;
  39872. /**
  39873. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  39874. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  39875. */
  39876. _this._useRadianceOverAlpha = true;
  39877. /**
  39878. * Allows using the bump map in parallax mode.
  39879. */
  39880. _this._useParallax = false;
  39881. /**
  39882. * Allows using the bump map in parallax occlusion mode.
  39883. */
  39884. _this._useParallaxOcclusion = false;
  39885. /**
  39886. * Controls the scale bias of the parallax mode.
  39887. */
  39888. _this._parallaxScaleBias = 0.05;
  39889. /**
  39890. * If sets to true, disables all the lights affecting the material.
  39891. */
  39892. _this._disableLighting = false;
  39893. /**
  39894. * Number of Simultaneous lights allowed on the material.
  39895. */
  39896. _this._maxSimultaneousLights = 4;
  39897. /**
  39898. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  39899. */
  39900. _this._invertNormalMapX = false;
  39901. /**
  39902. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  39903. */
  39904. _this._invertNormalMapY = false;
  39905. /**
  39906. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  39907. */
  39908. _this._twoSidedLighting = false;
  39909. /**
  39910. * Defines the alpha limits in alpha test mode.
  39911. */
  39912. _this._alphaCutOff = 0.4;
  39913. /**
  39914. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  39915. */
  39916. _this._forceAlphaTest = false;
  39917. /**
  39918. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  39919. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  39920. */
  39921. _this._useAlphaFresnel = false;
  39922. /**
  39923. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  39924. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  39925. */
  39926. _this._useLinearAlphaFresnel = false;
  39927. /**
  39928. * The transparency mode of the material.
  39929. */
  39930. _this._transparencyMode = null;
  39931. /**
  39932. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  39933. * from cos thetav and roughness:
  39934. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  39935. */
  39936. _this._environmentBRDFTexture = null;
  39937. /**
  39938. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  39939. */
  39940. _this._forceIrradianceInFragment = false;
  39941. /**
  39942. * Force normal to face away from face.
  39943. */
  39944. _this._forceNormalForward = false;
  39945. /**
  39946. * Force metallic workflow.
  39947. */
  39948. _this._forceMetallicWorkflow = false;
  39949. /**
  39950. * Stores the available render targets.
  39951. */
  39952. _this._renderTargets = new BABYLON.SmartArray(16);
  39953. /**
  39954. * Sets the global ambient color for the material used in lighting calculations.
  39955. */
  39956. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  39957. // Setup the default processing configuration to the scene.
  39958. _this._attachImageProcessingConfiguration(null);
  39959. _this.getRenderTargetTextures = function () {
  39960. _this._renderTargets.reset();
  39961. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  39962. _this._renderTargets.push(_this._reflectionTexture);
  39963. }
  39964. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  39965. _this._renderTargets.push(_this._refractionTexture);
  39966. }
  39967. return _this._renderTargets;
  39968. };
  39969. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  39970. return _this;
  39971. }
  39972. /**
  39973. * Attaches a new image processing configuration to the PBR Material.
  39974. * @param configuration
  39975. */
  39976. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  39977. var _this = this;
  39978. if (configuration === this._imageProcessingConfiguration) {
  39979. return;
  39980. }
  39981. // Detaches observer.
  39982. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  39983. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  39984. }
  39985. // Pick the scene configuration if needed.
  39986. if (!configuration) {
  39987. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  39988. }
  39989. else {
  39990. this._imageProcessingConfiguration = configuration;
  39991. }
  39992. // Attaches observer.
  39993. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  39994. _this._markAllSubMeshesAsImageProcessingDirty();
  39995. });
  39996. };
  39997. /**
  39998. * Gets the name of the material class.
  39999. */
  40000. PBRBaseMaterial.prototype.getClassName = function () {
  40001. return "PBRBaseMaterial";
  40002. };
  40003. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  40004. /**
  40005. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  40006. */
  40007. get: function () {
  40008. return this._useLogarithmicDepth;
  40009. },
  40010. /**
  40011. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  40012. */
  40013. set: function (value) {
  40014. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  40015. },
  40016. enumerable: true,
  40017. configurable: true
  40018. });
  40019. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  40020. /**
  40021. * Gets the current transparency mode.
  40022. */
  40023. get: function () {
  40024. return this._transparencyMode;
  40025. },
  40026. /**
  40027. * Sets the transparency mode of the material.
  40028. */
  40029. set: function (value) {
  40030. if (this._transparencyMode === value) {
  40031. return;
  40032. }
  40033. this._transparencyMode = value;
  40034. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  40035. this._markAllSubMeshesAsTexturesAndMiscDirty();
  40036. },
  40037. enumerable: true,
  40038. configurable: true
  40039. });
  40040. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  40041. /**
  40042. * Returns true if alpha blending should be disabled.
  40043. */
  40044. get: function () {
  40045. return (this._linkRefractionWithTransparency ||
  40046. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  40047. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  40048. },
  40049. enumerable: true,
  40050. configurable: true
  40051. });
  40052. /**
  40053. * Specifies whether or not this material should be rendered in alpha blend mode.
  40054. */
  40055. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  40056. if (this._disableAlphaBlending) {
  40057. return false;
  40058. }
  40059. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  40060. };
  40061. /**
  40062. * Specifies if the mesh will require alpha blending.
  40063. * @param mesh - BJS mesh.
  40064. */
  40065. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  40066. if (this._disableAlphaBlending) {
  40067. return false;
  40068. }
  40069. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  40070. };
  40071. /**
  40072. * Specifies whether or not this material should be rendered in alpha test mode.
  40073. */
  40074. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  40075. if (this._forceAlphaTest) {
  40076. return true;
  40077. }
  40078. if (this._linkRefractionWithTransparency) {
  40079. return false;
  40080. }
  40081. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  40082. };
  40083. /**
  40084. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  40085. */
  40086. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  40087. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  40088. };
  40089. /**
  40090. * Gets the texture used for the alpha test.
  40091. */
  40092. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  40093. return this._albedoTexture;
  40094. };
  40095. /**
  40096. * Specifies that the submesh is ready to be used.
  40097. * @param mesh - BJS mesh.
  40098. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  40099. * @param useInstances - Specifies that instances should be used.
  40100. * @returns - boolean indicating that the submesh is ready or not.
  40101. */
  40102. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  40103. if (subMesh.effect && this.isFrozen) {
  40104. if (this._wasPreviouslyReady) {
  40105. return true;
  40106. }
  40107. }
  40108. if (!subMesh._materialDefines) {
  40109. subMesh._materialDefines = new PBRMaterialDefines();
  40110. }
  40111. var defines = subMesh._materialDefines;
  40112. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  40113. if (defines._renderId === this.getScene().getRenderId()) {
  40114. return true;
  40115. }
  40116. }
  40117. var scene = this.getScene();
  40118. var engine = scene.getEngine();
  40119. if (defines._areTexturesDirty) {
  40120. if (scene.texturesEnabled) {
  40121. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  40122. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  40123. return false;
  40124. }
  40125. }
  40126. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  40127. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  40128. return false;
  40129. }
  40130. }
  40131. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  40132. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  40133. return false;
  40134. }
  40135. }
  40136. var reflectionTexture = this._getReflectionTexture();
  40137. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  40138. if (!reflectionTexture.isReadyOrNotBlocking()) {
  40139. return false;
  40140. }
  40141. }
  40142. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  40143. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  40144. return false;
  40145. }
  40146. }
  40147. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  40148. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  40149. return false;
  40150. }
  40151. }
  40152. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  40153. if (this._metallicTexture) {
  40154. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  40155. return false;
  40156. }
  40157. }
  40158. else if (this._reflectivityTexture) {
  40159. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  40160. return false;
  40161. }
  40162. }
  40163. if (this._microSurfaceTexture) {
  40164. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  40165. return false;
  40166. }
  40167. }
  40168. }
  40169. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  40170. // Bump texture cannot be not blocking.
  40171. if (!this._bumpTexture.isReady()) {
  40172. return false;
  40173. }
  40174. }
  40175. var refractionTexture = this._getRefractionTexture();
  40176. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  40177. if (!refractionTexture.isReadyOrNotBlocking()) {
  40178. return false;
  40179. }
  40180. }
  40181. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  40182. // This is blocking.
  40183. if (!this._environmentBRDFTexture.isReady()) {
  40184. return false;
  40185. }
  40186. }
  40187. }
  40188. }
  40189. if (defines._areImageProcessingDirty) {
  40190. if (!this._imageProcessingConfiguration.isReady()) {
  40191. return false;
  40192. }
  40193. }
  40194. if (!engine.getCaps().standardDerivatives) {
  40195. var bufferMesh = null;
  40196. if (mesh.getClassName() === "InstancedMesh") {
  40197. bufferMesh = mesh.sourceMesh;
  40198. }
  40199. else if (mesh.getClassName() === "Mesh") {
  40200. bufferMesh = mesh;
  40201. }
  40202. if (bufferMesh && bufferMesh.geometry && bufferMesh.geometry.isReady() && !bufferMesh.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  40203. bufferMesh.createNormals(true);
  40204. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + bufferMesh.name);
  40205. }
  40206. }
  40207. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  40208. if (effect) {
  40209. scene.resetCachedMaterial();
  40210. subMesh.setEffect(effect, defines);
  40211. this.buildUniformLayout();
  40212. }
  40213. if (!subMesh.effect || !subMesh.effect.isReady()) {
  40214. return false;
  40215. }
  40216. defines._renderId = scene.getRenderId();
  40217. this._wasPreviouslyReady = true;
  40218. return true;
  40219. };
  40220. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  40221. if (onCompiled === void 0) { onCompiled = null; }
  40222. if (onError === void 0) { onError = null; }
  40223. if (useInstances === void 0) { useInstances = null; }
  40224. if (useClipPlane === void 0) { useClipPlane = null; }
  40225. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  40226. if (!defines.isDirty) {
  40227. return null;
  40228. }
  40229. defines.markAsProcessed();
  40230. var scene = this.getScene();
  40231. var engine = scene.getEngine();
  40232. // Fallbacks
  40233. var fallbacks = new BABYLON.EffectFallbacks();
  40234. var fallbackRank = 0;
  40235. if (defines.USESPHERICALINVERTEX) {
  40236. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  40237. }
  40238. if (defines.FOG) {
  40239. fallbacks.addFallback(fallbackRank, "FOG");
  40240. }
  40241. if (defines.POINTSIZE) {
  40242. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  40243. }
  40244. if (defines.LOGARITHMICDEPTH) {
  40245. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  40246. }
  40247. if (defines.PARALLAX) {
  40248. fallbacks.addFallback(fallbackRank, "PARALLAX");
  40249. }
  40250. if (defines.PARALLAXOCCLUSION) {
  40251. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  40252. }
  40253. if (defines.ENVIRONMENTBRDF) {
  40254. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  40255. }
  40256. if (defines.TANGENT) {
  40257. fallbacks.addFallback(fallbackRank++, "TANGENT");
  40258. }
  40259. if (defines.BUMP) {
  40260. fallbacks.addFallback(fallbackRank++, "BUMP");
  40261. }
  40262. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  40263. if (defines.SPECULARTERM) {
  40264. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  40265. }
  40266. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  40267. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  40268. }
  40269. if (defines.LIGHTMAP) {
  40270. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  40271. }
  40272. if (defines.NORMAL) {
  40273. fallbacks.addFallback(fallbackRank++, "NORMAL");
  40274. }
  40275. if (defines.AMBIENT) {
  40276. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  40277. }
  40278. if (defines.EMISSIVE) {
  40279. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  40280. }
  40281. if (defines.VERTEXCOLOR) {
  40282. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  40283. }
  40284. if (defines.NUM_BONE_INFLUENCERS > 0) {
  40285. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  40286. }
  40287. if (defines.MORPHTARGETS) {
  40288. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  40289. }
  40290. //Attributes
  40291. var attribs = [BABYLON.VertexBuffer.PositionKind];
  40292. if (defines.NORMAL) {
  40293. attribs.push(BABYLON.VertexBuffer.NormalKind);
  40294. }
  40295. if (defines.TANGENT) {
  40296. attribs.push(BABYLON.VertexBuffer.TangentKind);
  40297. }
  40298. if (defines.UV1) {
  40299. attribs.push(BABYLON.VertexBuffer.UVKind);
  40300. }
  40301. if (defines.UV2) {
  40302. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  40303. }
  40304. if (defines.VERTEXCOLOR) {
  40305. attribs.push(BABYLON.VertexBuffer.ColorKind);
  40306. }
  40307. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  40308. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  40309. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  40310. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  40311. "vFogInfos", "vFogColor", "pointSize",
  40312. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  40313. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  40314. "mBones",
  40315. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  40316. "vLightingIntensity",
  40317. "logarithmicDepthConstant",
  40318. "vSphericalX", "vSphericalY", "vSphericalZ",
  40319. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  40320. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  40321. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  40322. "vTangentSpaceParams"
  40323. ];
  40324. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  40325. "bumpSampler", "lightmapSampler", "opacitySampler",
  40326. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  40327. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  40328. "microSurfaceSampler", "environmentBrdfSampler"];
  40329. var uniformBuffers = ["Material", "Scene"];
  40330. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  40331. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  40332. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  40333. uniformsNames: uniforms,
  40334. uniformBuffersNames: uniformBuffers,
  40335. samplers: samplers,
  40336. defines: defines,
  40337. maxSimultaneousLights: this._maxSimultaneousLights
  40338. });
  40339. var join = defines.toString();
  40340. return engine.createEffect("pbr", {
  40341. attributes: attribs,
  40342. uniformsNames: uniforms,
  40343. uniformBuffersNames: uniformBuffers,
  40344. samplers: samplers,
  40345. defines: join,
  40346. fallbacks: fallbacks,
  40347. onCompiled: onCompiled,
  40348. onError: onError,
  40349. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  40350. }, engine);
  40351. };
  40352. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  40353. if (useInstances === void 0) { useInstances = null; }
  40354. if (useClipPlane === void 0) { useClipPlane = null; }
  40355. var scene = this.getScene();
  40356. var engine = scene.getEngine();
  40357. // Lights
  40358. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  40359. defines._needNormals = true;
  40360. // Textures
  40361. if (defines._areTexturesDirty) {
  40362. defines._needUVs = false;
  40363. if (scene.texturesEnabled) {
  40364. if (scene.getEngine().getCaps().textureLOD) {
  40365. defines.LODBASEDMICROSFURACE = true;
  40366. }
  40367. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  40368. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  40369. }
  40370. else {
  40371. defines.ALBEDO = false;
  40372. }
  40373. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  40374. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  40375. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  40376. }
  40377. else {
  40378. defines.AMBIENT = false;
  40379. }
  40380. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  40381. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  40382. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  40383. }
  40384. else {
  40385. defines.OPACITY = false;
  40386. }
  40387. var reflectionTexture = this._getReflectionTexture();
  40388. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  40389. defines.REFLECTION = true;
  40390. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  40391. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  40392. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  40393. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  40394. defines.INVERTCUBICMAP = true;
  40395. }
  40396. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  40397. switch (reflectionTexture.coordinatesMode) {
  40398. case BABYLON.Texture.CUBIC_MODE:
  40399. case BABYLON.Texture.INVCUBIC_MODE:
  40400. defines.REFLECTIONMAP_CUBIC = true;
  40401. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  40402. break;
  40403. case BABYLON.Texture.EXPLICIT_MODE:
  40404. defines.REFLECTIONMAP_EXPLICIT = true;
  40405. break;
  40406. case BABYLON.Texture.PLANAR_MODE:
  40407. defines.REFLECTIONMAP_PLANAR = true;
  40408. break;
  40409. case BABYLON.Texture.PROJECTION_MODE:
  40410. defines.REFLECTIONMAP_PROJECTION = true;
  40411. break;
  40412. case BABYLON.Texture.SKYBOX_MODE:
  40413. defines.REFLECTIONMAP_SKYBOX = true;
  40414. break;
  40415. case BABYLON.Texture.SPHERICAL_MODE:
  40416. defines.REFLECTIONMAP_SPHERICAL = true;
  40417. break;
  40418. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  40419. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  40420. break;
  40421. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  40422. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  40423. break;
  40424. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  40425. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  40426. break;
  40427. }
  40428. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  40429. if (reflectionTexture.sphericalPolynomial) {
  40430. defines.USESPHERICALFROMREFLECTIONMAP = true;
  40431. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  40432. defines.USESPHERICALINVERTEX = false;
  40433. }
  40434. else {
  40435. defines.USESPHERICALINVERTEX = true;
  40436. }
  40437. }
  40438. }
  40439. }
  40440. else {
  40441. defines.REFLECTION = false;
  40442. defines.REFLECTIONMAP_3D = false;
  40443. defines.REFLECTIONMAP_SPHERICAL = false;
  40444. defines.REFLECTIONMAP_PLANAR = false;
  40445. defines.REFLECTIONMAP_CUBIC = false;
  40446. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  40447. defines.REFLECTIONMAP_PROJECTION = false;
  40448. defines.REFLECTIONMAP_SKYBOX = false;
  40449. defines.REFLECTIONMAP_EXPLICIT = false;
  40450. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  40451. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  40452. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  40453. defines.INVERTCUBICMAP = false;
  40454. defines.USESPHERICALFROMREFLECTIONMAP = false;
  40455. defines.USESPHERICALINVERTEX = false;
  40456. defines.REFLECTIONMAP_OPPOSITEZ = false;
  40457. defines.LODINREFLECTIONALPHA = false;
  40458. defines.GAMMAREFLECTION = false;
  40459. }
  40460. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  40461. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  40462. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  40463. }
  40464. else {
  40465. defines.LIGHTMAP = false;
  40466. }
  40467. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  40468. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  40469. }
  40470. else {
  40471. defines.EMISSIVE = false;
  40472. }
  40473. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  40474. if (this._metallicTexture) {
  40475. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  40476. defines.METALLICWORKFLOW = true;
  40477. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  40478. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  40479. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  40480. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  40481. }
  40482. else if (this._reflectivityTexture) {
  40483. defines.METALLICWORKFLOW = false;
  40484. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  40485. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  40486. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  40487. }
  40488. else {
  40489. defines.METALLICWORKFLOW = false;
  40490. defines.REFLECTIVITY = false;
  40491. }
  40492. if (this._microSurfaceTexture) {
  40493. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  40494. }
  40495. else {
  40496. defines.MICROSURFACEMAP = false;
  40497. }
  40498. }
  40499. else {
  40500. defines.REFLECTIVITY = false;
  40501. defines.MICROSURFACEMAP = false;
  40502. }
  40503. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  40504. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  40505. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  40506. defines.PARALLAX = true;
  40507. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  40508. }
  40509. else {
  40510. defines.PARALLAX = false;
  40511. }
  40512. }
  40513. else {
  40514. defines.BUMP = false;
  40515. }
  40516. var refractionTexture = this._getRefractionTexture();
  40517. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  40518. defines.REFRACTION = true;
  40519. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  40520. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  40521. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  40522. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  40523. if (this._linkRefractionWithTransparency) {
  40524. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  40525. }
  40526. }
  40527. else {
  40528. defines.REFRACTION = false;
  40529. }
  40530. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  40531. defines.ENVIRONMENTBRDF = true;
  40532. }
  40533. else {
  40534. defines.ENVIRONMENTBRDF = false;
  40535. }
  40536. if (this._shouldUseAlphaFromAlbedoTexture()) {
  40537. defines.ALPHAFROMALBEDO = true;
  40538. }
  40539. else {
  40540. defines.ALPHAFROMALBEDO = false;
  40541. }
  40542. }
  40543. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  40544. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  40545. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  40546. if (this._forceMetallicWorkflow || (this._metallic !== undefined && this._metallic !== null) || (this._roughness !== undefined && this._roughness !== null)) {
  40547. defines.METALLICWORKFLOW = true;
  40548. }
  40549. else {
  40550. defines.METALLICWORKFLOW = false;
  40551. }
  40552. if (!this.backFaceCulling && this._twoSidedLighting) {
  40553. defines.TWOSIDEDLIGHTING = true;
  40554. }
  40555. else {
  40556. defines.TWOSIDEDLIGHTING = false;
  40557. }
  40558. defines.ALPHATESTVALUE = this._alphaCutOff;
  40559. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  40560. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  40561. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  40562. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  40563. }
  40564. if (defines._areImageProcessingDirty) {
  40565. this._imageProcessingConfiguration.prepareDefines(defines);
  40566. }
  40567. defines.FORCENORMALFORWARD = this._forceNormalForward;
  40568. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  40569. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  40570. // Misc.
  40571. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  40572. // Values that need to be evaluated on every frame
  40573. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  40574. // Attribs
  40575. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  40576. };
  40577. /**
  40578. * Force shader compilation
  40579. */
  40580. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  40581. var _this = this;
  40582. var localOptions = __assign({ clipPlane: false }, options);
  40583. var defines = new PBRMaterialDefines();
  40584. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  40585. if (effect.isReady()) {
  40586. if (onCompiled) {
  40587. onCompiled(this);
  40588. }
  40589. }
  40590. else {
  40591. effect.onCompileObservable.add(function () {
  40592. if (onCompiled) {
  40593. onCompiled(_this);
  40594. }
  40595. });
  40596. }
  40597. };
  40598. /**
  40599. * Initializes the uniform buffer layout for the shader.
  40600. */
  40601. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  40602. // Order is important !
  40603. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  40604. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  40605. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  40606. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  40607. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  40608. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  40609. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  40610. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  40611. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  40612. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  40613. this._uniformBuffer.addUniform("vReflectionSize", 3);
  40614. this._uniformBuffer.addUniform("vBumpInfos", 3);
  40615. this._uniformBuffer.addUniform("albedoMatrix", 16);
  40616. this._uniformBuffer.addUniform("ambientMatrix", 16);
  40617. this._uniformBuffer.addUniform("opacityMatrix", 16);
  40618. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  40619. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  40620. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  40621. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  40622. this._uniformBuffer.addUniform("bumpMatrix", 16);
  40623. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  40624. this._uniformBuffer.addUniform("refractionMatrix", 16);
  40625. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  40626. this._uniformBuffer.addUniform("vReflectionColor", 3);
  40627. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  40628. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  40629. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  40630. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  40631. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  40632. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  40633. this._uniformBuffer.addUniform("pointSize", 1);
  40634. this._uniformBuffer.create();
  40635. };
  40636. /**
  40637. * Unbinds the textures.
  40638. */
  40639. PBRBaseMaterial.prototype.unbind = function () {
  40640. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  40641. this._uniformBuffer.setTexture("reflectionSampler", null);
  40642. }
  40643. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  40644. this._uniformBuffer.setTexture("refractionSampler", null);
  40645. }
  40646. _super.prototype.unbind.call(this);
  40647. };
  40648. /**
  40649. * Binds to the world matrix.
  40650. * @param world - The world matrix.
  40651. */
  40652. PBRBaseMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  40653. this._activeEffect.setMatrix("world", world);
  40654. };
  40655. /**
  40656. * Binds the submesh data.
  40657. * @param world - The world matrix.
  40658. * @param mesh - The BJS mesh.
  40659. * @param subMesh - A submesh of the BJS mesh.
  40660. */
  40661. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  40662. var scene = this.getScene();
  40663. var defines = subMesh._materialDefines;
  40664. if (!defines) {
  40665. return;
  40666. }
  40667. var effect = subMesh.effect;
  40668. if (!effect) {
  40669. return;
  40670. }
  40671. this._activeEffect = effect;
  40672. // Matrices
  40673. this.bindOnlyWorldMatrix(world);
  40674. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  40675. // Bones
  40676. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  40677. var reflectionTexture = null;
  40678. if (mustRebind) {
  40679. this._uniformBuffer.bindToEffect(effect, "Material");
  40680. this.bindViewProjection(effect);
  40681. reflectionTexture = this._getReflectionTexture();
  40682. var refractionTexture = this._getRefractionTexture();
  40683. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  40684. // Texture uniforms
  40685. if (scene.texturesEnabled) {
  40686. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  40687. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  40688. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  40689. }
  40690. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  40691. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  40692. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  40693. }
  40694. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  40695. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  40696. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  40697. }
  40698. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  40699. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  40700. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  40701. if (reflectionTexture.boundingBoxSize) {
  40702. var cubeTexture = reflectionTexture;
  40703. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  40704. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  40705. }
  40706. var polynomials = reflectionTexture.sphericalPolynomial;
  40707. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  40708. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  40709. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  40710. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  40711. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  40712. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  40713. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  40714. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  40715. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  40716. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  40717. }
  40718. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  40719. }
  40720. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  40721. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  40722. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  40723. }
  40724. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  40725. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  40726. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  40727. }
  40728. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  40729. if (this._metallicTexture) {
  40730. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  40731. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  40732. }
  40733. else if (this._reflectivityTexture) {
  40734. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  40735. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  40736. }
  40737. if (this._microSurfaceTexture) {
  40738. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  40739. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  40740. }
  40741. }
  40742. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  40743. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  40744. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  40745. if (scene._mirroredCameraPosition) {
  40746. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  40747. }
  40748. else {
  40749. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  40750. }
  40751. }
  40752. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  40753. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  40754. var depth = 1.0;
  40755. if (!refractionTexture.isCube) {
  40756. if (refractionTexture.depth) {
  40757. depth = refractionTexture.depth;
  40758. }
  40759. }
  40760. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  40761. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  40762. }
  40763. }
  40764. // Point size
  40765. if (this.pointsCloud) {
  40766. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  40767. }
  40768. // Colors
  40769. if (defines.METALLICWORKFLOW) {
  40770. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  40771. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  40772. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  40773. }
  40774. else {
  40775. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  40776. }
  40777. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  40778. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  40779. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  40780. // Misc
  40781. this._lightingInfos.x = this._directIntensity;
  40782. this._lightingInfos.y = this._emissiveIntensity;
  40783. this._lightingInfos.z = this._environmentIntensity;
  40784. this._lightingInfos.w = this._specularIntensity;
  40785. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  40786. }
  40787. // Textures
  40788. if (scene.texturesEnabled) {
  40789. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  40790. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  40791. }
  40792. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  40793. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  40794. }
  40795. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  40796. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  40797. }
  40798. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  40799. if (defines.LODBASEDMICROSFURACE) {
  40800. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  40801. }
  40802. else {
  40803. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  40804. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  40805. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  40806. }
  40807. }
  40808. if (defines.ENVIRONMENTBRDF) {
  40809. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  40810. }
  40811. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  40812. if (defines.LODBASEDMICROSFURACE) {
  40813. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  40814. }
  40815. else {
  40816. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  40817. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  40818. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  40819. }
  40820. }
  40821. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  40822. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  40823. }
  40824. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  40825. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  40826. }
  40827. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  40828. if (this._metallicTexture) {
  40829. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  40830. }
  40831. else if (this._reflectivityTexture) {
  40832. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  40833. }
  40834. if (this._microSurfaceTexture) {
  40835. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  40836. }
  40837. }
  40838. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  40839. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  40840. }
  40841. }
  40842. // Clip plane
  40843. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  40844. // Colors
  40845. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  40846. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  40847. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  40848. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  40849. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  40850. }
  40851. if (mustRebind || !this.isFrozen) {
  40852. // Lights
  40853. if (scene.lightsEnabled && !this._disableLighting) {
  40854. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  40855. }
  40856. // View
  40857. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  40858. this.bindView(effect);
  40859. }
  40860. // Fog
  40861. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  40862. // Morph targets
  40863. if (defines.NUM_MORPH_INFLUENCERS) {
  40864. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  40865. }
  40866. // image processing
  40867. this._imageProcessingConfiguration.bind(this._activeEffect);
  40868. // Log. depth
  40869. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  40870. }
  40871. this._uniformBuffer.update();
  40872. this._afterBind(mesh);
  40873. };
  40874. /**
  40875. * Returns the animatable textures.
  40876. * @returns - Array of animatable textures.
  40877. */
  40878. PBRBaseMaterial.prototype.getAnimatables = function () {
  40879. var results = [];
  40880. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  40881. results.push(this._albedoTexture);
  40882. }
  40883. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  40884. results.push(this._ambientTexture);
  40885. }
  40886. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  40887. results.push(this._opacityTexture);
  40888. }
  40889. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  40890. results.push(this._reflectionTexture);
  40891. }
  40892. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  40893. results.push(this._emissiveTexture);
  40894. }
  40895. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  40896. results.push(this._metallicTexture);
  40897. }
  40898. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  40899. results.push(this._reflectivityTexture);
  40900. }
  40901. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  40902. results.push(this._bumpTexture);
  40903. }
  40904. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  40905. results.push(this._lightmapTexture);
  40906. }
  40907. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  40908. results.push(this._refractionTexture);
  40909. }
  40910. return results;
  40911. };
  40912. /**
  40913. * Returns the texture used for reflections.
  40914. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  40915. */
  40916. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  40917. if (this._reflectionTexture) {
  40918. return this._reflectionTexture;
  40919. }
  40920. return this.getScene().environmentTexture;
  40921. };
  40922. /**
  40923. * Returns the texture used for refraction or null if none is used.
  40924. * @returns - Refection texture if present. If no refraction texture and refraction
  40925. * is linked with transparency, returns environment texture. Otherwise, returns null.
  40926. */
  40927. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  40928. if (this._refractionTexture) {
  40929. return this._refractionTexture;
  40930. }
  40931. if (this._linkRefractionWithTransparency) {
  40932. return this.getScene().environmentTexture;
  40933. }
  40934. return null;
  40935. };
  40936. /**
  40937. * Disposes the resources of the material.
  40938. * @param forceDisposeEffect - Forces the disposal of effects.
  40939. * @param forceDisposeTextures - Forces the disposal of all textures.
  40940. */
  40941. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  40942. if (forceDisposeTextures) {
  40943. if (this._albedoTexture) {
  40944. this._albedoTexture.dispose();
  40945. }
  40946. if (this._ambientTexture) {
  40947. this._ambientTexture.dispose();
  40948. }
  40949. if (this._opacityTexture) {
  40950. this._opacityTexture.dispose();
  40951. }
  40952. if (this._reflectionTexture) {
  40953. this._reflectionTexture.dispose();
  40954. }
  40955. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  40956. this._environmentBRDFTexture.dispose();
  40957. }
  40958. if (this._emissiveTexture) {
  40959. this._emissiveTexture.dispose();
  40960. }
  40961. if (this._metallicTexture) {
  40962. this._metallicTexture.dispose();
  40963. }
  40964. if (this._reflectivityTexture) {
  40965. this._reflectivityTexture.dispose();
  40966. }
  40967. if (this._bumpTexture) {
  40968. this._bumpTexture.dispose();
  40969. }
  40970. if (this._lightmapTexture) {
  40971. this._lightmapTexture.dispose();
  40972. }
  40973. if (this._refractionTexture) {
  40974. this._refractionTexture.dispose();
  40975. }
  40976. }
  40977. this._renderTargets.dispose();
  40978. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  40979. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  40980. }
  40981. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  40982. };
  40983. /**
  40984. * Stores the reflectivity values based on metallic roughness workflow.
  40985. */
  40986. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  40987. __decorate([
  40988. BABYLON.serializeAsImageProcessingConfiguration()
  40989. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  40990. __decorate([
  40991. BABYLON.serialize()
  40992. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  40993. __decorate([
  40994. BABYLON.serialize()
  40995. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  40996. return PBRBaseMaterial;
  40997. }(BABYLON.PushMaterial));
  40998. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  40999. })(BABYLON || (BABYLON = {}));
  41000. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  41001. var BABYLON;
  41002. (function (BABYLON) {
  41003. /**
  41004. * The Physically based simple base material of BJS.
  41005. *
  41006. * This enables better naming and convention enforcements on top of the pbrMaterial.
  41007. * It is used as the base class for both the specGloss and metalRough conventions.
  41008. */
  41009. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  41010. __extends(PBRBaseSimpleMaterial, _super);
  41011. /**
  41012. * Instantiates a new PBRMaterial instance.
  41013. *
  41014. * @param name The material name
  41015. * @param scene The scene the material will be use in.
  41016. */
  41017. function PBRBaseSimpleMaterial(name, scene) {
  41018. var _this = _super.call(this, name, scene) || this;
  41019. /**
  41020. * Number of Simultaneous lights allowed on the material.
  41021. */
  41022. _this.maxSimultaneousLights = 4;
  41023. /**
  41024. * If sets to true, disables all the lights affecting the material.
  41025. */
  41026. _this.disableLighting = false;
  41027. /**
  41028. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  41029. */
  41030. _this.invertNormalMapX = false;
  41031. /**
  41032. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  41033. */
  41034. _this.invertNormalMapY = false;
  41035. /**
  41036. * Emissivie color used to self-illuminate the model.
  41037. */
  41038. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  41039. /**
  41040. * Occlusion Channel Strenght.
  41041. */
  41042. _this.occlusionStrength = 1.0;
  41043. _this.useLightmapAsShadowmap = false;
  41044. _this._useAlphaFromAlbedoTexture = true;
  41045. _this._useAmbientInGrayScale = true;
  41046. return _this;
  41047. }
  41048. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  41049. /**
  41050. * Gets the current double sided mode.
  41051. */
  41052. get: function () {
  41053. return this._twoSidedLighting;
  41054. },
  41055. /**
  41056. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  41057. */
  41058. set: function (value) {
  41059. if (this._twoSidedLighting === value) {
  41060. return;
  41061. }
  41062. this._twoSidedLighting = value;
  41063. this.backFaceCulling = !value;
  41064. this._markAllSubMeshesAsTexturesDirty();
  41065. },
  41066. enumerable: true,
  41067. configurable: true
  41068. });
  41069. /**
  41070. * Return the active textures of the material.
  41071. */
  41072. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  41073. var activeTextures = _super.prototype.getActiveTextures.call(this);
  41074. if (this.environmentTexture) {
  41075. activeTextures.push(this.environmentTexture);
  41076. }
  41077. if (this.normalTexture) {
  41078. activeTextures.push(this.normalTexture);
  41079. }
  41080. if (this.emissiveTexture) {
  41081. activeTextures.push(this.emissiveTexture);
  41082. }
  41083. if (this.occlusionTexture) {
  41084. activeTextures.push(this.occlusionTexture);
  41085. }
  41086. if (this.lightmapTexture) {
  41087. activeTextures.push(this.lightmapTexture);
  41088. }
  41089. return activeTextures;
  41090. };
  41091. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  41092. if (_super.prototype.hasTexture.call(this, texture)) {
  41093. return true;
  41094. }
  41095. if (this.lightmapTexture === texture) {
  41096. return true;
  41097. }
  41098. return false;
  41099. };
  41100. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  41101. return "PBRBaseSimpleMaterial";
  41102. };
  41103. __decorate([
  41104. BABYLON.serialize(),
  41105. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  41106. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  41107. __decorate([
  41108. BABYLON.serialize(),
  41109. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  41110. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  41111. __decorate([
  41112. BABYLON.serializeAsTexture(),
  41113. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  41114. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  41115. __decorate([
  41116. BABYLON.serialize(),
  41117. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41118. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  41119. __decorate([
  41120. BABYLON.serialize(),
  41121. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41122. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  41123. __decorate([
  41124. BABYLON.serializeAsTexture(),
  41125. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  41126. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  41127. __decorate([
  41128. BABYLON.serializeAsColor3("emissive"),
  41129. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41130. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  41131. __decorate([
  41132. BABYLON.serializeAsTexture(),
  41133. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41134. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  41135. __decorate([
  41136. BABYLON.serialize(),
  41137. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  41138. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  41139. __decorate([
  41140. BABYLON.serializeAsTexture(),
  41141. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  41142. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  41143. __decorate([
  41144. BABYLON.serialize(),
  41145. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  41146. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  41147. __decorate([
  41148. BABYLON.serialize()
  41149. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  41150. __decorate([
  41151. BABYLON.serializeAsTexture(),
  41152. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  41153. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  41154. __decorate([
  41155. BABYLON.serialize(),
  41156. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41157. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  41158. return PBRBaseSimpleMaterial;
  41159. }(BABYLON.PBRBaseMaterial));
  41160. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  41161. })(BABYLON || (BABYLON = {}));
  41162. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  41163. var BABYLON;
  41164. (function (BABYLON) {
  41165. /**
  41166. * The Physically based material of BJS.
  41167. *
  41168. * This offers the main features of a standard PBR material.
  41169. * For more information, please refer to the documentation :
  41170. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  41171. */
  41172. var PBRMaterial = /** @class */ (function (_super) {
  41173. __extends(PBRMaterial, _super);
  41174. /**
  41175. * Instantiates a new PBRMaterial instance.
  41176. *
  41177. * @param name The material name
  41178. * @param scene The scene the material will be use in.
  41179. */
  41180. function PBRMaterial(name, scene) {
  41181. var _this = _super.call(this, name, scene) || this;
  41182. /**
  41183. * Intensity of the direct lights e.g. the four lights available in your scene.
  41184. * This impacts both the direct diffuse and specular highlights.
  41185. */
  41186. _this.directIntensity = 1.0;
  41187. /**
  41188. * Intensity of the emissive part of the material.
  41189. * This helps controlling the emissive effect without modifying the emissive color.
  41190. */
  41191. _this.emissiveIntensity = 1.0;
  41192. /**
  41193. * Intensity of the environment e.g. how much the environment will light the object
  41194. * either through harmonics for rough material or through the refelction for shiny ones.
  41195. */
  41196. _this.environmentIntensity = 1.0;
  41197. /**
  41198. * This is a special control allowing the reduction of the specular highlights coming from the
  41199. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  41200. */
  41201. _this.specularIntensity = 1.0;
  41202. /**
  41203. * Debug Control allowing disabling the bump map on this material.
  41204. */
  41205. _this.disableBumpMap = false;
  41206. /**
  41207. * AKA Occlusion Texture Intensity in other nomenclature.
  41208. */
  41209. _this.ambientTextureStrength = 1.0;
  41210. /**
  41211. * The color of a material in ambient lighting.
  41212. */
  41213. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  41214. /**
  41215. * AKA Diffuse Color in other nomenclature.
  41216. */
  41217. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  41218. /**
  41219. * AKA Specular Color in other nomenclature.
  41220. */
  41221. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  41222. /**
  41223. * The color reflected from the material.
  41224. */
  41225. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  41226. /**
  41227. * The color emitted from the material.
  41228. */
  41229. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  41230. /**
  41231. * AKA Glossiness in other nomenclature.
  41232. */
  41233. _this.microSurface = 1.0;
  41234. /**
  41235. * source material index of refraction (IOR)' / 'destination material IOR.
  41236. */
  41237. _this.indexOfRefraction = 0.66;
  41238. /**
  41239. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  41240. */
  41241. _this.invertRefractionY = false;
  41242. /**
  41243. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  41244. * Materials half opaque for instance using refraction could benefit from this control.
  41245. */
  41246. _this.linkRefractionWithTransparency = false;
  41247. _this.useLightmapAsShadowmap = false;
  41248. /**
  41249. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  41250. */
  41251. _this.useAlphaFromAlbedoTexture = false;
  41252. /**
  41253. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  41254. */
  41255. _this.forceAlphaTest = false;
  41256. /**
  41257. * Defines the alpha limits in alpha test mode.
  41258. */
  41259. _this.alphaCutOff = 0.4;
  41260. /**
  41261. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  41262. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  41263. */
  41264. _this.useSpecularOverAlpha = true;
  41265. /**
  41266. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  41267. */
  41268. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  41269. /**
  41270. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  41271. */
  41272. _this.useRoughnessFromMetallicTextureAlpha = true;
  41273. /**
  41274. * Specifies if the metallic texture contains the roughness information in its green channel.
  41275. */
  41276. _this.useRoughnessFromMetallicTextureGreen = false;
  41277. /**
  41278. * Specifies if the metallic texture contains the metallness information in its blue channel.
  41279. */
  41280. _this.useMetallnessFromMetallicTextureBlue = false;
  41281. /**
  41282. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  41283. */
  41284. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  41285. /**
  41286. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  41287. */
  41288. _this.useAmbientInGrayScale = false;
  41289. /**
  41290. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  41291. * The material will try to infer what glossiness each pixel should be.
  41292. */
  41293. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  41294. /**
  41295. * BJS is using an harcoded light falloff based on a manually sets up range.
  41296. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  41297. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  41298. */
  41299. _this.usePhysicalLightFalloff = true;
  41300. /**
  41301. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  41302. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  41303. */
  41304. _this.useRadianceOverAlpha = true;
  41305. /**
  41306. * Allows using the bump map in parallax mode.
  41307. */
  41308. _this.useParallax = false;
  41309. /**
  41310. * Allows using the bump map in parallax occlusion mode.
  41311. */
  41312. _this.useParallaxOcclusion = false;
  41313. /**
  41314. * Controls the scale bias of the parallax mode.
  41315. */
  41316. _this.parallaxScaleBias = 0.05;
  41317. /**
  41318. * If sets to true, disables all the lights affecting the material.
  41319. */
  41320. _this.disableLighting = false;
  41321. /**
  41322. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  41323. */
  41324. _this.forceIrradianceInFragment = false;
  41325. /**
  41326. * Number of Simultaneous lights allowed on the material.
  41327. */
  41328. _this.maxSimultaneousLights = 4;
  41329. /**
  41330. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  41331. */
  41332. _this.invertNormalMapX = false;
  41333. /**
  41334. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  41335. */
  41336. _this.invertNormalMapY = false;
  41337. /**
  41338. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  41339. */
  41340. _this.twoSidedLighting = false;
  41341. /**
  41342. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  41343. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  41344. */
  41345. _this.useAlphaFresnel = false;
  41346. /**
  41347. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  41348. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  41349. */
  41350. _this.useLinearAlphaFresnel = false;
  41351. /**
  41352. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  41353. * And/Or occlude the blended part.
  41354. */
  41355. _this.environmentBRDFTexture = null;
  41356. /**
  41357. * Force normal to face away from face.
  41358. */
  41359. _this.forceNormalForward = false;
  41360. /**
  41361. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  41362. * makes the reflect vector face the model (under horizon).
  41363. */
  41364. _this.useHorizonOcclusion = true;
  41365. /**
  41366. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  41367. * too much the area relying on ambient texture to define their ambient occlusion.
  41368. */
  41369. _this.useRadianceOcclusion = true;
  41370. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  41371. return _this;
  41372. }
  41373. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  41374. /**
  41375. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  41376. */
  41377. get: function () {
  41378. return this._PBRMATERIAL_OPAQUE;
  41379. },
  41380. enumerable: true,
  41381. configurable: true
  41382. });
  41383. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  41384. /**
  41385. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  41386. */
  41387. get: function () {
  41388. return this._PBRMATERIAL_ALPHATEST;
  41389. },
  41390. enumerable: true,
  41391. configurable: true
  41392. });
  41393. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  41394. /**
  41395. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  41396. */
  41397. get: function () {
  41398. return this._PBRMATERIAL_ALPHABLEND;
  41399. },
  41400. enumerable: true,
  41401. configurable: true
  41402. });
  41403. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  41404. /**
  41405. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  41406. * They are also discarded below the alpha cutoff threshold to improve performances.
  41407. */
  41408. get: function () {
  41409. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  41410. },
  41411. enumerable: true,
  41412. configurable: true
  41413. });
  41414. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  41415. /**
  41416. * Gets the image processing configuration used either in this material.
  41417. */
  41418. get: function () {
  41419. return this._imageProcessingConfiguration;
  41420. },
  41421. /**
  41422. * Sets the Default image processing configuration used either in the this material.
  41423. *
  41424. * If sets to null, the scene one is in use.
  41425. */
  41426. set: function (value) {
  41427. this._attachImageProcessingConfiguration(value);
  41428. // Ensure the effect will be rebuilt.
  41429. this._markAllSubMeshesAsTexturesDirty();
  41430. },
  41431. enumerable: true,
  41432. configurable: true
  41433. });
  41434. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  41435. /**
  41436. * Gets wether the color curves effect is enabled.
  41437. */
  41438. get: function () {
  41439. return this.imageProcessingConfiguration.colorCurvesEnabled;
  41440. },
  41441. /**
  41442. * Sets wether the color curves effect is enabled.
  41443. */
  41444. set: function (value) {
  41445. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  41446. },
  41447. enumerable: true,
  41448. configurable: true
  41449. });
  41450. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  41451. /**
  41452. * Gets wether the color grading effect is enabled.
  41453. */
  41454. get: function () {
  41455. return this.imageProcessingConfiguration.colorGradingEnabled;
  41456. },
  41457. /**
  41458. * Gets wether the color grading effect is enabled.
  41459. */
  41460. set: function (value) {
  41461. this.imageProcessingConfiguration.colorGradingEnabled = value;
  41462. },
  41463. enumerable: true,
  41464. configurable: true
  41465. });
  41466. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  41467. /**
  41468. * Gets wether tonemapping is enabled or not.
  41469. */
  41470. get: function () {
  41471. return this._imageProcessingConfiguration.toneMappingEnabled;
  41472. },
  41473. /**
  41474. * Sets wether tonemapping is enabled or not
  41475. */
  41476. set: function (value) {
  41477. this._imageProcessingConfiguration.toneMappingEnabled = value;
  41478. },
  41479. enumerable: true,
  41480. configurable: true
  41481. });
  41482. ;
  41483. ;
  41484. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  41485. /**
  41486. * The camera exposure used on this material.
  41487. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  41488. * This corresponds to a photographic exposure.
  41489. */
  41490. get: function () {
  41491. return this._imageProcessingConfiguration.exposure;
  41492. },
  41493. /**
  41494. * The camera exposure used on this material.
  41495. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  41496. * This corresponds to a photographic exposure.
  41497. */
  41498. set: function (value) {
  41499. this._imageProcessingConfiguration.exposure = value;
  41500. },
  41501. enumerable: true,
  41502. configurable: true
  41503. });
  41504. ;
  41505. ;
  41506. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  41507. /**
  41508. * Gets The camera contrast used on this material.
  41509. */
  41510. get: function () {
  41511. return this._imageProcessingConfiguration.contrast;
  41512. },
  41513. /**
  41514. * Sets The camera contrast used on this material.
  41515. */
  41516. set: function (value) {
  41517. this._imageProcessingConfiguration.contrast = value;
  41518. },
  41519. enumerable: true,
  41520. configurable: true
  41521. });
  41522. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  41523. /**
  41524. * Gets the Color Grading 2D Lookup Texture.
  41525. */
  41526. get: function () {
  41527. return this._imageProcessingConfiguration.colorGradingTexture;
  41528. },
  41529. /**
  41530. * Sets the Color Grading 2D Lookup Texture.
  41531. */
  41532. set: function (value) {
  41533. this._imageProcessingConfiguration.colorGradingTexture = value;
  41534. },
  41535. enumerable: true,
  41536. configurable: true
  41537. });
  41538. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  41539. /**
  41540. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  41541. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  41542. * 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;
  41543. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  41544. */
  41545. get: function () {
  41546. return this._imageProcessingConfiguration.colorCurves;
  41547. },
  41548. /**
  41549. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  41550. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  41551. * 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;
  41552. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  41553. */
  41554. set: function (value) {
  41555. this._imageProcessingConfiguration.colorCurves = value;
  41556. },
  41557. enumerable: true,
  41558. configurable: true
  41559. });
  41560. /**
  41561. * Returns the name of this material class.
  41562. */
  41563. PBRMaterial.prototype.getClassName = function () {
  41564. return "PBRMaterial";
  41565. };
  41566. /**
  41567. * Returns an array of the actively used textures.
  41568. * @returns - Array of BaseTextures
  41569. */
  41570. PBRMaterial.prototype.getActiveTextures = function () {
  41571. var activeTextures = _super.prototype.getActiveTextures.call(this);
  41572. if (this._albedoTexture) {
  41573. activeTextures.push(this._albedoTexture);
  41574. }
  41575. if (this._ambientTexture) {
  41576. activeTextures.push(this._ambientTexture);
  41577. }
  41578. if (this._opacityTexture) {
  41579. activeTextures.push(this._opacityTexture);
  41580. }
  41581. if (this._reflectionTexture) {
  41582. activeTextures.push(this._reflectionTexture);
  41583. }
  41584. if (this._emissiveTexture) {
  41585. activeTextures.push(this._emissiveTexture);
  41586. }
  41587. if (this._reflectivityTexture) {
  41588. activeTextures.push(this._reflectivityTexture);
  41589. }
  41590. if (this._metallicTexture) {
  41591. activeTextures.push(this._metallicTexture);
  41592. }
  41593. if (this._microSurfaceTexture) {
  41594. activeTextures.push(this._microSurfaceTexture);
  41595. }
  41596. if (this._bumpTexture) {
  41597. activeTextures.push(this._bumpTexture);
  41598. }
  41599. if (this._lightmapTexture) {
  41600. activeTextures.push(this._lightmapTexture);
  41601. }
  41602. if (this._refractionTexture) {
  41603. activeTextures.push(this._refractionTexture);
  41604. }
  41605. return activeTextures;
  41606. };
  41607. /**
  41608. * Checks to see if a texture is used in the material.
  41609. * @param texture - Base texture to use.
  41610. * @returns - Boolean specifying if a texture is used in the material.
  41611. */
  41612. PBRMaterial.prototype.hasTexture = function (texture) {
  41613. if (_super.prototype.hasTexture.call(this, texture)) {
  41614. return true;
  41615. }
  41616. if (this._albedoTexture === texture) {
  41617. return true;
  41618. }
  41619. if (this._ambientTexture === texture) {
  41620. return true;
  41621. }
  41622. if (this._opacityTexture === texture) {
  41623. return true;
  41624. }
  41625. if (this._reflectionTexture === texture) {
  41626. return true;
  41627. }
  41628. if (this._reflectivityTexture === texture) {
  41629. return true;
  41630. }
  41631. if (this._metallicTexture === texture) {
  41632. return true;
  41633. }
  41634. if (this._microSurfaceTexture === texture) {
  41635. return true;
  41636. }
  41637. if (this._bumpTexture === texture) {
  41638. return true;
  41639. }
  41640. if (this._lightmapTexture === texture) {
  41641. return true;
  41642. }
  41643. if (this._refractionTexture === texture) {
  41644. return true;
  41645. }
  41646. return false;
  41647. };
  41648. /**
  41649. * Makes a duplicate of the current material.
  41650. * @param name - name to use for the new material.
  41651. */
  41652. PBRMaterial.prototype.clone = function (name) {
  41653. var _this = this;
  41654. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  41655. clone.id = name;
  41656. clone.name = name;
  41657. return clone;
  41658. };
  41659. /**
  41660. * Serializes this PBR Material.
  41661. * @returns - An object with the serialized material.
  41662. */
  41663. PBRMaterial.prototype.serialize = function () {
  41664. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  41665. serializationObject.customType = "BABYLON.PBRMaterial";
  41666. return serializationObject;
  41667. };
  41668. // Statics
  41669. /**
  41670. * Parses a PBR Material from a serialized object.
  41671. * @param source - Serialized object.
  41672. * @param scene - BJS scene instance.
  41673. * @param rootUrl - url for the scene object
  41674. * @returns - PBRMaterial
  41675. */
  41676. PBRMaterial.Parse = function (source, scene, rootUrl) {
  41677. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  41678. };
  41679. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  41680. /**
  41681. * Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  41682. */
  41683. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  41684. /**
  41685. * Represents the value for Alpha Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  41686. */
  41687. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  41688. /**
  41689. * 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.
  41690. * They are also discarded below the alpha cutoff threshold to improve performances.
  41691. */
  41692. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  41693. __decorate([
  41694. BABYLON.serialize(),
  41695. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41696. ], PBRMaterial.prototype, "directIntensity", void 0);
  41697. __decorate([
  41698. BABYLON.serialize(),
  41699. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41700. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  41701. __decorate([
  41702. BABYLON.serialize(),
  41703. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41704. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  41705. __decorate([
  41706. BABYLON.serialize(),
  41707. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41708. ], PBRMaterial.prototype, "specularIntensity", void 0);
  41709. __decorate([
  41710. BABYLON.serialize(),
  41711. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41712. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  41713. __decorate([
  41714. BABYLON.serializeAsTexture(),
  41715. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41716. ], PBRMaterial.prototype, "albedoTexture", void 0);
  41717. __decorate([
  41718. BABYLON.serializeAsTexture(),
  41719. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41720. ], PBRMaterial.prototype, "ambientTexture", void 0);
  41721. __decorate([
  41722. BABYLON.serialize(),
  41723. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41724. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  41725. __decorate([
  41726. BABYLON.serializeAsTexture(),
  41727. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  41728. ], PBRMaterial.prototype, "opacityTexture", void 0);
  41729. __decorate([
  41730. BABYLON.serializeAsTexture(),
  41731. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41732. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  41733. __decorate([
  41734. BABYLON.serializeAsTexture(),
  41735. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41736. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  41737. __decorate([
  41738. BABYLON.serializeAsTexture(),
  41739. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41740. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  41741. __decorate([
  41742. BABYLON.serializeAsTexture(),
  41743. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41744. ], PBRMaterial.prototype, "metallicTexture", void 0);
  41745. __decorate([
  41746. BABYLON.serialize(),
  41747. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41748. ], PBRMaterial.prototype, "metallic", void 0);
  41749. __decorate([
  41750. BABYLON.serialize(),
  41751. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41752. ], PBRMaterial.prototype, "roughness", void 0);
  41753. __decorate([
  41754. BABYLON.serializeAsTexture(),
  41755. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41756. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  41757. __decorate([
  41758. BABYLON.serializeAsTexture(),
  41759. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41760. ], PBRMaterial.prototype, "bumpTexture", void 0);
  41761. __decorate([
  41762. BABYLON.serializeAsTexture(),
  41763. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  41764. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  41765. __decorate([
  41766. BABYLON.serializeAsTexture(),
  41767. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41768. ], PBRMaterial.prototype, "refractionTexture", void 0);
  41769. __decorate([
  41770. BABYLON.serializeAsColor3("ambient"),
  41771. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41772. ], PBRMaterial.prototype, "ambientColor", void 0);
  41773. __decorate([
  41774. BABYLON.serializeAsColor3("albedo"),
  41775. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41776. ], PBRMaterial.prototype, "albedoColor", void 0);
  41777. __decorate([
  41778. BABYLON.serializeAsColor3("reflectivity"),
  41779. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41780. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  41781. __decorate([
  41782. BABYLON.serializeAsColor3("reflection"),
  41783. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41784. ], PBRMaterial.prototype, "reflectionColor", void 0);
  41785. __decorate([
  41786. BABYLON.serializeAsColor3("emissive"),
  41787. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41788. ], PBRMaterial.prototype, "emissiveColor", void 0);
  41789. __decorate([
  41790. BABYLON.serialize(),
  41791. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41792. ], PBRMaterial.prototype, "microSurface", void 0);
  41793. __decorate([
  41794. BABYLON.serialize(),
  41795. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41796. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  41797. __decorate([
  41798. BABYLON.serialize(),
  41799. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41800. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  41801. __decorate([
  41802. BABYLON.serialize(),
  41803. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41804. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  41805. __decorate([
  41806. BABYLON.serialize(),
  41807. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41808. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  41809. __decorate([
  41810. BABYLON.serialize(),
  41811. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  41812. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  41813. __decorate([
  41814. BABYLON.serialize(),
  41815. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  41816. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  41817. __decorate([
  41818. BABYLON.serialize(),
  41819. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  41820. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  41821. __decorate([
  41822. BABYLON.serialize(),
  41823. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41824. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  41825. __decorate([
  41826. BABYLON.serialize(),
  41827. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41828. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  41829. __decorate([
  41830. BABYLON.serialize(),
  41831. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41832. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  41833. __decorate([
  41834. BABYLON.serialize(),
  41835. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41836. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  41837. __decorate([
  41838. BABYLON.serialize(),
  41839. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41840. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  41841. __decorate([
  41842. BABYLON.serialize(),
  41843. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41844. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  41845. __decorate([
  41846. BABYLON.serialize(),
  41847. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41848. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  41849. __decorate([
  41850. BABYLON.serialize(),
  41851. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41852. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  41853. __decorate([
  41854. BABYLON.serialize(),
  41855. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41856. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  41857. __decorate([
  41858. BABYLON.serialize(),
  41859. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41860. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  41861. __decorate([
  41862. BABYLON.serialize(),
  41863. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41864. ], PBRMaterial.prototype, "useParallax", void 0);
  41865. __decorate([
  41866. BABYLON.serialize(),
  41867. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41868. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  41869. __decorate([
  41870. BABYLON.serialize(),
  41871. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41872. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  41873. __decorate([
  41874. BABYLON.serialize(),
  41875. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  41876. ], PBRMaterial.prototype, "disableLighting", void 0);
  41877. __decorate([
  41878. BABYLON.serialize(),
  41879. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41880. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  41881. __decorate([
  41882. BABYLON.serialize(),
  41883. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  41884. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  41885. __decorate([
  41886. BABYLON.serialize(),
  41887. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41888. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  41889. __decorate([
  41890. BABYLON.serialize(),
  41891. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41892. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  41893. __decorate([
  41894. BABYLON.serialize(),
  41895. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41896. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  41897. __decorate([
  41898. BABYLON.serialize(),
  41899. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41900. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  41901. __decorate([
  41902. BABYLON.serialize(),
  41903. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41904. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  41905. __decorate([
  41906. BABYLON.serializeAsTexture(),
  41907. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41908. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  41909. __decorate([
  41910. BABYLON.serialize(),
  41911. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41912. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  41913. __decorate([
  41914. BABYLON.serialize(),
  41915. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41916. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  41917. __decorate([
  41918. BABYLON.serialize(),
  41919. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41920. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  41921. return PBRMaterial;
  41922. }(BABYLON.PBRBaseMaterial));
  41923. BABYLON.PBRMaterial = PBRMaterial;
  41924. })(BABYLON || (BABYLON = {}));
  41925. //# sourceMappingURL=babylon.pbrMaterial.js.map
  41926. var BABYLON;
  41927. (function (BABYLON) {
  41928. /**
  41929. * The PBR material of BJS following the metal roughness convention.
  41930. *
  41931. * This fits to the PBR convention in the GLTF definition:
  41932. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  41933. */
  41934. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  41935. __extends(PBRMetallicRoughnessMaterial, _super);
  41936. /**
  41937. * Instantiates a new PBRMetalRoughnessMaterial instance.
  41938. *
  41939. * @param name The material name
  41940. * @param scene The scene the material will be use in.
  41941. */
  41942. function PBRMetallicRoughnessMaterial(name, scene) {
  41943. var _this = _super.call(this, name, scene) || this;
  41944. _this._useRoughnessFromMetallicTextureAlpha = false;
  41945. _this._useRoughnessFromMetallicTextureGreen = true;
  41946. _this._useMetallnessFromMetallicTextureBlue = true;
  41947. _this._forceMetallicWorkflow = true;
  41948. return _this;
  41949. }
  41950. /**
  41951. * Return the currrent class name of the material.
  41952. */
  41953. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  41954. return "PBRMetallicRoughnessMaterial";
  41955. };
  41956. /**
  41957. * Return the active textures of the material.
  41958. */
  41959. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  41960. var activeTextures = _super.prototype.getActiveTextures.call(this);
  41961. if (this.baseTexture) {
  41962. activeTextures.push(this.baseTexture);
  41963. }
  41964. if (this.metallicRoughnessTexture) {
  41965. activeTextures.push(this.metallicRoughnessTexture);
  41966. }
  41967. return activeTextures;
  41968. };
  41969. /**
  41970. * Checks to see if a texture is used in the material.
  41971. * @param texture - Base texture to use.
  41972. * @returns - Boolean specifying if a texture is used in the material.
  41973. */
  41974. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  41975. if (_super.prototype.hasTexture.call(this, texture)) {
  41976. return true;
  41977. }
  41978. if (this.baseTexture === texture) {
  41979. return true;
  41980. }
  41981. if (this.metallicRoughnessTexture === texture) {
  41982. return true;
  41983. }
  41984. return false;
  41985. };
  41986. /**
  41987. * Makes a duplicate of the current material.
  41988. * @param name - name to use for the new material.
  41989. */
  41990. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  41991. var _this = this;
  41992. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  41993. clone.id = name;
  41994. clone.name = name;
  41995. return clone;
  41996. };
  41997. /**
  41998. * Serialize the material to a parsable JSON object.
  41999. */
  42000. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  42001. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  42002. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  42003. return serializationObject;
  42004. };
  42005. /**
  42006. * Parses a JSON object correponding to the serialize function.
  42007. */
  42008. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  42009. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  42010. };
  42011. __decorate([
  42012. BABYLON.serializeAsColor3(),
  42013. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  42014. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  42015. __decorate([
  42016. BABYLON.serializeAsTexture(),
  42017. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  42018. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  42019. __decorate([
  42020. BABYLON.serialize(),
  42021. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42022. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  42023. __decorate([
  42024. BABYLON.serialize(),
  42025. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42026. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  42027. __decorate([
  42028. BABYLON.serializeAsTexture(),
  42029. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  42030. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  42031. return PBRMetallicRoughnessMaterial;
  42032. }(BABYLON.PBRBaseSimpleMaterial));
  42033. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  42034. })(BABYLON || (BABYLON = {}));
  42035. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  42036. var BABYLON;
  42037. (function (BABYLON) {
  42038. /**
  42039. * The PBR material of BJS following the specular glossiness convention.
  42040. *
  42041. * This fits to the PBR convention in the GLTF definition:
  42042. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  42043. */
  42044. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  42045. __extends(PBRSpecularGlossinessMaterial, _super);
  42046. /**
  42047. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  42048. *
  42049. * @param name The material name
  42050. * @param scene The scene the material will be use in.
  42051. */
  42052. function PBRSpecularGlossinessMaterial(name, scene) {
  42053. var _this = _super.call(this, name, scene) || this;
  42054. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  42055. return _this;
  42056. }
  42057. /**
  42058. * Return the currrent class name of the material.
  42059. */
  42060. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  42061. return "PBRSpecularGlossinessMaterial";
  42062. };
  42063. /**
  42064. * Return the active textures of the material.
  42065. */
  42066. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  42067. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42068. if (this.diffuseTexture) {
  42069. activeTextures.push(this.diffuseTexture);
  42070. }
  42071. if (this.specularGlossinessTexture) {
  42072. activeTextures.push(this.specularGlossinessTexture);
  42073. }
  42074. return activeTextures;
  42075. };
  42076. /**
  42077. * Checks to see if a texture is used in the material.
  42078. * @param texture - Base texture to use.
  42079. * @returns - Boolean specifying if a texture is used in the material.
  42080. */
  42081. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  42082. if (_super.prototype.hasTexture.call(this, texture)) {
  42083. return true;
  42084. }
  42085. if (this.diffuseTexture === texture) {
  42086. return true;
  42087. }
  42088. if (this.specularGlossinessTexture === texture) {
  42089. return true;
  42090. }
  42091. return false;
  42092. };
  42093. /**
  42094. * Makes a duplicate of the current material.
  42095. * @param name - name to use for the new material.
  42096. */
  42097. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  42098. var _this = this;
  42099. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  42100. clone.id = name;
  42101. clone.name = name;
  42102. return clone;
  42103. };
  42104. /**
  42105. * Serialize the material to a parsable JSON object.
  42106. */
  42107. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  42108. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  42109. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  42110. return serializationObject;
  42111. };
  42112. /**
  42113. * Parses a JSON object correponding to the serialize function.
  42114. */
  42115. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  42116. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  42117. };
  42118. __decorate([
  42119. BABYLON.serializeAsColor3("diffuse"),
  42120. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  42121. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  42122. __decorate([
  42123. BABYLON.serializeAsTexture(),
  42124. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  42125. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  42126. __decorate([
  42127. BABYLON.serializeAsColor3("specular"),
  42128. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  42129. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  42130. __decorate([
  42131. BABYLON.serialize(),
  42132. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  42133. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  42134. __decorate([
  42135. BABYLON.serializeAsTexture(),
  42136. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  42137. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  42138. return PBRSpecularGlossinessMaterial;
  42139. }(BABYLON.PBRBaseSimpleMaterial));
  42140. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  42141. })(BABYLON || (BABYLON = {}));
  42142. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  42143. var BABYLON;
  42144. (function (BABYLON) {
  42145. BABYLON.CameraInputTypes = {};
  42146. var CameraInputsManager = /** @class */ (function () {
  42147. function CameraInputsManager(camera) {
  42148. this.attached = {};
  42149. this.camera = camera;
  42150. this.checkInputs = function () { };
  42151. }
  42152. /**
  42153. * Add an input method to a camera.
  42154. * builtin inputs example: camera.inputs.addGamepad();
  42155. * custom inputs example: camera.inputs.add(new BABYLON.FreeCameraGamepadInput());
  42156. * @param input camera input method
  42157. */
  42158. CameraInputsManager.prototype.add = function (input) {
  42159. var type = input.getSimpleName();
  42160. if (this.attached[type]) {
  42161. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  42162. return;
  42163. }
  42164. this.attached[type] = input;
  42165. input.camera = this.camera;
  42166. //for checkInputs, we are dynamically creating a function
  42167. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  42168. if (input.checkInputs) {
  42169. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  42170. }
  42171. if (this.attachedElement) {
  42172. input.attachControl(this.attachedElement);
  42173. }
  42174. };
  42175. /**
  42176. * Remove a specific input method from a camera
  42177. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  42178. * @param inputToRemove camera input method
  42179. */
  42180. CameraInputsManager.prototype.remove = function (inputToRemove) {
  42181. for (var cam in this.attached) {
  42182. var input = this.attached[cam];
  42183. if (input === inputToRemove) {
  42184. input.detachControl(this.attachedElement);
  42185. input.camera = null;
  42186. delete this.attached[cam];
  42187. this.rebuildInputCheck();
  42188. }
  42189. }
  42190. };
  42191. CameraInputsManager.prototype.removeByType = function (inputType) {
  42192. for (var cam in this.attached) {
  42193. var input = this.attached[cam];
  42194. if (input.getClassName() === inputType) {
  42195. input.detachControl(this.attachedElement);
  42196. input.camera = null;
  42197. delete this.attached[cam];
  42198. this.rebuildInputCheck();
  42199. }
  42200. }
  42201. };
  42202. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  42203. var current = this.checkInputs;
  42204. return function () {
  42205. current();
  42206. fn();
  42207. };
  42208. };
  42209. CameraInputsManager.prototype.attachInput = function (input) {
  42210. if (this.attachedElement) {
  42211. input.attachControl(this.attachedElement, this.noPreventDefault);
  42212. }
  42213. };
  42214. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  42215. if (noPreventDefault === void 0) { noPreventDefault = false; }
  42216. if (this.attachedElement) {
  42217. return;
  42218. }
  42219. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  42220. this.attachedElement = element;
  42221. this.noPreventDefault = noPreventDefault;
  42222. for (var cam in this.attached) {
  42223. this.attached[cam].attachControl(element, noPreventDefault);
  42224. }
  42225. };
  42226. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  42227. if (disconnect === void 0) { disconnect = false; }
  42228. if (this.attachedElement !== element) {
  42229. return;
  42230. }
  42231. for (var cam in this.attached) {
  42232. this.attached[cam].detachControl(element);
  42233. if (disconnect) {
  42234. this.attached[cam].camera = null;
  42235. }
  42236. }
  42237. this.attachedElement = null;
  42238. };
  42239. CameraInputsManager.prototype.rebuildInputCheck = function () {
  42240. this.checkInputs = function () { };
  42241. for (var cam in this.attached) {
  42242. var input = this.attached[cam];
  42243. if (input.checkInputs) {
  42244. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  42245. }
  42246. }
  42247. };
  42248. /**
  42249. * Remove all attached input methods from a camera
  42250. */
  42251. CameraInputsManager.prototype.clear = function () {
  42252. if (this.attachedElement) {
  42253. this.detachElement(this.attachedElement, true);
  42254. }
  42255. this.attached = {};
  42256. this.attachedElement = null;
  42257. this.checkInputs = function () { };
  42258. };
  42259. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  42260. var inputs = {};
  42261. for (var cam in this.attached) {
  42262. var input = this.attached[cam];
  42263. var res = BABYLON.SerializationHelper.Serialize(input);
  42264. inputs[input.getClassName()] = res;
  42265. }
  42266. serializedCamera.inputsmgr = inputs;
  42267. };
  42268. CameraInputsManager.prototype.parse = function (parsedCamera) {
  42269. var parsedInputs = parsedCamera.inputsmgr;
  42270. if (parsedInputs) {
  42271. this.clear();
  42272. for (var n in parsedInputs) {
  42273. var construct = BABYLON.CameraInputTypes[n];
  42274. if (construct) {
  42275. var parsedinput = parsedInputs[n];
  42276. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  42277. this.add(input);
  42278. }
  42279. }
  42280. }
  42281. else {
  42282. //2016-03-08 this part is for managing backward compatibility
  42283. for (var n in this.attached) {
  42284. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  42285. if (construct) {
  42286. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  42287. this.remove(this.attached[n]);
  42288. this.add(input);
  42289. }
  42290. }
  42291. }
  42292. };
  42293. return CameraInputsManager;
  42294. }());
  42295. BABYLON.CameraInputsManager = CameraInputsManager;
  42296. })(BABYLON || (BABYLON = {}));
  42297. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  42298. var BABYLON;
  42299. (function (BABYLON) {
  42300. var TargetCamera = /** @class */ (function (_super) {
  42301. __extends(TargetCamera, _super);
  42302. function TargetCamera(name, position, scene) {
  42303. var _this = _super.call(this, name, position, scene) || this;
  42304. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  42305. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  42306. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  42307. _this.speed = 2.0;
  42308. _this.noRotationConstraint = false;
  42309. _this.lockedTarget = null;
  42310. _this._currentTarget = BABYLON.Vector3.Zero();
  42311. _this._viewMatrix = BABYLON.Matrix.Zero();
  42312. _this._camMatrix = BABYLON.Matrix.Zero();
  42313. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  42314. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  42315. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  42316. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  42317. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  42318. _this._lookAtTemp = BABYLON.Matrix.Zero();
  42319. _this._tempMatrix = BABYLON.Matrix.Zero();
  42320. return _this;
  42321. }
  42322. TargetCamera.prototype.getFrontPosition = function (distance) {
  42323. this.getWorldMatrix();
  42324. var direction = this.getTarget().subtract(this.position);
  42325. direction.normalize();
  42326. direction.scaleInPlace(distance);
  42327. return this.globalPosition.add(direction);
  42328. };
  42329. TargetCamera.prototype._getLockedTargetPosition = function () {
  42330. if (!this.lockedTarget) {
  42331. return null;
  42332. }
  42333. if (this.lockedTarget.absolutePosition) {
  42334. this.lockedTarget.computeWorldMatrix();
  42335. }
  42336. return this.lockedTarget.absolutePosition || this.lockedTarget;
  42337. };
  42338. TargetCamera.prototype.storeState = function () {
  42339. this._storedPosition = this.position.clone();
  42340. this._storedRotation = this.rotation.clone();
  42341. if (this.rotationQuaternion) {
  42342. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  42343. }
  42344. return _super.prototype.storeState.call(this);
  42345. };
  42346. /**
  42347. * Restored camera state. You must call storeState() first
  42348. */
  42349. TargetCamera.prototype._restoreStateValues = function () {
  42350. if (!_super.prototype._restoreStateValues.call(this)) {
  42351. return false;
  42352. }
  42353. this.position = this._storedPosition.clone();
  42354. this.rotation = this._storedRotation.clone();
  42355. if (this.rotationQuaternion) {
  42356. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  42357. }
  42358. this.cameraDirection.copyFromFloats(0, 0, 0);
  42359. this.cameraRotation.copyFromFloats(0, 0);
  42360. return true;
  42361. };
  42362. // Cache
  42363. TargetCamera.prototype._initCache = function () {
  42364. _super.prototype._initCache.call(this);
  42365. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  42366. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  42367. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  42368. };
  42369. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  42370. if (!ignoreParentClass) {
  42371. _super.prototype._updateCache.call(this);
  42372. }
  42373. var lockedTargetPosition = this._getLockedTargetPosition();
  42374. if (!lockedTargetPosition) {
  42375. this._cache.lockedTarget = null;
  42376. }
  42377. else {
  42378. if (!this._cache.lockedTarget) {
  42379. this._cache.lockedTarget = lockedTargetPosition.clone();
  42380. }
  42381. else {
  42382. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  42383. }
  42384. }
  42385. this._cache.rotation.copyFrom(this.rotation);
  42386. if (this.rotationQuaternion)
  42387. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  42388. };
  42389. // Synchronized
  42390. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  42391. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  42392. return false;
  42393. }
  42394. var lockedTargetPosition = this._getLockedTargetPosition();
  42395. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  42396. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  42397. };
  42398. // Methods
  42399. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  42400. var engine = this.getEngine();
  42401. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  42402. };
  42403. // Target
  42404. TargetCamera.prototype.setTarget = function (target) {
  42405. this.upVector.normalize();
  42406. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  42407. this._camMatrix.invert();
  42408. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  42409. var vDir = target.subtract(this.position);
  42410. if (vDir.x >= 0.0) {
  42411. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  42412. }
  42413. else {
  42414. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  42415. }
  42416. this.rotation.z = 0;
  42417. if (isNaN(this.rotation.x)) {
  42418. this.rotation.x = 0;
  42419. }
  42420. if (isNaN(this.rotation.y)) {
  42421. this.rotation.y = 0;
  42422. }
  42423. if (isNaN(this.rotation.z)) {
  42424. this.rotation.z = 0;
  42425. }
  42426. if (this.rotationQuaternion) {
  42427. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  42428. }
  42429. };
  42430. /**
  42431. * Return the current target position of the camera. This value is expressed in local space.
  42432. */
  42433. TargetCamera.prototype.getTarget = function () {
  42434. return this._currentTarget;
  42435. };
  42436. TargetCamera.prototype._decideIfNeedsToMove = function () {
  42437. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  42438. };
  42439. TargetCamera.prototype._updatePosition = function () {
  42440. if (this.parent) {
  42441. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  42442. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  42443. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  42444. return;
  42445. }
  42446. this.position.addInPlace(this.cameraDirection);
  42447. };
  42448. TargetCamera.prototype._checkInputs = function () {
  42449. var needToMove = this._decideIfNeedsToMove();
  42450. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  42451. // Move
  42452. if (needToMove) {
  42453. this._updatePosition();
  42454. }
  42455. // Rotate
  42456. if (needToRotate) {
  42457. this.rotation.x += this.cameraRotation.x;
  42458. this.rotation.y += this.cameraRotation.y;
  42459. //rotate, if quaternion is set and rotation was used
  42460. if (this.rotationQuaternion) {
  42461. var len = this.rotation.lengthSquared();
  42462. if (len) {
  42463. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  42464. }
  42465. }
  42466. if (!this.noRotationConstraint) {
  42467. var limit = (Math.PI / 2) * 0.95;
  42468. if (this.rotation.x > limit)
  42469. this.rotation.x = limit;
  42470. if (this.rotation.x < -limit)
  42471. this.rotation.x = -limit;
  42472. }
  42473. }
  42474. // Inertia
  42475. if (needToMove) {
  42476. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  42477. this.cameraDirection.x = 0;
  42478. }
  42479. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  42480. this.cameraDirection.y = 0;
  42481. }
  42482. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  42483. this.cameraDirection.z = 0;
  42484. }
  42485. this.cameraDirection.scaleInPlace(this.inertia);
  42486. }
  42487. if (needToRotate) {
  42488. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  42489. this.cameraRotation.x = 0;
  42490. }
  42491. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  42492. this.cameraRotation.y = 0;
  42493. }
  42494. this.cameraRotation.scaleInPlace(this.inertia);
  42495. }
  42496. _super.prototype._checkInputs.call(this);
  42497. };
  42498. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  42499. if (this.rotationQuaternion) {
  42500. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  42501. }
  42502. else {
  42503. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  42504. }
  42505. //update the up vector!
  42506. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  42507. };
  42508. TargetCamera.prototype._getViewMatrix = function () {
  42509. if (this.lockedTarget) {
  42510. this.setTarget(this._getLockedTargetPosition());
  42511. }
  42512. // Compute
  42513. this._updateCameraRotationMatrix();
  42514. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  42515. // Computing target and final matrix
  42516. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  42517. if (this.getScene().useRightHandedSystem) {
  42518. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  42519. }
  42520. else {
  42521. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  42522. }
  42523. return this._viewMatrix;
  42524. };
  42525. /**
  42526. * @override
  42527. * Override Camera.createRigCamera
  42528. */
  42529. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  42530. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  42531. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  42532. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  42533. if (!this.rotationQuaternion) {
  42534. this.rotationQuaternion = new BABYLON.Quaternion();
  42535. }
  42536. rigCamera._cameraRigParams = {};
  42537. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  42538. }
  42539. return rigCamera;
  42540. }
  42541. return null;
  42542. };
  42543. /**
  42544. * @override
  42545. * Override Camera._updateRigCameras
  42546. */
  42547. TargetCamera.prototype._updateRigCameras = function () {
  42548. var camLeft = this._rigCameras[0];
  42549. var camRight = this._rigCameras[1];
  42550. switch (this.cameraRigMode) {
  42551. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  42552. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  42553. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  42554. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  42555. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  42556. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  42557. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  42558. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  42559. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  42560. camLeft.setTarget(this.getTarget());
  42561. camRight.setTarget(this.getTarget());
  42562. break;
  42563. case BABYLON.Camera.RIG_MODE_VR:
  42564. if (camLeft.rotationQuaternion) {
  42565. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  42566. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  42567. }
  42568. else {
  42569. camLeft.rotation.copyFrom(this.rotation);
  42570. camRight.rotation.copyFrom(this.rotation);
  42571. }
  42572. camLeft.position.copyFrom(this.position);
  42573. camRight.position.copyFrom(this.position);
  42574. break;
  42575. }
  42576. _super.prototype._updateRigCameras.call(this);
  42577. };
  42578. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  42579. if (!this._rigCamTransformMatrix) {
  42580. this._rigCamTransformMatrix = new BABYLON.Matrix();
  42581. }
  42582. var target = this.getTarget();
  42583. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  42584. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  42585. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  42586. };
  42587. TargetCamera.prototype.getClassName = function () {
  42588. return "TargetCamera";
  42589. };
  42590. __decorate([
  42591. BABYLON.serializeAsVector3()
  42592. ], TargetCamera.prototype, "rotation", void 0);
  42593. __decorate([
  42594. BABYLON.serialize()
  42595. ], TargetCamera.prototype, "speed", void 0);
  42596. __decorate([
  42597. BABYLON.serializeAsMeshReference("lockedTargetId")
  42598. ], TargetCamera.prototype, "lockedTarget", void 0);
  42599. return TargetCamera;
  42600. }(BABYLON.Camera));
  42601. BABYLON.TargetCamera = TargetCamera;
  42602. })(BABYLON || (BABYLON = {}));
  42603. //# sourceMappingURL=babylon.targetCamera.js.map
  42604. var BABYLON;
  42605. (function (BABYLON) {
  42606. var FreeCameraMouseInput = /** @class */ (function () {
  42607. function FreeCameraMouseInput(touchEnabled) {
  42608. if (touchEnabled === void 0) { touchEnabled = true; }
  42609. this.touchEnabled = touchEnabled;
  42610. this.buttons = [0, 1, 2];
  42611. this.angularSensibility = 2000.0;
  42612. this.previousPosition = null;
  42613. }
  42614. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  42615. var _this = this;
  42616. var engine = this.camera.getEngine();
  42617. if (!this._pointerInput) {
  42618. this._pointerInput = function (p, s) {
  42619. var evt = p.event;
  42620. if (engine.isInVRExclusivePointerMode) {
  42621. return;
  42622. }
  42623. if (!_this.touchEnabled && evt.pointerType === "touch") {
  42624. return;
  42625. }
  42626. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  42627. return;
  42628. }
  42629. var srcElement = (evt.srcElement || evt.target);
  42630. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  42631. try {
  42632. srcElement.setPointerCapture(evt.pointerId);
  42633. }
  42634. catch (e) {
  42635. //Nothing to do with the error. Execution will continue.
  42636. }
  42637. _this.previousPosition = {
  42638. x: evt.clientX,
  42639. y: evt.clientY
  42640. };
  42641. if (!noPreventDefault) {
  42642. evt.preventDefault();
  42643. element.focus();
  42644. }
  42645. }
  42646. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  42647. try {
  42648. srcElement.releasePointerCapture(evt.pointerId);
  42649. }
  42650. catch (e) {
  42651. //Nothing to do with the error.
  42652. }
  42653. _this.previousPosition = null;
  42654. if (!noPreventDefault) {
  42655. evt.preventDefault();
  42656. }
  42657. }
  42658. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  42659. if (!_this.previousPosition || engine.isPointerLock) {
  42660. return;
  42661. }
  42662. var offsetX = evt.clientX - _this.previousPosition.x;
  42663. var offsetY = evt.clientY - _this.previousPosition.y;
  42664. if (_this.camera.getScene().useRightHandedSystem) {
  42665. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  42666. }
  42667. else {
  42668. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  42669. }
  42670. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  42671. _this.previousPosition = {
  42672. x: evt.clientX,
  42673. y: evt.clientY
  42674. };
  42675. if (!noPreventDefault) {
  42676. evt.preventDefault();
  42677. }
  42678. }
  42679. };
  42680. }
  42681. this._onMouseMove = function (evt) {
  42682. if (!engine.isPointerLock) {
  42683. return;
  42684. }
  42685. if (engine.isInVRExclusivePointerMode) {
  42686. return;
  42687. }
  42688. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  42689. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  42690. if (_this.camera.getScene().useRightHandedSystem) {
  42691. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  42692. }
  42693. else {
  42694. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  42695. }
  42696. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  42697. _this.previousPosition = null;
  42698. if (!noPreventDefault) {
  42699. evt.preventDefault();
  42700. }
  42701. };
  42702. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  42703. element.addEventListener("mousemove", this._onMouseMove, false);
  42704. };
  42705. FreeCameraMouseInput.prototype.detachControl = function (element) {
  42706. if (this._observer && element) {
  42707. this.camera.getScene().onPointerObservable.remove(this._observer);
  42708. if (this._onMouseMove) {
  42709. element.removeEventListener("mousemove", this._onMouseMove);
  42710. }
  42711. this._observer = null;
  42712. this._onMouseMove = null;
  42713. this.previousPosition = null;
  42714. }
  42715. };
  42716. FreeCameraMouseInput.prototype.getClassName = function () {
  42717. return "FreeCameraMouseInput";
  42718. };
  42719. FreeCameraMouseInput.prototype.getSimpleName = function () {
  42720. return "mouse";
  42721. };
  42722. __decorate([
  42723. BABYLON.serialize()
  42724. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  42725. __decorate([
  42726. BABYLON.serialize()
  42727. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  42728. return FreeCameraMouseInput;
  42729. }());
  42730. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  42731. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  42732. })(BABYLON || (BABYLON = {}));
  42733. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  42734. var BABYLON;
  42735. (function (BABYLON) {
  42736. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  42737. function FreeCameraKeyboardMoveInput() {
  42738. this._keys = new Array();
  42739. this.keysUp = [38];
  42740. this.keysDown = [40];
  42741. this.keysLeft = [37];
  42742. this.keysRight = [39];
  42743. }
  42744. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  42745. var _this = this;
  42746. if (this._onCanvasBlurObserver) {
  42747. return;
  42748. }
  42749. this._scene = this.camera.getScene();
  42750. this._engine = this._scene.getEngine();
  42751. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  42752. _this._keys = [];
  42753. });
  42754. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  42755. var evt = info.event;
  42756. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  42757. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  42758. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  42759. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  42760. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  42761. var index = _this._keys.indexOf(evt.keyCode);
  42762. if (index === -1) {
  42763. _this._keys.push(evt.keyCode);
  42764. }
  42765. if (!noPreventDefault) {
  42766. evt.preventDefault();
  42767. }
  42768. }
  42769. }
  42770. else {
  42771. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  42772. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  42773. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  42774. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  42775. var index = _this._keys.indexOf(evt.keyCode);
  42776. if (index >= 0) {
  42777. _this._keys.splice(index, 1);
  42778. }
  42779. if (!noPreventDefault) {
  42780. evt.preventDefault();
  42781. }
  42782. }
  42783. }
  42784. });
  42785. };
  42786. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  42787. if (this._scene) {
  42788. if (this._onKeyboardObserver) {
  42789. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  42790. }
  42791. if (this._onCanvasBlurObserver) {
  42792. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  42793. }
  42794. this._onKeyboardObserver = null;
  42795. this._onCanvasBlurObserver = null;
  42796. }
  42797. this._keys = [];
  42798. };
  42799. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  42800. if (this._onKeyboardObserver) {
  42801. var camera = this.camera;
  42802. // Keyboard
  42803. for (var index = 0; index < this._keys.length; index++) {
  42804. var keyCode = this._keys[index];
  42805. var speed = camera._computeLocalCameraSpeed();
  42806. if (this.keysLeft.indexOf(keyCode) !== -1) {
  42807. camera._localDirection.copyFromFloats(-speed, 0, 0);
  42808. }
  42809. else if (this.keysUp.indexOf(keyCode) !== -1) {
  42810. camera._localDirection.copyFromFloats(0, 0, speed);
  42811. }
  42812. else if (this.keysRight.indexOf(keyCode) !== -1) {
  42813. camera._localDirection.copyFromFloats(speed, 0, 0);
  42814. }
  42815. else if (this.keysDown.indexOf(keyCode) !== -1) {
  42816. camera._localDirection.copyFromFloats(0, 0, -speed);
  42817. }
  42818. if (camera.getScene().useRightHandedSystem) {
  42819. camera._localDirection.z *= -1;
  42820. }
  42821. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  42822. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  42823. camera.cameraDirection.addInPlace(camera._transformedDirection);
  42824. }
  42825. }
  42826. };
  42827. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  42828. return "FreeCameraKeyboardMoveInput";
  42829. };
  42830. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  42831. this._keys = [];
  42832. };
  42833. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  42834. return "keyboard";
  42835. };
  42836. __decorate([
  42837. BABYLON.serialize()
  42838. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  42839. __decorate([
  42840. BABYLON.serialize()
  42841. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  42842. __decorate([
  42843. BABYLON.serialize()
  42844. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  42845. __decorate([
  42846. BABYLON.serialize()
  42847. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  42848. return FreeCameraKeyboardMoveInput;
  42849. }());
  42850. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  42851. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  42852. })(BABYLON || (BABYLON = {}));
  42853. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  42854. var BABYLON;
  42855. (function (BABYLON) {
  42856. var FreeCameraInputsManager = /** @class */ (function (_super) {
  42857. __extends(FreeCameraInputsManager, _super);
  42858. function FreeCameraInputsManager(camera) {
  42859. return _super.call(this, camera) || this;
  42860. }
  42861. FreeCameraInputsManager.prototype.addKeyboard = function () {
  42862. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  42863. return this;
  42864. };
  42865. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  42866. if (touchEnabled === void 0) { touchEnabled = true; }
  42867. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  42868. return this;
  42869. };
  42870. FreeCameraInputsManager.prototype.addGamepad = function () {
  42871. this.add(new BABYLON.FreeCameraGamepadInput());
  42872. return this;
  42873. };
  42874. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  42875. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  42876. return this;
  42877. };
  42878. FreeCameraInputsManager.prototype.addTouch = function () {
  42879. this.add(new BABYLON.FreeCameraTouchInput());
  42880. return this;
  42881. };
  42882. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  42883. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  42884. return this;
  42885. };
  42886. return FreeCameraInputsManager;
  42887. }(BABYLON.CameraInputsManager));
  42888. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  42889. })(BABYLON || (BABYLON = {}));
  42890. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  42891. var BABYLON;
  42892. (function (BABYLON) {
  42893. var FreeCamera = /** @class */ (function (_super) {
  42894. __extends(FreeCamera, _super);
  42895. function FreeCamera(name, position, scene) {
  42896. var _this = _super.call(this, name, position, scene) || this;
  42897. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  42898. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  42899. _this.checkCollisions = false;
  42900. _this.applyGravity = false;
  42901. _this._needMoveForGravity = false;
  42902. _this._oldPosition = BABYLON.Vector3.Zero();
  42903. _this._diffPosition = BABYLON.Vector3.Zero();
  42904. _this._newPosition = BABYLON.Vector3.Zero();
  42905. // Collisions
  42906. _this._collisionMask = -1;
  42907. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  42908. if (collidedMesh === void 0) { collidedMesh = null; }
  42909. //TODO move this to the collision coordinator!
  42910. if (_this.getScene().workerCollisions)
  42911. newPosition.multiplyInPlace(_this._collider._radius);
  42912. var updatePosition = function (newPos) {
  42913. _this._newPosition.copyFrom(newPos);
  42914. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  42915. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  42916. _this.position.addInPlace(_this._diffPosition);
  42917. if (_this.onCollide && collidedMesh) {
  42918. _this.onCollide(collidedMesh);
  42919. }
  42920. }
  42921. };
  42922. updatePosition(newPosition);
  42923. };
  42924. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  42925. _this.inputs.addKeyboard().addMouse();
  42926. return _this;
  42927. }
  42928. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  42929. //-- begin properties for backward compatibility for inputs
  42930. /**
  42931. * Gets the input sensibility for a mouse input. (default is 2000.0)
  42932. * Higher values reduce sensitivity.
  42933. */
  42934. get: function () {
  42935. var mouse = this.inputs.attached["mouse"];
  42936. if (mouse)
  42937. return mouse.angularSensibility;
  42938. return 0;
  42939. },
  42940. /**
  42941. * Sets the input sensibility for a mouse input. (default is 2000.0)
  42942. * Higher values reduce sensitivity.
  42943. */
  42944. set: function (value) {
  42945. var mouse = this.inputs.attached["mouse"];
  42946. if (mouse)
  42947. mouse.angularSensibility = value;
  42948. },
  42949. enumerable: true,
  42950. configurable: true
  42951. });
  42952. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  42953. get: function () {
  42954. var keyboard = this.inputs.attached["keyboard"];
  42955. if (keyboard)
  42956. return keyboard.keysUp;
  42957. return [];
  42958. },
  42959. set: function (value) {
  42960. var keyboard = this.inputs.attached["keyboard"];
  42961. if (keyboard)
  42962. keyboard.keysUp = value;
  42963. },
  42964. enumerable: true,
  42965. configurable: true
  42966. });
  42967. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  42968. get: function () {
  42969. var keyboard = this.inputs.attached["keyboard"];
  42970. if (keyboard)
  42971. return keyboard.keysDown;
  42972. return [];
  42973. },
  42974. set: function (value) {
  42975. var keyboard = this.inputs.attached["keyboard"];
  42976. if (keyboard)
  42977. keyboard.keysDown = value;
  42978. },
  42979. enumerable: true,
  42980. configurable: true
  42981. });
  42982. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  42983. get: function () {
  42984. var keyboard = this.inputs.attached["keyboard"];
  42985. if (keyboard)
  42986. return keyboard.keysLeft;
  42987. return [];
  42988. },
  42989. set: function (value) {
  42990. var keyboard = this.inputs.attached["keyboard"];
  42991. if (keyboard)
  42992. keyboard.keysLeft = value;
  42993. },
  42994. enumerable: true,
  42995. configurable: true
  42996. });
  42997. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  42998. get: function () {
  42999. var keyboard = this.inputs.attached["keyboard"];
  43000. if (keyboard)
  43001. return keyboard.keysRight;
  43002. return [];
  43003. },
  43004. set: function (value) {
  43005. var keyboard = this.inputs.attached["keyboard"];
  43006. if (keyboard)
  43007. keyboard.keysRight = value;
  43008. },
  43009. enumerable: true,
  43010. configurable: true
  43011. });
  43012. // Controls
  43013. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  43014. this.inputs.attachElement(element, noPreventDefault);
  43015. };
  43016. FreeCamera.prototype.detachControl = function (element) {
  43017. this.inputs.detachElement(element);
  43018. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  43019. this.cameraRotation = new BABYLON.Vector2(0, 0);
  43020. };
  43021. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  43022. get: function () {
  43023. return this._collisionMask;
  43024. },
  43025. set: function (mask) {
  43026. this._collisionMask = !isNaN(mask) ? mask : -1;
  43027. },
  43028. enumerable: true,
  43029. configurable: true
  43030. });
  43031. FreeCamera.prototype._collideWithWorld = function (displacement) {
  43032. var globalPosition;
  43033. if (this.parent) {
  43034. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  43035. }
  43036. else {
  43037. globalPosition = this.position;
  43038. }
  43039. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  43040. this._oldPosition.addInPlace(this.ellipsoidOffset);
  43041. if (!this._collider) {
  43042. this._collider = new BABYLON.Collider();
  43043. }
  43044. this._collider._radius = this.ellipsoid;
  43045. this._collider.collisionMask = this._collisionMask;
  43046. //no need for clone, as long as gravity is not on.
  43047. var actualDisplacement = displacement;
  43048. //add gravity to the direction to prevent the dual-collision checking
  43049. if (this.applyGravity) {
  43050. //this prevents mending with cameraDirection, a global variable of the free camera class.
  43051. actualDisplacement = displacement.add(this.getScene().gravity);
  43052. }
  43053. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  43054. };
  43055. FreeCamera.prototype._checkInputs = function () {
  43056. if (!this._localDirection) {
  43057. this._localDirection = BABYLON.Vector3.Zero();
  43058. this._transformedDirection = BABYLON.Vector3.Zero();
  43059. }
  43060. this.inputs.checkInputs();
  43061. _super.prototype._checkInputs.call(this);
  43062. };
  43063. FreeCamera.prototype._decideIfNeedsToMove = function () {
  43064. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  43065. };
  43066. FreeCamera.prototype._updatePosition = function () {
  43067. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  43068. this._collideWithWorld(this.cameraDirection);
  43069. }
  43070. else {
  43071. _super.prototype._updatePosition.call(this);
  43072. }
  43073. };
  43074. FreeCamera.prototype.dispose = function () {
  43075. this.inputs.clear();
  43076. _super.prototype.dispose.call(this);
  43077. };
  43078. FreeCamera.prototype.getClassName = function () {
  43079. return "FreeCamera";
  43080. };
  43081. __decorate([
  43082. BABYLON.serializeAsVector3()
  43083. ], FreeCamera.prototype, "ellipsoid", void 0);
  43084. __decorate([
  43085. BABYLON.serializeAsVector3()
  43086. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  43087. __decorate([
  43088. BABYLON.serialize()
  43089. ], FreeCamera.prototype, "checkCollisions", void 0);
  43090. __decorate([
  43091. BABYLON.serialize()
  43092. ], FreeCamera.prototype, "applyGravity", void 0);
  43093. return FreeCamera;
  43094. }(BABYLON.TargetCamera));
  43095. BABYLON.FreeCamera = FreeCamera;
  43096. })(BABYLON || (BABYLON = {}));
  43097. //# sourceMappingURL=babylon.freeCamera.js.map
  43098. var BABYLON;
  43099. (function (BABYLON) {
  43100. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  43101. function ArcRotateCameraKeyboardMoveInput() {
  43102. this._keys = new Array();
  43103. this.keysUp = [38];
  43104. this.keysDown = [40];
  43105. this.keysLeft = [37];
  43106. this.keysRight = [39];
  43107. this.keysReset = [220];
  43108. this.panningSensibility = 50.0;
  43109. this.zoomingSensibility = 25.0;
  43110. this.useAltToZoom = true;
  43111. }
  43112. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  43113. var _this = this;
  43114. if (this._onCanvasBlurObserver) {
  43115. return;
  43116. }
  43117. this._scene = this.camera.getScene();
  43118. this._engine = this._scene.getEngine();
  43119. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  43120. _this._keys = [];
  43121. });
  43122. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  43123. var evt = info.event;
  43124. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  43125. _this._ctrlPressed = evt.ctrlKey;
  43126. _this._altPressed = evt.altKey;
  43127. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  43128. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  43129. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  43130. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  43131. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  43132. var index = _this._keys.indexOf(evt.keyCode);
  43133. if (index === -1) {
  43134. _this._keys.push(evt.keyCode);
  43135. }
  43136. if (evt.preventDefault) {
  43137. if (!noPreventDefault) {
  43138. evt.preventDefault();
  43139. }
  43140. }
  43141. }
  43142. }
  43143. else {
  43144. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  43145. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  43146. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  43147. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  43148. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  43149. var index = _this._keys.indexOf(evt.keyCode);
  43150. if (index >= 0) {
  43151. _this._keys.splice(index, 1);
  43152. }
  43153. if (evt.preventDefault) {
  43154. if (!noPreventDefault) {
  43155. evt.preventDefault();
  43156. }
  43157. }
  43158. }
  43159. }
  43160. });
  43161. };
  43162. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  43163. if (this._scene) {
  43164. if (this._onKeyboardObserver) {
  43165. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  43166. }
  43167. if (this._onCanvasBlurObserver) {
  43168. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  43169. }
  43170. this._onKeyboardObserver = null;
  43171. this._onCanvasBlurObserver = null;
  43172. }
  43173. this._keys = [];
  43174. };
  43175. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  43176. if (this._onKeyboardObserver) {
  43177. var camera = this.camera;
  43178. for (var index = 0; index < this._keys.length; index++) {
  43179. var keyCode = this._keys[index];
  43180. if (this.keysLeft.indexOf(keyCode) !== -1) {
  43181. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  43182. camera.inertialPanningX -= 1 / this.panningSensibility;
  43183. }
  43184. else {
  43185. camera.inertialAlphaOffset -= 0.01;
  43186. }
  43187. }
  43188. else if (this.keysUp.indexOf(keyCode) !== -1) {
  43189. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  43190. camera.inertialPanningY += 1 / this.panningSensibility;
  43191. }
  43192. else if (this._altPressed && this.useAltToZoom) {
  43193. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  43194. }
  43195. else {
  43196. camera.inertialBetaOffset -= 0.01;
  43197. }
  43198. }
  43199. else if (this.keysRight.indexOf(keyCode) !== -1) {
  43200. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  43201. camera.inertialPanningX += 1 / this.panningSensibility;
  43202. }
  43203. else {
  43204. camera.inertialAlphaOffset += 0.01;
  43205. }
  43206. }
  43207. else if (this.keysDown.indexOf(keyCode) !== -1) {
  43208. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  43209. camera.inertialPanningY -= 1 / this.panningSensibility;
  43210. }
  43211. else if (this._altPressed && this.useAltToZoom) {
  43212. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  43213. }
  43214. else {
  43215. camera.inertialBetaOffset += 0.01;
  43216. }
  43217. }
  43218. else if (this.keysReset.indexOf(keyCode) !== -1) {
  43219. camera.restoreState();
  43220. }
  43221. }
  43222. }
  43223. };
  43224. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  43225. return "ArcRotateCameraKeyboardMoveInput";
  43226. };
  43227. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  43228. return "keyboard";
  43229. };
  43230. __decorate([
  43231. BABYLON.serialize()
  43232. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  43233. __decorate([
  43234. BABYLON.serialize()
  43235. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  43236. __decorate([
  43237. BABYLON.serialize()
  43238. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  43239. __decorate([
  43240. BABYLON.serialize()
  43241. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  43242. __decorate([
  43243. BABYLON.serialize()
  43244. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  43245. __decorate([
  43246. BABYLON.serialize()
  43247. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  43248. __decorate([
  43249. BABYLON.serialize()
  43250. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  43251. __decorate([
  43252. BABYLON.serialize()
  43253. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  43254. return ArcRotateCameraKeyboardMoveInput;
  43255. }());
  43256. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  43257. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  43258. })(BABYLON || (BABYLON = {}));
  43259. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  43260. var BABYLON;
  43261. (function (BABYLON) {
  43262. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  43263. function ArcRotateCameraMouseWheelInput() {
  43264. this.wheelPrecision = 3.0;
  43265. /**
  43266. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  43267. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  43268. */
  43269. this.wheelDeltaPercentage = 0;
  43270. }
  43271. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  43272. var _this = this;
  43273. this._wheel = function (p, s) {
  43274. //sanity check - this should be a PointerWheel event.
  43275. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  43276. return;
  43277. var event = p.event;
  43278. var delta = 0;
  43279. if (event.wheelDelta) {
  43280. delta = _this.wheelDeltaPercentage ? (event.wheelDelta * 0.01) * _this.camera.radius * _this.wheelDeltaPercentage : event.wheelDelta / (_this.wheelPrecision * 40);
  43281. }
  43282. else if (event.detail) {
  43283. delta = -event.detail / _this.wheelPrecision;
  43284. }
  43285. if (delta)
  43286. _this.camera.inertialRadiusOffset += delta;
  43287. if (event.preventDefault) {
  43288. if (!noPreventDefault) {
  43289. event.preventDefault();
  43290. }
  43291. }
  43292. };
  43293. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  43294. };
  43295. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  43296. if (this._observer && element) {
  43297. this.camera.getScene().onPointerObservable.remove(this._observer);
  43298. this._observer = null;
  43299. this._wheel = null;
  43300. }
  43301. };
  43302. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  43303. return "ArcRotateCameraMouseWheelInput";
  43304. };
  43305. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  43306. return "mousewheel";
  43307. };
  43308. __decorate([
  43309. BABYLON.serialize()
  43310. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  43311. __decorate([
  43312. BABYLON.serialize()
  43313. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  43314. return ArcRotateCameraMouseWheelInput;
  43315. }());
  43316. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  43317. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  43318. })(BABYLON || (BABYLON = {}));
  43319. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  43320. var BABYLON;
  43321. (function (BABYLON) {
  43322. var ArcRotateCameraPointersInput = /** @class */ (function () {
  43323. function ArcRotateCameraPointersInput() {
  43324. this.buttons = [0, 1, 2];
  43325. this.angularSensibilityX = 1000.0;
  43326. this.angularSensibilityY = 1000.0;
  43327. this.pinchPrecision = 12.0;
  43328. /**
  43329. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  43330. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  43331. */
  43332. this.pinchDeltaPercentage = 0;
  43333. this.panningSensibility = 1000.0;
  43334. this.multiTouchPanning = true;
  43335. this.multiTouchPanAndZoom = true;
  43336. this._isPanClick = false;
  43337. this.pinchInwards = true;
  43338. }
  43339. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  43340. var _this = this;
  43341. var engine = this.camera.getEngine();
  43342. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  43343. var pointA = null;
  43344. var pointB = null;
  43345. var previousPinchSquaredDistance = 0;
  43346. var initialDistance = 0;
  43347. var twoFingerActivityCount = 0;
  43348. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  43349. this._pointerInput = function (p, s) {
  43350. var evt = p.event;
  43351. var isTouch = p.event.pointerType === "touch";
  43352. if (engine.isInVRExclusivePointerMode) {
  43353. return;
  43354. }
  43355. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  43356. return;
  43357. }
  43358. var srcElement = (evt.srcElement || evt.target);
  43359. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  43360. try {
  43361. srcElement.setPointerCapture(evt.pointerId);
  43362. }
  43363. catch (e) {
  43364. //Nothing to do with the error. Execution will continue.
  43365. }
  43366. // Manage panning with pan button click
  43367. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  43368. // manage pointers
  43369. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  43370. if (pointA === null) {
  43371. pointA = cacheSoloPointer;
  43372. }
  43373. else if (pointB === null) {
  43374. pointB = cacheSoloPointer;
  43375. }
  43376. if (!noPreventDefault) {
  43377. evt.preventDefault();
  43378. element.focus();
  43379. }
  43380. }
  43381. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  43382. _this.camera.restoreState();
  43383. }
  43384. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  43385. try {
  43386. srcElement.releasePointerCapture(evt.pointerId);
  43387. }
  43388. catch (e) {
  43389. //Nothing to do with the error.
  43390. }
  43391. cacheSoloPointer = null;
  43392. previousPinchSquaredDistance = 0;
  43393. previousMultiTouchPanPosition.isPaning = false;
  43394. previousMultiTouchPanPosition.isPinching = false;
  43395. twoFingerActivityCount = 0;
  43396. initialDistance = 0;
  43397. if (!isTouch) {
  43398. pointB = null; // Mouse and pen are mono pointer
  43399. }
  43400. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  43401. //but emptying completly pointers collection is required to fix a bug on iPhone :
  43402. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  43403. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  43404. if (engine.badOS) {
  43405. pointA = pointB = null;
  43406. }
  43407. else {
  43408. //only remove the impacted pointer in case of multitouch allowing on most
  43409. //platforms switching from rotate to zoom and pan seamlessly.
  43410. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  43411. pointA = pointB;
  43412. pointB = null;
  43413. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  43414. }
  43415. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  43416. pointB = null;
  43417. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  43418. }
  43419. else {
  43420. pointA = pointB = null;
  43421. }
  43422. }
  43423. if (!noPreventDefault) {
  43424. evt.preventDefault();
  43425. }
  43426. }
  43427. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  43428. if (!noPreventDefault) {
  43429. evt.preventDefault();
  43430. }
  43431. // One button down
  43432. if (pointA && pointB === null && cacheSoloPointer) {
  43433. if (_this.panningSensibility !== 0 &&
  43434. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  43435. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  43436. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  43437. }
  43438. else {
  43439. var offsetX = evt.clientX - cacheSoloPointer.x;
  43440. var offsetY = evt.clientY - cacheSoloPointer.y;
  43441. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  43442. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  43443. }
  43444. cacheSoloPointer.x = evt.clientX;
  43445. cacheSoloPointer.y = evt.clientY;
  43446. }
  43447. else if (pointA && pointB) {
  43448. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  43449. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  43450. ed.x = evt.clientX;
  43451. ed.y = evt.clientY;
  43452. var direction = _this.pinchInwards ? 1 : -1;
  43453. var distX = pointA.x - pointB.x;
  43454. var distY = pointA.y - pointB.y;
  43455. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  43456. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  43457. if (previousPinchSquaredDistance === 0) {
  43458. initialDistance = pinchDistance;
  43459. previousPinchSquaredDistance = pinchSquaredDistance;
  43460. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  43461. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  43462. return;
  43463. }
  43464. if (_this.multiTouchPanAndZoom) {
  43465. if (_this.pinchDeltaPercentage) {
  43466. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  43467. }
  43468. else {
  43469. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  43470. (_this.pinchPrecision *
  43471. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  43472. direction);
  43473. }
  43474. if (_this.panningSensibility !== 0) {
  43475. var pointersCenterX = (pointA.x + pointB.x) / 2;
  43476. var pointersCenterY = (pointA.y + pointB.y) / 2;
  43477. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  43478. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  43479. previousMultiTouchPanPosition.x = pointersCenterX;
  43480. previousMultiTouchPanPosition.y = pointersCenterY;
  43481. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  43482. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  43483. }
  43484. }
  43485. else {
  43486. twoFingerActivityCount++;
  43487. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  43488. if (_this.pinchDeltaPercentage) {
  43489. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  43490. }
  43491. else {
  43492. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  43493. (_this.pinchPrecision *
  43494. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  43495. direction);
  43496. }
  43497. previousMultiTouchPanPosition.isPaning = false;
  43498. previousMultiTouchPanPosition.isPinching = true;
  43499. }
  43500. else {
  43501. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  43502. if (!previousMultiTouchPanPosition.isPaning) {
  43503. previousMultiTouchPanPosition.isPaning = true;
  43504. previousMultiTouchPanPosition.isPinching = false;
  43505. previousMultiTouchPanPosition.x = ed.x;
  43506. previousMultiTouchPanPosition.y = ed.y;
  43507. return;
  43508. }
  43509. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  43510. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  43511. }
  43512. }
  43513. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  43514. previousMultiTouchPanPosition.x = ed.x;
  43515. previousMultiTouchPanPosition.y = ed.y;
  43516. }
  43517. }
  43518. previousPinchSquaredDistance = pinchSquaredDistance;
  43519. }
  43520. }
  43521. };
  43522. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  43523. this._onContextMenu = function (evt) {
  43524. evt.preventDefault();
  43525. };
  43526. if (!this.camera._useCtrlForPanning) {
  43527. element.addEventListener("contextmenu", this._onContextMenu, false);
  43528. }
  43529. this._onLostFocus = function () {
  43530. //this._keys = [];
  43531. pointA = pointB = null;
  43532. previousPinchSquaredDistance = 0;
  43533. previousMultiTouchPanPosition.isPaning = false;
  43534. previousMultiTouchPanPosition.isPinching = false;
  43535. twoFingerActivityCount = 0;
  43536. cacheSoloPointer = null;
  43537. initialDistance = 0;
  43538. };
  43539. this._onMouseMove = function (evt) {
  43540. if (!engine.isPointerLock) {
  43541. return;
  43542. }
  43543. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  43544. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  43545. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  43546. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  43547. if (!noPreventDefault) {
  43548. evt.preventDefault();
  43549. }
  43550. };
  43551. this._onGestureStart = function (e) {
  43552. if (window.MSGesture === undefined) {
  43553. return;
  43554. }
  43555. if (!_this._MSGestureHandler) {
  43556. _this._MSGestureHandler = new MSGesture();
  43557. _this._MSGestureHandler.target = element;
  43558. }
  43559. _this._MSGestureHandler.addPointer(e.pointerId);
  43560. };
  43561. this._onGesture = function (e) {
  43562. _this.camera.radius *= e.scale;
  43563. if (e.preventDefault) {
  43564. if (!noPreventDefault) {
  43565. e.stopPropagation();
  43566. e.preventDefault();
  43567. }
  43568. }
  43569. };
  43570. element.addEventListener("mousemove", this._onMouseMove, false);
  43571. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  43572. element.addEventListener("MSGestureChange", this._onGesture, false);
  43573. BABYLON.Tools.RegisterTopRootEvents([
  43574. { name: "blur", handler: this._onLostFocus }
  43575. ]);
  43576. };
  43577. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  43578. if (this._onLostFocus) {
  43579. BABYLON.Tools.UnregisterTopRootEvents([
  43580. { name: "blur", handler: this._onLostFocus }
  43581. ]);
  43582. }
  43583. if (element && this._observer) {
  43584. this.camera.getScene().onPointerObservable.remove(this._observer);
  43585. this._observer = null;
  43586. if (this._onContextMenu) {
  43587. element.removeEventListener("contextmenu", this._onContextMenu);
  43588. }
  43589. if (this._onMouseMove) {
  43590. element.removeEventListener("mousemove", this._onMouseMove);
  43591. }
  43592. if (this._onGestureStart) {
  43593. element.removeEventListener("MSPointerDown", this._onGestureStart);
  43594. }
  43595. if (this._onGesture) {
  43596. element.removeEventListener("MSGestureChange", this._onGesture);
  43597. }
  43598. this._isPanClick = false;
  43599. this.pinchInwards = true;
  43600. this._onMouseMove = null;
  43601. this._onGestureStart = null;
  43602. this._onGesture = null;
  43603. this._MSGestureHandler = null;
  43604. this._onLostFocus = null;
  43605. this._onContextMenu = null;
  43606. }
  43607. };
  43608. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  43609. return "ArcRotateCameraPointersInput";
  43610. };
  43611. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  43612. return "pointers";
  43613. };
  43614. __decorate([
  43615. BABYLON.serialize()
  43616. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  43617. __decorate([
  43618. BABYLON.serialize()
  43619. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  43620. __decorate([
  43621. BABYLON.serialize()
  43622. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  43623. __decorate([
  43624. BABYLON.serialize()
  43625. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  43626. __decorate([
  43627. BABYLON.serialize()
  43628. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  43629. __decorate([
  43630. BABYLON.serialize()
  43631. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  43632. __decorate([
  43633. BABYLON.serialize()
  43634. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  43635. __decorate([
  43636. BABYLON.serialize()
  43637. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  43638. return ArcRotateCameraPointersInput;
  43639. }());
  43640. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  43641. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  43642. })(BABYLON || (BABYLON = {}));
  43643. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  43644. var BABYLON;
  43645. (function (BABYLON) {
  43646. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  43647. __extends(ArcRotateCameraInputsManager, _super);
  43648. function ArcRotateCameraInputsManager(camera) {
  43649. return _super.call(this, camera) || this;
  43650. }
  43651. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  43652. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  43653. return this;
  43654. };
  43655. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  43656. this.add(new BABYLON.ArcRotateCameraPointersInput());
  43657. return this;
  43658. };
  43659. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  43660. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  43661. return this;
  43662. };
  43663. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  43664. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  43665. return this;
  43666. };
  43667. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  43668. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  43669. return this;
  43670. };
  43671. return ArcRotateCameraInputsManager;
  43672. }(BABYLON.CameraInputsManager));
  43673. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  43674. })(BABYLON || (BABYLON = {}));
  43675. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  43676. var BABYLON;
  43677. (function (BABYLON) {
  43678. var ArcRotateCamera = /** @class */ (function (_super) {
  43679. __extends(ArcRotateCamera, _super);
  43680. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  43681. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  43682. _this.inertialAlphaOffset = 0;
  43683. _this.inertialBetaOffset = 0;
  43684. _this.inertialRadiusOffset = 0;
  43685. _this.lowerAlphaLimit = null;
  43686. _this.upperAlphaLimit = null;
  43687. _this.lowerBetaLimit = 0.01;
  43688. _this.upperBetaLimit = Math.PI;
  43689. _this.lowerRadiusLimit = null;
  43690. _this.upperRadiusLimit = null;
  43691. _this.inertialPanningX = 0;
  43692. _this.inertialPanningY = 0;
  43693. _this.pinchToPanMaxDistance = 20;
  43694. _this.panningDistanceLimit = null;
  43695. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  43696. _this.panningInertia = 0.9;
  43697. //-- end properties for backward compatibility for inputs
  43698. _this.zoomOnFactor = 1;
  43699. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  43700. _this.allowUpsideDown = true;
  43701. _this._viewMatrix = new BABYLON.Matrix();
  43702. // Panning
  43703. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  43704. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  43705. _this.checkCollisions = false;
  43706. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  43707. _this._previousPosition = BABYLON.Vector3.Zero();
  43708. _this._collisionVelocity = BABYLON.Vector3.Zero();
  43709. _this._newPosition = BABYLON.Vector3.Zero();
  43710. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  43711. if (collidedMesh === void 0) { collidedMesh = null; }
  43712. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  43713. newPosition.multiplyInPlace(_this._collider._radius);
  43714. }
  43715. if (!collidedMesh) {
  43716. _this._previousPosition.copyFrom(_this.position);
  43717. }
  43718. else {
  43719. _this.setPosition(newPosition);
  43720. if (_this.onCollide) {
  43721. _this.onCollide(collidedMesh);
  43722. }
  43723. }
  43724. // Recompute because of constraints
  43725. var cosa = Math.cos(_this.alpha);
  43726. var sina = Math.sin(_this.alpha);
  43727. var cosb = Math.cos(_this.beta);
  43728. var sinb = Math.sin(_this.beta);
  43729. if (sinb === 0) {
  43730. sinb = 0.0001;
  43731. }
  43732. var target = _this._getTargetPosition();
  43733. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  43734. _this.position.copyFrom(_this._newPosition);
  43735. var up = _this.upVector;
  43736. if (_this.allowUpsideDown && _this.beta < 0) {
  43737. up = up.clone();
  43738. up = up.negate();
  43739. }
  43740. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  43741. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  43742. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  43743. _this._collisionTriggered = false;
  43744. };
  43745. _this._target = BABYLON.Vector3.Zero();
  43746. if (target) {
  43747. _this.setTarget(target);
  43748. }
  43749. _this.alpha = alpha;
  43750. _this.beta = beta;
  43751. _this.radius = radius;
  43752. _this.getViewMatrix();
  43753. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  43754. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  43755. return _this;
  43756. }
  43757. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  43758. get: function () {
  43759. return this._target;
  43760. },
  43761. set: function (value) {
  43762. this.setTarget(value);
  43763. },
  43764. enumerable: true,
  43765. configurable: true
  43766. });
  43767. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  43768. //-- begin properties for backward compatibility for inputs
  43769. get: function () {
  43770. var pointers = this.inputs.attached["pointers"];
  43771. if (pointers)
  43772. return pointers.angularSensibilityX;
  43773. return 0;
  43774. },
  43775. set: function (value) {
  43776. var pointers = this.inputs.attached["pointers"];
  43777. if (pointers) {
  43778. pointers.angularSensibilityX = value;
  43779. }
  43780. },
  43781. enumerable: true,
  43782. configurable: true
  43783. });
  43784. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  43785. get: function () {
  43786. var pointers = this.inputs.attached["pointers"];
  43787. if (pointers)
  43788. return pointers.angularSensibilityY;
  43789. return 0;
  43790. },
  43791. set: function (value) {
  43792. var pointers = this.inputs.attached["pointers"];
  43793. if (pointers) {
  43794. pointers.angularSensibilityY = value;
  43795. }
  43796. },
  43797. enumerable: true,
  43798. configurable: true
  43799. });
  43800. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  43801. get: function () {
  43802. var pointers = this.inputs.attached["pointers"];
  43803. if (pointers)
  43804. return pointers.pinchPrecision;
  43805. return 0;
  43806. },
  43807. set: function (value) {
  43808. var pointers = this.inputs.attached["pointers"];
  43809. if (pointers) {
  43810. pointers.pinchPrecision = value;
  43811. }
  43812. },
  43813. enumerable: true,
  43814. configurable: true
  43815. });
  43816. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  43817. get: function () {
  43818. var pointers = this.inputs.attached["pointers"];
  43819. if (pointers)
  43820. return pointers.pinchDeltaPercentage;
  43821. return 0;
  43822. },
  43823. set: function (value) {
  43824. var pointers = this.inputs.attached["pointers"];
  43825. if (pointers) {
  43826. pointers.pinchDeltaPercentage = value;
  43827. }
  43828. },
  43829. enumerable: true,
  43830. configurable: true
  43831. });
  43832. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  43833. get: function () {
  43834. var pointers = this.inputs.attached["pointers"];
  43835. if (pointers)
  43836. return pointers.panningSensibility;
  43837. return 0;
  43838. },
  43839. set: function (value) {
  43840. var pointers = this.inputs.attached["pointers"];
  43841. if (pointers) {
  43842. pointers.panningSensibility = value;
  43843. }
  43844. },
  43845. enumerable: true,
  43846. configurable: true
  43847. });
  43848. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  43849. get: function () {
  43850. var keyboard = this.inputs.attached["keyboard"];
  43851. if (keyboard)
  43852. return keyboard.keysUp;
  43853. return [];
  43854. },
  43855. set: function (value) {
  43856. var keyboard = this.inputs.attached["keyboard"];
  43857. if (keyboard)
  43858. keyboard.keysUp = value;
  43859. },
  43860. enumerable: true,
  43861. configurable: true
  43862. });
  43863. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  43864. get: function () {
  43865. var keyboard = this.inputs.attached["keyboard"];
  43866. if (keyboard)
  43867. return keyboard.keysDown;
  43868. return [];
  43869. },
  43870. set: function (value) {
  43871. var keyboard = this.inputs.attached["keyboard"];
  43872. if (keyboard)
  43873. keyboard.keysDown = value;
  43874. },
  43875. enumerable: true,
  43876. configurable: true
  43877. });
  43878. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  43879. get: function () {
  43880. var keyboard = this.inputs.attached["keyboard"];
  43881. if (keyboard)
  43882. return keyboard.keysLeft;
  43883. return [];
  43884. },
  43885. set: function (value) {
  43886. var keyboard = this.inputs.attached["keyboard"];
  43887. if (keyboard)
  43888. keyboard.keysLeft = value;
  43889. },
  43890. enumerable: true,
  43891. configurable: true
  43892. });
  43893. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  43894. get: function () {
  43895. var keyboard = this.inputs.attached["keyboard"];
  43896. if (keyboard)
  43897. return keyboard.keysRight;
  43898. return [];
  43899. },
  43900. set: function (value) {
  43901. var keyboard = this.inputs.attached["keyboard"];
  43902. if (keyboard)
  43903. keyboard.keysRight = value;
  43904. },
  43905. enumerable: true,
  43906. configurable: true
  43907. });
  43908. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  43909. get: function () {
  43910. var mousewheel = this.inputs.attached["mousewheel"];
  43911. if (mousewheel)
  43912. return mousewheel.wheelPrecision;
  43913. return 0;
  43914. },
  43915. set: function (value) {
  43916. var mousewheel = this.inputs.attached["mousewheel"];
  43917. if (mousewheel)
  43918. mousewheel.wheelPrecision = value;
  43919. },
  43920. enumerable: true,
  43921. configurable: true
  43922. });
  43923. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  43924. get: function () {
  43925. var mousewheel = this.inputs.attached["mousewheel"];
  43926. if (mousewheel)
  43927. return mousewheel.wheelDeltaPercentage;
  43928. return 0;
  43929. },
  43930. set: function (value) {
  43931. var mousewheel = this.inputs.attached["mousewheel"];
  43932. if (mousewheel)
  43933. mousewheel.wheelDeltaPercentage = value;
  43934. },
  43935. enumerable: true,
  43936. configurable: true
  43937. });
  43938. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  43939. get: function () {
  43940. return this._bouncingBehavior;
  43941. },
  43942. enumerable: true,
  43943. configurable: true
  43944. });
  43945. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  43946. get: function () {
  43947. return this._bouncingBehavior != null;
  43948. },
  43949. set: function (value) {
  43950. if (value === this.useBouncingBehavior) {
  43951. return;
  43952. }
  43953. if (value) {
  43954. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  43955. this.addBehavior(this._bouncingBehavior);
  43956. }
  43957. else if (this._bouncingBehavior) {
  43958. this.removeBehavior(this._bouncingBehavior);
  43959. this._bouncingBehavior = null;
  43960. }
  43961. },
  43962. enumerable: true,
  43963. configurable: true
  43964. });
  43965. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  43966. get: function () {
  43967. return this._framingBehavior;
  43968. },
  43969. enumerable: true,
  43970. configurable: true
  43971. });
  43972. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  43973. get: function () {
  43974. return this._framingBehavior != null;
  43975. },
  43976. set: function (value) {
  43977. if (value === this.useFramingBehavior) {
  43978. return;
  43979. }
  43980. if (value) {
  43981. this._framingBehavior = new BABYLON.FramingBehavior();
  43982. this.addBehavior(this._framingBehavior);
  43983. }
  43984. else if (this._framingBehavior) {
  43985. this.removeBehavior(this._framingBehavior);
  43986. this._framingBehavior = null;
  43987. }
  43988. },
  43989. enumerable: true,
  43990. configurable: true
  43991. });
  43992. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  43993. get: function () {
  43994. return this._autoRotationBehavior;
  43995. },
  43996. enumerable: true,
  43997. configurable: true
  43998. });
  43999. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  44000. get: function () {
  44001. return this._autoRotationBehavior != null;
  44002. },
  44003. set: function (value) {
  44004. if (value === this.useAutoRotationBehavior) {
  44005. return;
  44006. }
  44007. if (value) {
  44008. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  44009. this.addBehavior(this._autoRotationBehavior);
  44010. }
  44011. else if (this._autoRotationBehavior) {
  44012. this.removeBehavior(this._autoRotationBehavior);
  44013. this._autoRotationBehavior = null;
  44014. }
  44015. },
  44016. enumerable: true,
  44017. configurable: true
  44018. });
  44019. // Cache
  44020. ArcRotateCamera.prototype._initCache = function () {
  44021. _super.prototype._initCache.call(this);
  44022. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  44023. this._cache.alpha = undefined;
  44024. this._cache.beta = undefined;
  44025. this._cache.radius = undefined;
  44026. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  44027. };
  44028. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  44029. if (!ignoreParentClass) {
  44030. _super.prototype._updateCache.call(this);
  44031. }
  44032. this._cache._target.copyFrom(this._getTargetPosition());
  44033. this._cache.alpha = this.alpha;
  44034. this._cache.beta = this.beta;
  44035. this._cache.radius = this.radius;
  44036. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  44037. };
  44038. ArcRotateCamera.prototype._getTargetPosition = function () {
  44039. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  44040. var pos = this._targetHost.getAbsolutePosition();
  44041. if (this._targetBoundingCenter) {
  44042. pos.addToRef(this._targetBoundingCenter, this._target);
  44043. }
  44044. else {
  44045. this._target.copyFrom(pos);
  44046. }
  44047. }
  44048. var lockedTargetPosition = this._getLockedTargetPosition();
  44049. if (lockedTargetPosition) {
  44050. return lockedTargetPosition;
  44051. }
  44052. return this._target;
  44053. };
  44054. ArcRotateCamera.prototype.storeState = function () {
  44055. this._storedAlpha = this.alpha;
  44056. this._storedBeta = this.beta;
  44057. this._storedRadius = this.radius;
  44058. this._storedTarget = this._getTargetPosition().clone();
  44059. return _super.prototype.storeState.call(this);
  44060. };
  44061. /**
  44062. * Restored camera state. You must call storeState() first
  44063. */
  44064. ArcRotateCamera.prototype._restoreStateValues = function () {
  44065. if (!_super.prototype._restoreStateValues.call(this)) {
  44066. return false;
  44067. }
  44068. this.alpha = this._storedAlpha;
  44069. this.beta = this._storedBeta;
  44070. this.radius = this._storedRadius;
  44071. this.setTarget(this._storedTarget.clone());
  44072. this.inertialAlphaOffset = 0;
  44073. this.inertialBetaOffset = 0;
  44074. this.inertialRadiusOffset = 0;
  44075. this.inertialPanningX = 0;
  44076. this.inertialPanningY = 0;
  44077. return true;
  44078. };
  44079. // Synchronized
  44080. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  44081. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  44082. return false;
  44083. return this._cache._target.equals(this._getTargetPosition())
  44084. && this._cache.alpha === this.alpha
  44085. && this._cache.beta === this.beta
  44086. && this._cache.radius === this.radius
  44087. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  44088. };
  44089. // Methods
  44090. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  44091. var _this = this;
  44092. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  44093. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  44094. this._useCtrlForPanning = useCtrlForPanning;
  44095. this._panningMouseButton = panningMouseButton;
  44096. this.inputs.attachElement(element, noPreventDefault);
  44097. this._reset = function () {
  44098. _this.inertialAlphaOffset = 0;
  44099. _this.inertialBetaOffset = 0;
  44100. _this.inertialRadiusOffset = 0;
  44101. _this.inertialPanningX = 0;
  44102. _this.inertialPanningY = 0;
  44103. };
  44104. };
  44105. ArcRotateCamera.prototype.detachControl = function (element) {
  44106. this.inputs.detachElement(element);
  44107. if (this._reset) {
  44108. this._reset();
  44109. }
  44110. };
  44111. ArcRotateCamera.prototype._checkInputs = function () {
  44112. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  44113. if (this._collisionTriggered) {
  44114. return;
  44115. }
  44116. this.inputs.checkInputs();
  44117. // Inertia
  44118. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  44119. if (this.getScene().useRightHandedSystem) {
  44120. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  44121. }
  44122. else {
  44123. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  44124. }
  44125. this.beta += this.inertialBetaOffset;
  44126. this.radius -= this.inertialRadiusOffset;
  44127. this.inertialAlphaOffset *= this.inertia;
  44128. this.inertialBetaOffset *= this.inertia;
  44129. this.inertialRadiusOffset *= this.inertia;
  44130. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  44131. this.inertialAlphaOffset = 0;
  44132. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  44133. this.inertialBetaOffset = 0;
  44134. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  44135. this.inertialRadiusOffset = 0;
  44136. }
  44137. // Panning inertia
  44138. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  44139. if (!this._localDirection) {
  44140. this._localDirection = BABYLON.Vector3.Zero();
  44141. this._transformedDirection = BABYLON.Vector3.Zero();
  44142. }
  44143. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  44144. this._localDirection.multiplyInPlace(this.panningAxis);
  44145. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  44146. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  44147. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  44148. if (!this.panningAxis.y) {
  44149. this._transformedDirection.y = 0;
  44150. }
  44151. if (!this._targetHost) {
  44152. if (this.panningDistanceLimit) {
  44153. this._transformedDirection.addInPlace(this._target);
  44154. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  44155. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  44156. this._target.copyFrom(this._transformedDirection);
  44157. }
  44158. }
  44159. else {
  44160. this._target.addInPlace(this._transformedDirection);
  44161. }
  44162. }
  44163. this.inertialPanningX *= this.panningInertia;
  44164. this.inertialPanningY *= this.panningInertia;
  44165. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  44166. this.inertialPanningX = 0;
  44167. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  44168. this.inertialPanningY = 0;
  44169. }
  44170. // Limits
  44171. this._checkLimits();
  44172. _super.prototype._checkInputs.call(this);
  44173. };
  44174. ArcRotateCamera.prototype._checkLimits = function () {
  44175. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  44176. if (this.allowUpsideDown && this.beta > Math.PI) {
  44177. this.beta = this.beta - (2 * Math.PI);
  44178. }
  44179. }
  44180. else {
  44181. if (this.beta < this.lowerBetaLimit) {
  44182. this.beta = this.lowerBetaLimit;
  44183. }
  44184. }
  44185. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  44186. if (this.allowUpsideDown && this.beta < -Math.PI) {
  44187. this.beta = this.beta + (2 * Math.PI);
  44188. }
  44189. }
  44190. else {
  44191. if (this.beta > this.upperBetaLimit) {
  44192. this.beta = this.upperBetaLimit;
  44193. }
  44194. }
  44195. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  44196. this.alpha = this.lowerAlphaLimit;
  44197. }
  44198. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  44199. this.alpha = this.upperAlphaLimit;
  44200. }
  44201. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  44202. this.radius = this.lowerRadiusLimit;
  44203. }
  44204. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  44205. this.radius = this.upperRadiusLimit;
  44206. }
  44207. };
  44208. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  44209. var radiusv3 = this.position.subtract(this._getTargetPosition());
  44210. this.radius = radiusv3.length();
  44211. if (this.radius === 0) {
  44212. this.radius = 0.0001; // Just to avoid division by zero
  44213. }
  44214. // Alpha
  44215. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  44216. if (radiusv3.z < 0) {
  44217. this.alpha = 2 * Math.PI - this.alpha;
  44218. }
  44219. // Beta
  44220. this.beta = Math.acos(radiusv3.y / this.radius);
  44221. this._checkLimits();
  44222. };
  44223. ArcRotateCamera.prototype.setPosition = function (position) {
  44224. if (this.position.equals(position)) {
  44225. return;
  44226. }
  44227. this.position.copyFrom(position);
  44228. this.rebuildAnglesAndRadius();
  44229. };
  44230. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  44231. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  44232. if (allowSamePosition === void 0) { allowSamePosition = false; }
  44233. if (target.getBoundingInfo) {
  44234. if (toBoundingCenter) {
  44235. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  44236. }
  44237. else {
  44238. this._targetBoundingCenter = null;
  44239. }
  44240. this._targetHost = target;
  44241. this._target = this._getTargetPosition();
  44242. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  44243. }
  44244. else {
  44245. var newTarget = target;
  44246. var currentTarget = this._getTargetPosition();
  44247. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  44248. return;
  44249. }
  44250. this._targetHost = null;
  44251. this._target = newTarget;
  44252. this._targetBoundingCenter = null;
  44253. this.onMeshTargetChangedObservable.notifyObservers(null);
  44254. }
  44255. this.rebuildAnglesAndRadius();
  44256. };
  44257. ArcRotateCamera.prototype._getViewMatrix = function () {
  44258. // Compute
  44259. var cosa = Math.cos(this.alpha);
  44260. var sina = Math.sin(this.alpha);
  44261. var cosb = Math.cos(this.beta);
  44262. var sinb = Math.sin(this.beta);
  44263. if (sinb === 0) {
  44264. sinb = 0.0001;
  44265. }
  44266. var target = this._getTargetPosition();
  44267. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  44268. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  44269. if (!this._collider) {
  44270. this._collider = new BABYLON.Collider();
  44271. }
  44272. this._collider._radius = this.collisionRadius;
  44273. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  44274. this._collisionTriggered = true;
  44275. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  44276. }
  44277. else {
  44278. this.position.copyFrom(this._newPosition);
  44279. var up = this.upVector;
  44280. if (this.allowUpsideDown && sinb < 0) {
  44281. up = up.clone();
  44282. up = up.negate();
  44283. }
  44284. if (this.getScene().useRightHandedSystem) {
  44285. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  44286. }
  44287. else {
  44288. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  44289. }
  44290. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  44291. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  44292. }
  44293. this._currentTarget = target;
  44294. return this._viewMatrix;
  44295. };
  44296. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  44297. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  44298. meshes = meshes || this.getScene().meshes;
  44299. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  44300. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  44301. this.radius = distance * this.zoomOnFactor;
  44302. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  44303. };
  44304. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  44305. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  44306. var meshesOrMinMaxVector;
  44307. var distance;
  44308. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  44309. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  44310. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  44311. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  44312. }
  44313. else {
  44314. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  44315. meshesOrMinMaxVector = minMaxVectorAndDistance;
  44316. distance = minMaxVectorAndDistance.distance;
  44317. }
  44318. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  44319. if (!doNotUpdateMaxZ) {
  44320. this.maxZ = distance * 2;
  44321. }
  44322. };
  44323. /**
  44324. * @override
  44325. * Override Camera.createRigCamera
  44326. */
  44327. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  44328. var alphaShift = 0;
  44329. switch (this.cameraRigMode) {
  44330. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  44331. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  44332. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  44333. case BABYLON.Camera.RIG_MODE_VR:
  44334. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  44335. break;
  44336. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  44337. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  44338. break;
  44339. }
  44340. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  44341. rigCam._cameraRigParams = {};
  44342. return rigCam;
  44343. };
  44344. /**
  44345. * @override
  44346. * Override Camera._updateRigCameras
  44347. */
  44348. ArcRotateCamera.prototype._updateRigCameras = function () {
  44349. var camLeft = this._rigCameras[0];
  44350. var camRight = this._rigCameras[1];
  44351. camLeft.beta = camRight.beta = this.beta;
  44352. camLeft.radius = camRight.radius = this.radius;
  44353. switch (this.cameraRigMode) {
  44354. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  44355. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  44356. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  44357. case BABYLON.Camera.RIG_MODE_VR:
  44358. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  44359. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  44360. break;
  44361. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  44362. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  44363. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  44364. break;
  44365. }
  44366. _super.prototype._updateRigCameras.call(this);
  44367. };
  44368. ArcRotateCamera.prototype.dispose = function () {
  44369. this.inputs.clear();
  44370. _super.prototype.dispose.call(this);
  44371. };
  44372. ArcRotateCamera.prototype.getClassName = function () {
  44373. return "ArcRotateCamera";
  44374. };
  44375. __decorate([
  44376. BABYLON.serialize()
  44377. ], ArcRotateCamera.prototype, "alpha", void 0);
  44378. __decorate([
  44379. BABYLON.serialize()
  44380. ], ArcRotateCamera.prototype, "beta", void 0);
  44381. __decorate([
  44382. BABYLON.serialize()
  44383. ], ArcRotateCamera.prototype, "radius", void 0);
  44384. __decorate([
  44385. BABYLON.serializeAsVector3("target")
  44386. ], ArcRotateCamera.prototype, "_target", void 0);
  44387. __decorate([
  44388. BABYLON.serialize()
  44389. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  44390. __decorate([
  44391. BABYLON.serialize()
  44392. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  44393. __decorate([
  44394. BABYLON.serialize()
  44395. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  44396. __decorate([
  44397. BABYLON.serialize()
  44398. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  44399. __decorate([
  44400. BABYLON.serialize()
  44401. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  44402. __decorate([
  44403. BABYLON.serialize()
  44404. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  44405. __decorate([
  44406. BABYLON.serialize()
  44407. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  44408. __decorate([
  44409. BABYLON.serialize()
  44410. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  44411. __decorate([
  44412. BABYLON.serialize()
  44413. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  44414. __decorate([
  44415. BABYLON.serialize()
  44416. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  44417. __decorate([
  44418. BABYLON.serialize()
  44419. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  44420. __decorate([
  44421. BABYLON.serialize()
  44422. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  44423. __decorate([
  44424. BABYLON.serialize()
  44425. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  44426. __decorate([
  44427. BABYLON.serializeAsVector3()
  44428. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  44429. __decorate([
  44430. BABYLON.serialize()
  44431. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  44432. __decorate([
  44433. BABYLON.serialize()
  44434. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  44435. __decorate([
  44436. BABYLON.serialize()
  44437. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  44438. return ArcRotateCamera;
  44439. }(BABYLON.TargetCamera));
  44440. BABYLON.ArcRotateCamera = ArcRotateCamera;
  44441. })(BABYLON || (BABYLON = {}));
  44442. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  44443. var BABYLON;
  44444. (function (BABYLON) {
  44445. /**
  44446. * The HemisphericLight simulates the ambient environment light,
  44447. * so the passed direction is the light reflection direction, not the incoming direction.
  44448. */
  44449. var HemisphericLight = /** @class */ (function (_super) {
  44450. __extends(HemisphericLight, _super);
  44451. /**
  44452. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  44453. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  44454. * The HemisphericLight can't cast shadows.
  44455. * Documentation : http://doc.babylonjs.com/tutorials/lights
  44456. * @param name The friendly name of the light
  44457. * @param direction The direction of the light reflection
  44458. * @param scene The scene the light belongs to
  44459. */
  44460. function HemisphericLight(name, direction, scene) {
  44461. var _this = _super.call(this, name, scene) || this;
  44462. /**
  44463. * The groundColor is the light in the opposite direction to the one specified during creation.
  44464. * 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.
  44465. */
  44466. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  44467. _this.direction = direction || BABYLON.Vector3.Up();
  44468. return _this;
  44469. }
  44470. HemisphericLight.prototype._buildUniformLayout = function () {
  44471. this._uniformBuffer.addUniform("vLightData", 4);
  44472. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  44473. this._uniformBuffer.addUniform("vLightSpecular", 3);
  44474. this._uniformBuffer.addUniform("vLightGround", 3);
  44475. this._uniformBuffer.addUniform("shadowsInfo", 3);
  44476. this._uniformBuffer.addUniform("depthValues", 2);
  44477. this._uniformBuffer.create();
  44478. };
  44479. /**
  44480. * Returns the string "HemisphericLight".
  44481. * @return The class name
  44482. */
  44483. HemisphericLight.prototype.getClassName = function () {
  44484. return "HemisphericLight";
  44485. };
  44486. /**
  44487. * Sets the HemisphericLight direction towards the passed target (Vector3).
  44488. * Returns the updated direction.
  44489. * @param target The target the direction should point to
  44490. * @return The computed direction
  44491. */
  44492. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  44493. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  44494. return this.direction;
  44495. };
  44496. /**
  44497. * Returns the shadow generator associated to the light.
  44498. * @returns Always null for hemispheric lights because it does not support shadows.
  44499. */
  44500. HemisphericLight.prototype.getShadowGenerator = function () {
  44501. return null;
  44502. };
  44503. /**
  44504. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  44505. * @param effect The effect to update
  44506. * @param lightIndex The index of the light in the effect to update
  44507. * @returns The hemispheric light
  44508. */
  44509. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  44510. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  44511. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  44512. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  44513. return this;
  44514. };
  44515. /**
  44516. * @ignore internal use only.
  44517. */
  44518. HemisphericLight.prototype._getWorldMatrix = function () {
  44519. if (!this._worldMatrix) {
  44520. this._worldMatrix = BABYLON.Matrix.Identity();
  44521. }
  44522. return this._worldMatrix;
  44523. };
  44524. /**
  44525. * Returns the integer 3.
  44526. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  44527. */
  44528. HemisphericLight.prototype.getTypeID = function () {
  44529. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  44530. };
  44531. __decorate([
  44532. BABYLON.serializeAsColor3()
  44533. ], HemisphericLight.prototype, "groundColor", void 0);
  44534. __decorate([
  44535. BABYLON.serializeAsVector3()
  44536. ], HemisphericLight.prototype, "direction", void 0);
  44537. return HemisphericLight;
  44538. }(BABYLON.Light));
  44539. BABYLON.HemisphericLight = HemisphericLight;
  44540. })(BABYLON || (BABYLON = {}));
  44541. //# sourceMappingURL=babylon.hemisphericLight.js.map
  44542. var BABYLON;
  44543. (function (BABYLON) {
  44544. /**
  44545. * Base implementation of @see IShadowLight
  44546. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  44547. */
  44548. var ShadowLight = /** @class */ (function (_super) {
  44549. __extends(ShadowLight, _super);
  44550. function ShadowLight() {
  44551. var _this = _super !== null && _super.apply(this, arguments) || this;
  44552. _this._needProjectionMatrixCompute = true;
  44553. return _this;
  44554. }
  44555. ShadowLight.prototype._setPosition = function (value) {
  44556. this._position = value;
  44557. };
  44558. Object.defineProperty(ShadowLight.prototype, "position", {
  44559. /**
  44560. * Sets the position the shadow will be casted from. Also use as the light position for both
  44561. * point and spot lights.
  44562. */
  44563. get: function () {
  44564. return this._position;
  44565. },
  44566. /**
  44567. * Sets the position the shadow will be casted from. Also use as the light position for both
  44568. * point and spot lights.
  44569. */
  44570. set: function (value) {
  44571. this._setPosition(value);
  44572. },
  44573. enumerable: true,
  44574. configurable: true
  44575. });
  44576. ShadowLight.prototype._setDirection = function (value) {
  44577. this._direction = value;
  44578. };
  44579. Object.defineProperty(ShadowLight.prototype, "direction", {
  44580. /**
  44581. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  44582. * Also use as the light direction on spot and directional lights.
  44583. */
  44584. get: function () {
  44585. return this._direction;
  44586. },
  44587. /**
  44588. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  44589. * Also use as the light direction on spot and directional lights.
  44590. */
  44591. set: function (value) {
  44592. this._setDirection(value);
  44593. },
  44594. enumerable: true,
  44595. configurable: true
  44596. });
  44597. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  44598. /**
  44599. * Gets the shadow projection clipping minimum z value.
  44600. */
  44601. get: function () {
  44602. return this._shadowMinZ;
  44603. },
  44604. /**
  44605. * Sets the shadow projection clipping minimum z value.
  44606. */
  44607. set: function (value) {
  44608. this._shadowMinZ = value;
  44609. this.forceProjectionMatrixCompute();
  44610. },
  44611. enumerable: true,
  44612. configurable: true
  44613. });
  44614. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  44615. /**
  44616. * Sets the shadow projection clipping maximum z value.
  44617. */
  44618. get: function () {
  44619. return this._shadowMaxZ;
  44620. },
  44621. /**
  44622. * Gets the shadow projection clipping maximum z value.
  44623. */
  44624. set: function (value) {
  44625. this._shadowMaxZ = value;
  44626. this.forceProjectionMatrixCompute();
  44627. },
  44628. enumerable: true,
  44629. configurable: true
  44630. });
  44631. /**
  44632. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  44633. * @returns true if the information has been computed, false if it does not need to (no parenting)
  44634. */
  44635. ShadowLight.prototype.computeTransformedInformation = function () {
  44636. if (this.parent && this.parent.getWorldMatrix) {
  44637. if (!this.transformedPosition) {
  44638. this.transformedPosition = BABYLON.Vector3.Zero();
  44639. }
  44640. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  44641. // In case the direction is present.
  44642. if (this.direction) {
  44643. if (!this.transformedDirection) {
  44644. this.transformedDirection = BABYLON.Vector3.Zero();
  44645. }
  44646. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  44647. }
  44648. return true;
  44649. }
  44650. return false;
  44651. };
  44652. /**
  44653. * Return the depth scale used for the shadow map.
  44654. * @returns the depth scale.
  44655. */
  44656. ShadowLight.prototype.getDepthScale = function () {
  44657. return 50.0;
  44658. };
  44659. /**
  44660. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  44661. * @param faceIndex The index of the face we are computed the direction to generate shadow
  44662. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  44663. */
  44664. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  44665. return this.transformedDirection ? this.transformedDirection : this.direction;
  44666. };
  44667. /**
  44668. * Returns the ShadowLight absolute position in the World.
  44669. * @returns the position vector in world space
  44670. */
  44671. ShadowLight.prototype.getAbsolutePosition = function () {
  44672. return this.transformedPosition ? this.transformedPosition : this.position;
  44673. };
  44674. /**
  44675. * Sets the ShadowLight direction toward the passed target.
  44676. * @param target The point tot target in local space
  44677. * @returns the updated ShadowLight direction
  44678. */
  44679. ShadowLight.prototype.setDirectionToTarget = function (target) {
  44680. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  44681. return this.direction;
  44682. };
  44683. /**
  44684. * Returns the light rotation in euler definition.
  44685. * @returns the x y z rotation in local space.
  44686. */
  44687. ShadowLight.prototype.getRotation = function () {
  44688. this.direction.normalize();
  44689. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  44690. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  44691. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  44692. };
  44693. /**
  44694. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  44695. * @returns true if a cube texture needs to be use
  44696. */
  44697. ShadowLight.prototype.needCube = function () {
  44698. return false;
  44699. };
  44700. /**
  44701. * Detects if the projection matrix requires to be recomputed this frame.
  44702. * @returns true if it requires to be recomputed otherwise, false.
  44703. */
  44704. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  44705. return this._needProjectionMatrixCompute;
  44706. };
  44707. /**
  44708. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  44709. */
  44710. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  44711. this._needProjectionMatrixCompute = true;
  44712. };
  44713. /**
  44714. * Get the world matrix of the sahdow lights.
  44715. * @ignore Internal Use Only
  44716. */
  44717. ShadowLight.prototype._getWorldMatrix = function () {
  44718. if (!this._worldMatrix) {
  44719. this._worldMatrix = BABYLON.Matrix.Identity();
  44720. }
  44721. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  44722. return this._worldMatrix;
  44723. };
  44724. /**
  44725. * Gets the minZ used for shadow according to both the scene and the light.
  44726. * @param activeCamera The camera we are returning the min for
  44727. * @returns the depth min z
  44728. */
  44729. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  44730. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  44731. };
  44732. /**
  44733. * Gets the maxZ used for shadow according to both the scene and the light.
  44734. * @param activeCamera The camera we are returning the max for
  44735. * @returns the depth max z
  44736. */
  44737. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  44738. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  44739. };
  44740. /**
  44741. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  44742. * @param matrix The materix to updated with the projection information
  44743. * @param viewMatrix The transform matrix of the light
  44744. * @param renderList The list of mesh to render in the map
  44745. * @returns The current light
  44746. */
  44747. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  44748. if (this.customProjectionMatrixBuilder) {
  44749. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  44750. }
  44751. else {
  44752. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  44753. }
  44754. return this;
  44755. };
  44756. __decorate([
  44757. BABYLON.serializeAsVector3()
  44758. ], ShadowLight.prototype, "position", null);
  44759. __decorate([
  44760. BABYLON.serializeAsVector3()
  44761. ], ShadowLight.prototype, "direction", null);
  44762. __decorate([
  44763. BABYLON.serialize()
  44764. ], ShadowLight.prototype, "shadowMinZ", null);
  44765. __decorate([
  44766. BABYLON.serialize()
  44767. ], ShadowLight.prototype, "shadowMaxZ", null);
  44768. return ShadowLight;
  44769. }(BABYLON.Light));
  44770. BABYLON.ShadowLight = ShadowLight;
  44771. })(BABYLON || (BABYLON = {}));
  44772. //# sourceMappingURL=babylon.shadowLight.js.map
  44773. var BABYLON;
  44774. (function (BABYLON) {
  44775. /**
  44776. * A point light is a light defined by an unique point in world space.
  44777. * The light is emitted in every direction from this point.
  44778. * A good example of a point light is a standard light bulb.
  44779. * Documentation: https://doc.babylonjs.com/babylon101/lights
  44780. */
  44781. var PointLight = /** @class */ (function (_super) {
  44782. __extends(PointLight, _super);
  44783. /**
  44784. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  44785. * A PointLight emits the light in every direction.
  44786. * It can cast shadows.
  44787. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  44788. * ```javascript
  44789. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  44790. * ```
  44791. * Documentation : http://doc.babylonjs.com/tutorials/lights
  44792. * @param name The light friendly name
  44793. * @param position The position of the point light in the scene
  44794. * @param scene The scene the lights belongs to
  44795. */
  44796. function PointLight(name, position, scene) {
  44797. var _this = _super.call(this, name, scene) || this;
  44798. _this._shadowAngle = Math.PI / 2;
  44799. _this.position = position;
  44800. return _this;
  44801. }
  44802. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  44803. /**
  44804. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  44805. * This specifies what angle the shadow will use to be created.
  44806. *
  44807. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  44808. */
  44809. get: function () {
  44810. return this._shadowAngle;
  44811. },
  44812. /**
  44813. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  44814. * This specifies what angle the shadow will use to be created.
  44815. *
  44816. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  44817. */
  44818. set: function (value) {
  44819. this._shadowAngle = value;
  44820. this.forceProjectionMatrixCompute();
  44821. },
  44822. enumerable: true,
  44823. configurable: true
  44824. });
  44825. Object.defineProperty(PointLight.prototype, "direction", {
  44826. /**
  44827. * Gets the direction if it has been set.
  44828. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  44829. */
  44830. get: function () {
  44831. return this._direction;
  44832. },
  44833. /**
  44834. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  44835. */
  44836. set: function (value) {
  44837. var previousNeedCube = this.needCube();
  44838. this._direction = value;
  44839. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  44840. this._shadowGenerator.recreateShadowMap();
  44841. }
  44842. },
  44843. enumerable: true,
  44844. configurable: true
  44845. });
  44846. /**
  44847. * Returns the string "PointLight"
  44848. * @returns the class name
  44849. */
  44850. PointLight.prototype.getClassName = function () {
  44851. return "PointLight";
  44852. };
  44853. /**
  44854. * Returns the integer 0.
  44855. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  44856. */
  44857. PointLight.prototype.getTypeID = function () {
  44858. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  44859. };
  44860. /**
  44861. * Specifies wether or not the shadowmap should be a cube texture.
  44862. * @returns true if the shadowmap needs to be a cube texture.
  44863. */
  44864. PointLight.prototype.needCube = function () {
  44865. return !this.direction;
  44866. };
  44867. /**
  44868. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  44869. * @param faceIndex The index of the face we are computed the direction to generate shadow
  44870. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  44871. */
  44872. PointLight.prototype.getShadowDirection = function (faceIndex) {
  44873. if (this.direction) {
  44874. return _super.prototype.getShadowDirection.call(this, faceIndex);
  44875. }
  44876. else {
  44877. switch (faceIndex) {
  44878. case 0:
  44879. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  44880. case 1:
  44881. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  44882. case 2:
  44883. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  44884. case 3:
  44885. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  44886. case 4:
  44887. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  44888. case 5:
  44889. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  44890. }
  44891. }
  44892. return BABYLON.Vector3.Zero();
  44893. };
  44894. /**
  44895. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  44896. * - fov = PI / 2
  44897. * - aspect ratio : 1.0
  44898. * - z-near and far equal to the active camera minZ and maxZ.
  44899. * Returns the PointLight.
  44900. */
  44901. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  44902. var activeCamera = this.getScene().activeCamera;
  44903. if (!activeCamera) {
  44904. return;
  44905. }
  44906. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  44907. };
  44908. PointLight.prototype._buildUniformLayout = function () {
  44909. this._uniformBuffer.addUniform("vLightData", 4);
  44910. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  44911. this._uniformBuffer.addUniform("vLightSpecular", 3);
  44912. this._uniformBuffer.addUniform("shadowsInfo", 3);
  44913. this._uniformBuffer.addUniform("depthValues", 2);
  44914. this._uniformBuffer.create();
  44915. };
  44916. /**
  44917. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  44918. * @param effect The effect to update
  44919. * @param lightIndex The index of the light in the effect to update
  44920. * @returns The point light
  44921. */
  44922. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  44923. if (this.computeTransformedInformation()) {
  44924. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  44925. return this;
  44926. }
  44927. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  44928. return this;
  44929. };
  44930. __decorate([
  44931. BABYLON.serialize()
  44932. ], PointLight.prototype, "shadowAngle", null);
  44933. return PointLight;
  44934. }(BABYLON.ShadowLight));
  44935. BABYLON.PointLight = PointLight;
  44936. })(BABYLON || (BABYLON = {}));
  44937. //# sourceMappingURL=babylon.pointLight.js.map
  44938. var BABYLON;
  44939. (function (BABYLON) {
  44940. /**
  44941. * A directional light is defined by a direction (what a surprise!).
  44942. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  44943. * 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.
  44944. * Documentation: https://doc.babylonjs.com/babylon101/lights
  44945. */
  44946. var DirectionalLight = /** @class */ (function (_super) {
  44947. __extends(DirectionalLight, _super);
  44948. /**
  44949. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  44950. * The directional light is emitted from everywhere in the given direction.
  44951. * It can cast shawdows.
  44952. * Documentation : http://doc.babylonjs.com/tutorials/lights
  44953. * @param name The friendly name of the light
  44954. * @param direction The direction of the light
  44955. * @param scene The scene the light belongs to
  44956. */
  44957. function DirectionalLight(name, direction, scene) {
  44958. var _this = _super.call(this, name, scene) || this;
  44959. _this._shadowFrustumSize = 0;
  44960. _this._shadowOrthoScale = 0.5;
  44961. /**
  44962. * Automatically compute the projection matrix to best fit (including all the casters)
  44963. * on each frame.
  44964. */
  44965. _this.autoUpdateExtends = true;
  44966. // Cache
  44967. _this._orthoLeft = Number.MAX_VALUE;
  44968. _this._orthoRight = Number.MIN_VALUE;
  44969. _this._orthoTop = Number.MIN_VALUE;
  44970. _this._orthoBottom = Number.MAX_VALUE;
  44971. _this.position = direction.scale(-1.0);
  44972. _this.direction = direction;
  44973. return _this;
  44974. }
  44975. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  44976. /**
  44977. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  44978. */
  44979. get: function () {
  44980. return this._shadowFrustumSize;
  44981. },
  44982. /**
  44983. * Specifies a fix frustum size for the shadow generation.
  44984. */
  44985. set: function (value) {
  44986. this._shadowFrustumSize = value;
  44987. this.forceProjectionMatrixCompute();
  44988. },
  44989. enumerable: true,
  44990. configurable: true
  44991. });
  44992. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  44993. /**
  44994. * Gets the shadow projection scale against the optimal computed one.
  44995. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  44996. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  44997. */
  44998. get: function () {
  44999. return this._shadowOrthoScale;
  45000. },
  45001. /**
  45002. * Sets the shadow projection scale against the optimal computed one.
  45003. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  45004. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  45005. */
  45006. set: function (value) {
  45007. this._shadowOrthoScale = value;
  45008. this.forceProjectionMatrixCompute();
  45009. },
  45010. enumerable: true,
  45011. configurable: true
  45012. });
  45013. /**
  45014. * Returns the string "DirectionalLight".
  45015. * @return The class name
  45016. */
  45017. DirectionalLight.prototype.getClassName = function () {
  45018. return "DirectionalLight";
  45019. };
  45020. /**
  45021. * Returns the integer 1.
  45022. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  45023. */
  45024. DirectionalLight.prototype.getTypeID = function () {
  45025. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  45026. };
  45027. /**
  45028. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  45029. * Returns the DirectionalLight Shadow projection matrix.
  45030. */
  45031. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  45032. if (this.shadowFrustumSize > 0) {
  45033. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  45034. }
  45035. else {
  45036. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  45037. }
  45038. };
  45039. /**
  45040. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  45041. * Returns the DirectionalLight Shadow projection matrix.
  45042. */
  45043. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  45044. var activeCamera = this.getScene().activeCamera;
  45045. if (!activeCamera) {
  45046. return;
  45047. }
  45048. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  45049. };
  45050. /**
  45051. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  45052. * Returns the DirectionalLight Shadow projection matrix.
  45053. */
  45054. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  45055. var activeCamera = this.getScene().activeCamera;
  45056. if (!activeCamera) {
  45057. return;
  45058. }
  45059. // Check extends
  45060. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  45061. var tempVector3 = BABYLON.Vector3.Zero();
  45062. this._orthoLeft = Number.MAX_VALUE;
  45063. this._orthoRight = Number.MIN_VALUE;
  45064. this._orthoTop = Number.MIN_VALUE;
  45065. this._orthoBottom = Number.MAX_VALUE;
  45066. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  45067. var mesh = renderList[meshIndex];
  45068. if (!mesh) {
  45069. continue;
  45070. }
  45071. var boundingInfo = mesh.getBoundingInfo();
  45072. var boundingBox = boundingInfo.boundingBox;
  45073. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  45074. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  45075. if (tempVector3.x < this._orthoLeft)
  45076. this._orthoLeft = tempVector3.x;
  45077. if (tempVector3.y < this._orthoBottom)
  45078. this._orthoBottom = tempVector3.y;
  45079. if (tempVector3.x > this._orthoRight)
  45080. this._orthoRight = tempVector3.x;
  45081. if (tempVector3.y > this._orthoTop)
  45082. this._orthoTop = tempVector3.y;
  45083. }
  45084. }
  45085. }
  45086. var xOffset = this._orthoRight - this._orthoLeft;
  45087. var yOffset = this._orthoTop - this._orthoBottom;
  45088. 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);
  45089. };
  45090. DirectionalLight.prototype._buildUniformLayout = function () {
  45091. this._uniformBuffer.addUniform("vLightData", 4);
  45092. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  45093. this._uniformBuffer.addUniform("vLightSpecular", 3);
  45094. this._uniformBuffer.addUniform("shadowsInfo", 3);
  45095. this._uniformBuffer.addUniform("depthValues", 2);
  45096. this._uniformBuffer.create();
  45097. };
  45098. /**
  45099. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  45100. * @param effect The effect to update
  45101. * @param lightIndex The index of the light in the effect to update
  45102. * @returns The directional light
  45103. */
  45104. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  45105. if (this.computeTransformedInformation()) {
  45106. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  45107. return this;
  45108. }
  45109. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  45110. return this;
  45111. };
  45112. /**
  45113. * Gets the minZ used for shadow according to both the scene and the light.
  45114. *
  45115. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  45116. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  45117. * @param activeCamera The camera we are returning the min for
  45118. * @returns the depth min z
  45119. */
  45120. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  45121. return 1;
  45122. };
  45123. /**
  45124. * Gets the maxZ used for shadow according to both the scene and the light.
  45125. *
  45126. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  45127. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  45128. * @param activeCamera The camera we are returning the max for
  45129. * @returns the depth max z
  45130. */
  45131. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  45132. return 1;
  45133. };
  45134. __decorate([
  45135. BABYLON.serialize()
  45136. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  45137. __decorate([
  45138. BABYLON.serialize()
  45139. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  45140. __decorate([
  45141. BABYLON.serialize()
  45142. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  45143. return DirectionalLight;
  45144. }(BABYLON.ShadowLight));
  45145. BABYLON.DirectionalLight = DirectionalLight;
  45146. })(BABYLON || (BABYLON = {}));
  45147. //# sourceMappingURL=babylon.directionalLight.js.map
  45148. var BABYLON;
  45149. (function (BABYLON) {
  45150. /**
  45151. * A spot light is defined by a position, a direction, an angle, and an exponent.
  45152. * These values define a cone of light starting from the position, emitting toward the direction.
  45153. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  45154. * and the exponent defines the speed of the decay of the light with distance (reach).
  45155. * Documentation: https://doc.babylonjs.com/babylon101/lights
  45156. */
  45157. var SpotLight = /** @class */ (function (_super) {
  45158. __extends(SpotLight, _super);
  45159. /**
  45160. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  45161. * It can cast shadows.
  45162. * Documentation : http://doc.babylonjs.com/tutorials/lights
  45163. * @param name The light friendly name
  45164. * @param position The position of the spot light in the scene
  45165. * @param direction The direction of the light in the scene
  45166. * @param angle The cone angle of the light in Radians
  45167. * @param exponent The light decay speed with the distance from the emission spot
  45168. * @param scene The scene the lights belongs to
  45169. */
  45170. function SpotLight(name, position, direction, angle, exponent, scene) {
  45171. var _this = _super.call(this, name, scene) || this;
  45172. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  45173. _this._projectionTextureLightNear = 1e-6;
  45174. _this._projectionTextureLightFar = 1000.0;
  45175. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  45176. _this._projectionTextureViewLightDirty = true;
  45177. _this._projectionTextureProjectionLightDirty = true;
  45178. _this._projectionTextureDirty = true;
  45179. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  45180. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  45181. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  45182. _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);
  45183. _this.position = position;
  45184. _this.direction = direction;
  45185. _this.angle = angle;
  45186. _this.exponent = exponent;
  45187. return _this;
  45188. }
  45189. Object.defineProperty(SpotLight.prototype, "angle", {
  45190. /**
  45191. * Gets the cone angle of the spot light in Radians.
  45192. */
  45193. get: function () {
  45194. return this._angle;
  45195. },
  45196. /**
  45197. * Sets the cone angle of the spot light in Radians.
  45198. */
  45199. set: function (value) {
  45200. this._angle = value;
  45201. this._projectionTextureProjectionLightDirty = true;
  45202. this.forceProjectionMatrixCompute();
  45203. },
  45204. enumerable: true,
  45205. configurable: true
  45206. });
  45207. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  45208. /**
  45209. * Allows scaling the angle of the light for shadow generation only.
  45210. */
  45211. get: function () {
  45212. return this._shadowAngleScale;
  45213. },
  45214. /**
  45215. * Allows scaling the angle of the light for shadow generation only.
  45216. */
  45217. set: function (value) {
  45218. this._shadowAngleScale = value;
  45219. this.forceProjectionMatrixCompute();
  45220. },
  45221. enumerable: true,
  45222. configurable: true
  45223. });
  45224. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  45225. /**
  45226. * Allows reading the projecton texture
  45227. */
  45228. get: function () {
  45229. return this._projectionTextureMatrix;
  45230. },
  45231. enumerable: true,
  45232. configurable: true
  45233. });
  45234. ;
  45235. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  45236. /**
  45237. * Gets the near clip of the Spotlight for texture projection.
  45238. */
  45239. get: function () {
  45240. return this._projectionTextureLightNear;
  45241. },
  45242. /**
  45243. * Sets the near clip of the Spotlight for texture projection.
  45244. */
  45245. set: function (value) {
  45246. this._projectionTextureLightNear = value;
  45247. this._projectionTextureProjectionLightDirty = true;
  45248. },
  45249. enumerable: true,
  45250. configurable: true
  45251. });
  45252. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  45253. /**
  45254. * Gets the far clip of the Spotlight for texture projection.
  45255. */
  45256. get: function () {
  45257. return this._projectionTextureLightFar;
  45258. },
  45259. /**
  45260. * Sets the far clip of the Spotlight for texture projection.
  45261. */
  45262. set: function (value) {
  45263. this._projectionTextureLightFar = value;
  45264. this._projectionTextureProjectionLightDirty = true;
  45265. },
  45266. enumerable: true,
  45267. configurable: true
  45268. });
  45269. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  45270. /**
  45271. * Gets the Up vector of the Spotlight for texture projection.
  45272. */
  45273. get: function () {
  45274. return this._projectionTextureUpDirection;
  45275. },
  45276. /**
  45277. * Sets the Up vector of the Spotlight for texture projection.
  45278. */
  45279. set: function (value) {
  45280. this._projectionTextureUpDirection = value;
  45281. this._projectionTextureProjectionLightDirty = true;
  45282. },
  45283. enumerable: true,
  45284. configurable: true
  45285. });
  45286. ;
  45287. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  45288. /**
  45289. * Gets the projection texture of the light.
  45290. */
  45291. get: function () {
  45292. return this._projectionTexture;
  45293. },
  45294. /**
  45295. * Sets the projection texture of the light.
  45296. */
  45297. set: function (value) {
  45298. this._projectionTexture = value;
  45299. this._projectionTextureDirty = true;
  45300. },
  45301. enumerable: true,
  45302. configurable: true
  45303. });
  45304. /**
  45305. * Returns the string "SpotLight".
  45306. * @returns the class name
  45307. */
  45308. SpotLight.prototype.getClassName = function () {
  45309. return "SpotLight";
  45310. };
  45311. /**
  45312. * Returns the integer 2.
  45313. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  45314. */
  45315. SpotLight.prototype.getTypeID = function () {
  45316. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  45317. };
  45318. /**
  45319. * Overrides the direction setter to recompute the projection texture view light Matrix.
  45320. */
  45321. SpotLight.prototype._setDirection = function (value) {
  45322. _super.prototype._setDirection.call(this, value);
  45323. this._projectionTextureViewLightDirty = true;
  45324. };
  45325. /**
  45326. * Overrides the position setter to recompute the projection texture view light Matrix.
  45327. */
  45328. SpotLight.prototype._setPosition = function (value) {
  45329. _super.prototype._setPosition.call(this, value);
  45330. this._projectionTextureViewLightDirty = true;
  45331. };
  45332. /**
  45333. * 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.
  45334. * Returns the SpotLight.
  45335. */
  45336. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  45337. var activeCamera = this.getScene().activeCamera;
  45338. if (!activeCamera) {
  45339. return;
  45340. }
  45341. this._shadowAngleScale = this._shadowAngleScale || 1;
  45342. var angle = this._shadowAngleScale * this._angle;
  45343. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  45344. };
  45345. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  45346. this._projectionTextureViewLightDirty = false;
  45347. this._projectionTextureDirty = true;
  45348. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  45349. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  45350. };
  45351. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  45352. this._projectionTextureProjectionLightDirty = false;
  45353. this._projectionTextureDirty = true;
  45354. var light_far = this.projectionTextureLightFar;
  45355. var light_near = this.projectionTextureLightNear;
  45356. var P = light_far / (light_far - light_near);
  45357. var Q = -P * light_near;
  45358. var S = 1.0 / Math.tan(this._angle / 2.0);
  45359. var A = 1.0;
  45360. 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);
  45361. };
  45362. /**
  45363. * Main function for light texture projection matrix computing.
  45364. */
  45365. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  45366. this._projectionTextureDirty = false;
  45367. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  45368. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  45369. };
  45370. SpotLight.prototype._buildUniformLayout = function () {
  45371. this._uniformBuffer.addUniform("vLightData", 4);
  45372. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  45373. this._uniformBuffer.addUniform("vLightSpecular", 3);
  45374. this._uniformBuffer.addUniform("vLightDirection", 3);
  45375. this._uniformBuffer.addUniform("shadowsInfo", 3);
  45376. this._uniformBuffer.addUniform("depthValues", 2);
  45377. this._uniformBuffer.create();
  45378. };
  45379. /**
  45380. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  45381. * @param effect The effect to update
  45382. * @param lightIndex The index of the light in the effect to update
  45383. * @returns The spot light
  45384. */
  45385. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  45386. var normalizeDirection;
  45387. if (this.computeTransformedInformation()) {
  45388. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  45389. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  45390. }
  45391. else {
  45392. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  45393. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  45394. }
  45395. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  45396. if (this.projectionTexture && this.projectionTexture.isReady()) {
  45397. if (this._projectionTextureViewLightDirty) {
  45398. this._computeProjectionTextureViewLightMatrix();
  45399. }
  45400. if (this._projectionTextureProjectionLightDirty) {
  45401. this._computeProjectionTextureProjectionLightMatrix();
  45402. }
  45403. if (this._projectionTextureDirty) {
  45404. this._computeProjectionTextureMatrix();
  45405. }
  45406. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  45407. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  45408. }
  45409. return this;
  45410. };
  45411. /**
  45412. * Disposes the light and the associated resources.
  45413. */
  45414. SpotLight.prototype.dispose = function () {
  45415. _super.prototype.dispose.call(this);
  45416. if (this._projectionTexture) {
  45417. this._projectionTexture.dispose();
  45418. }
  45419. };
  45420. __decorate([
  45421. BABYLON.serialize()
  45422. ], SpotLight.prototype, "angle", null);
  45423. __decorate([
  45424. BABYLON.serialize()
  45425. ], SpotLight.prototype, "shadowAngleScale", null);
  45426. __decorate([
  45427. BABYLON.serialize()
  45428. ], SpotLight.prototype, "exponent", void 0);
  45429. __decorate([
  45430. BABYLON.serialize()
  45431. ], SpotLight.prototype, "projectionTextureLightNear", null);
  45432. __decorate([
  45433. BABYLON.serialize()
  45434. ], SpotLight.prototype, "projectionTextureLightFar", null);
  45435. __decorate([
  45436. BABYLON.serialize()
  45437. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  45438. __decorate([
  45439. BABYLON.serializeAsTexture("projectedLightTexture")
  45440. ], SpotLight.prototype, "_projectionTexture", void 0);
  45441. return SpotLight;
  45442. }(BABYLON.ShadowLight));
  45443. BABYLON.SpotLight = SpotLight;
  45444. })(BABYLON || (BABYLON = {}));
  45445. //# sourceMappingURL=babylon.spotLight.js.map
  45446. var BABYLON;
  45447. (function (BABYLON) {
  45448. var AnimationRange = /** @class */ (function () {
  45449. function AnimationRange(name, from, to) {
  45450. this.name = name;
  45451. this.from = from;
  45452. this.to = to;
  45453. }
  45454. AnimationRange.prototype.clone = function () {
  45455. return new AnimationRange(this.name, this.from, this.to);
  45456. };
  45457. return AnimationRange;
  45458. }());
  45459. BABYLON.AnimationRange = AnimationRange;
  45460. /**
  45461. * Composed of a frame, and an action function
  45462. */
  45463. var AnimationEvent = /** @class */ (function () {
  45464. function AnimationEvent(frame, action, onlyOnce) {
  45465. this.frame = frame;
  45466. this.action = action;
  45467. this.onlyOnce = onlyOnce;
  45468. this.isDone = false;
  45469. }
  45470. return AnimationEvent;
  45471. }());
  45472. BABYLON.AnimationEvent = AnimationEvent;
  45473. var PathCursor = /** @class */ (function () {
  45474. function PathCursor(path) {
  45475. this.path = path;
  45476. this._onchange = new Array();
  45477. this.value = 0;
  45478. this.animations = new Array();
  45479. }
  45480. PathCursor.prototype.getPoint = function () {
  45481. var point = this.path.getPointAtLengthPosition(this.value);
  45482. return new BABYLON.Vector3(point.x, 0, point.y);
  45483. };
  45484. PathCursor.prototype.moveAhead = function (step) {
  45485. if (step === void 0) { step = 0.002; }
  45486. this.move(step);
  45487. return this;
  45488. };
  45489. PathCursor.prototype.moveBack = function (step) {
  45490. if (step === void 0) { step = 0.002; }
  45491. this.move(-step);
  45492. return this;
  45493. };
  45494. PathCursor.prototype.move = function (step) {
  45495. if (Math.abs(step) > 1) {
  45496. throw "step size should be less than 1.";
  45497. }
  45498. this.value += step;
  45499. this.ensureLimits();
  45500. this.raiseOnChange();
  45501. return this;
  45502. };
  45503. PathCursor.prototype.ensureLimits = function () {
  45504. while (this.value > 1) {
  45505. this.value -= 1;
  45506. }
  45507. while (this.value < 0) {
  45508. this.value += 1;
  45509. }
  45510. return this;
  45511. };
  45512. // used by animation engine
  45513. PathCursor.prototype.raiseOnChange = function () {
  45514. var _this = this;
  45515. this._onchange.forEach(function (f) { return f(_this); });
  45516. return this;
  45517. };
  45518. PathCursor.prototype.onchange = function (f) {
  45519. this._onchange.push(f);
  45520. return this;
  45521. };
  45522. return PathCursor;
  45523. }());
  45524. BABYLON.PathCursor = PathCursor;
  45525. var AnimationKeyInterpolation;
  45526. (function (AnimationKeyInterpolation) {
  45527. /**
  45528. * Do not interpolate between keys and use the start key value only. Tangents are ignored.
  45529. */
  45530. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  45531. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  45532. var Animation = /** @class */ (function () {
  45533. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  45534. this.name = name;
  45535. this.targetProperty = targetProperty;
  45536. this.framePerSecond = framePerSecond;
  45537. this.dataType = dataType;
  45538. this.loopMode = loopMode;
  45539. this.enableBlending = enableBlending;
  45540. this._runtimeAnimations = new Array();
  45541. // The set of event that will be linked to this animation
  45542. this._events = new Array();
  45543. this.blendingSpeed = 0.01;
  45544. this._ranges = {};
  45545. this.targetPropertyPath = targetProperty.split(".");
  45546. this.dataType = dataType;
  45547. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  45548. }
  45549. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  45550. var dataType = undefined;
  45551. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  45552. dataType = Animation.ANIMATIONTYPE_FLOAT;
  45553. }
  45554. else if (from instanceof BABYLON.Quaternion) {
  45555. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  45556. }
  45557. else if (from instanceof BABYLON.Vector3) {
  45558. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  45559. }
  45560. else if (from instanceof BABYLON.Vector2) {
  45561. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  45562. }
  45563. else if (from instanceof BABYLON.Color3) {
  45564. dataType = Animation.ANIMATIONTYPE_COLOR3;
  45565. }
  45566. else if (from instanceof BABYLON.Size) {
  45567. dataType = Animation.ANIMATIONTYPE_SIZE;
  45568. }
  45569. if (dataType == undefined) {
  45570. return null;
  45571. }
  45572. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  45573. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  45574. animation.setKeys(keys);
  45575. if (easingFunction !== undefined) {
  45576. animation.setEasingFunction(easingFunction);
  45577. }
  45578. return animation;
  45579. };
  45580. /**
  45581. * Sets up an animation.
  45582. * @param property the property to animate
  45583. * @param animationType the animation type to apply
  45584. * @param easingFunction the easing function used in the animation
  45585. * @returns The created animation
  45586. */
  45587. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  45588. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  45589. animation.setEasingFunction(easingFunction);
  45590. return animation;
  45591. };
  45592. /**
  45593. * Create and start an animation on a node
  45594. * @param {string} name defines the name of the global animation that will be run on all nodes
  45595. * @param {BABYLON.Node} node defines the root node where the animation will take place
  45596. * @param {string} targetProperty defines property to animate
  45597. * @param {number} framePerSecond defines the number of frame per second yo use
  45598. * @param {number} totalFrame defines the number of frames in total
  45599. * @param {any} from defines the initial value
  45600. * @param {any} to defines the final value
  45601. * @param {number} loopMode defines which loop mode you want to use (off by default)
  45602. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  45603. * @param onAnimationEnd defines the callback to call when animation end
  45604. * @returns the animatable created for this animation
  45605. */
  45606. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  45607. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  45608. if (!animation) {
  45609. return null;
  45610. }
  45611. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  45612. };
  45613. /**
  45614. * Create and start an animation on a node and its descendants
  45615. * @param {string} name defines the name of the global animation that will be run on all nodes
  45616. * @param {BABYLON.Node} node defines the root node where the animation will take place
  45617. * @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.
  45618. * @param {string} targetProperty defines property to animate
  45619. * @param {number} framePerSecond defines the number of frame per second yo use
  45620. * @param {number} totalFrame defines the number of frames in total
  45621. * @param {any} from defines the initial value
  45622. * @param {any} to defines the final value
  45623. * @param {number} loopMode defines which loop mode you want to use (off by default)
  45624. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  45625. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  45626. * @returns the list of animatables created for all nodes
  45627. * @example https://www.babylonjs-playground.com/#MH0VLI
  45628. */
  45629. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  45630. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  45631. if (!animation) {
  45632. return null;
  45633. }
  45634. var scene = node.getScene();
  45635. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  45636. };
  45637. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  45638. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  45639. if (!animation) {
  45640. return null;
  45641. }
  45642. node.animations.push(animation);
  45643. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  45644. };
  45645. /**
  45646. * Transition property of the Camera to the target Value.
  45647. * @param property The property to transition
  45648. * @param targetValue The target Value of the property
  45649. * @param host The object where the property to animate belongs
  45650. * @param scene Scene used to run the animation
  45651. * @param frameRate Framerate (in frame/s) to use
  45652. * @param transition The transition type we want to use
  45653. * @param duration The duration of the animation, in milliseconds
  45654. * @param onAnimationEnd Call back trigger at the end of the animation.
  45655. */
  45656. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  45657. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  45658. if (duration <= 0) {
  45659. host[property] = targetValue;
  45660. if (onAnimationEnd) {
  45661. onAnimationEnd();
  45662. }
  45663. return null;
  45664. }
  45665. var endFrame = frameRate * (duration / 1000);
  45666. transition.setKeys([{
  45667. frame: 0,
  45668. value: host[property].clone ? host[property].clone() : host[property]
  45669. },
  45670. {
  45671. frame: endFrame,
  45672. value: targetValue
  45673. }]);
  45674. if (!host.animations) {
  45675. host.animations = [];
  45676. }
  45677. host.animations.push(transition);
  45678. var animation = scene.beginAnimation(host, 0, endFrame, false);
  45679. animation.onAnimationEnd = onAnimationEnd;
  45680. return animation;
  45681. };
  45682. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  45683. /**
  45684. * Return the array of runtime animations currently using this animation
  45685. */
  45686. get: function () {
  45687. return this._runtimeAnimations;
  45688. },
  45689. enumerable: true,
  45690. configurable: true
  45691. });
  45692. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  45693. get: function () {
  45694. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  45695. var runtimeAnimation = _a[_i];
  45696. if (!runtimeAnimation.isStopped) {
  45697. return true;
  45698. }
  45699. }
  45700. return false;
  45701. },
  45702. enumerable: true,
  45703. configurable: true
  45704. });
  45705. // Methods
  45706. /**
  45707. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  45708. */
  45709. Animation.prototype.toString = function (fullDetails) {
  45710. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  45711. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  45712. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  45713. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  45714. if (fullDetails) {
  45715. ret += ", Ranges: {";
  45716. var first = true;
  45717. for (var name in this._ranges) {
  45718. if (first) {
  45719. ret += ", ";
  45720. first = false;
  45721. }
  45722. ret += name;
  45723. }
  45724. ret += "}";
  45725. }
  45726. return ret;
  45727. };
  45728. /**
  45729. * Add an event to this animation.
  45730. */
  45731. Animation.prototype.addEvent = function (event) {
  45732. this._events.push(event);
  45733. };
  45734. /**
  45735. * Remove all events found at the given frame
  45736. * @param frame
  45737. */
  45738. Animation.prototype.removeEvents = function (frame) {
  45739. for (var index = 0; index < this._events.length; index++) {
  45740. if (this._events[index].frame === frame) {
  45741. this._events.splice(index, 1);
  45742. index--;
  45743. }
  45744. }
  45745. };
  45746. Animation.prototype.getEvents = function () {
  45747. return this._events;
  45748. };
  45749. Animation.prototype.createRange = function (name, from, to) {
  45750. // check name not already in use; could happen for bones after serialized
  45751. if (!this._ranges[name]) {
  45752. this._ranges[name] = new AnimationRange(name, from, to);
  45753. }
  45754. };
  45755. Animation.prototype.deleteRange = function (name, deleteFrames) {
  45756. if (deleteFrames === void 0) { deleteFrames = true; }
  45757. var range = this._ranges[name];
  45758. if (!range) {
  45759. return;
  45760. }
  45761. if (deleteFrames) {
  45762. var from = range.from;
  45763. var to = range.to;
  45764. // this loop MUST go high to low for multiple splices to work
  45765. for (var key = this._keys.length - 1; key >= 0; key--) {
  45766. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  45767. this._keys.splice(key, 1);
  45768. }
  45769. }
  45770. }
  45771. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  45772. };
  45773. Animation.prototype.getRange = function (name) {
  45774. return this._ranges[name];
  45775. };
  45776. Animation.prototype.getKeys = function () {
  45777. return this._keys;
  45778. };
  45779. Animation.prototype.getHighestFrame = function () {
  45780. var ret = 0;
  45781. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  45782. if (ret < this._keys[key].frame) {
  45783. ret = this._keys[key].frame;
  45784. }
  45785. }
  45786. return ret;
  45787. };
  45788. Animation.prototype.getEasingFunction = function () {
  45789. return this._easingFunction;
  45790. };
  45791. Animation.prototype.setEasingFunction = function (easingFunction) {
  45792. this._easingFunction = easingFunction;
  45793. };
  45794. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  45795. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  45796. };
  45797. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  45798. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  45799. };
  45800. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  45801. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  45802. };
  45803. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  45804. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  45805. };
  45806. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  45807. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  45808. };
  45809. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  45810. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  45811. };
  45812. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  45813. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  45814. };
  45815. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  45816. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  45817. };
  45818. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  45819. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  45820. };
  45821. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  45822. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  45823. };
  45824. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  45825. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  45826. };
  45827. Animation.prototype.clone = function () {
  45828. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  45829. clone.enableBlending = this.enableBlending;
  45830. clone.blendingSpeed = this.blendingSpeed;
  45831. if (this._keys) {
  45832. clone.setKeys(this._keys);
  45833. }
  45834. if (this._ranges) {
  45835. clone._ranges = {};
  45836. for (var name in this._ranges) {
  45837. var range = this._ranges[name];
  45838. if (!range) {
  45839. continue;
  45840. }
  45841. clone._ranges[name] = range.clone();
  45842. }
  45843. }
  45844. return clone;
  45845. };
  45846. Animation.prototype.setKeys = function (values) {
  45847. this._keys = values.slice(0);
  45848. };
  45849. Animation.prototype.serialize = function () {
  45850. var serializationObject = {};
  45851. serializationObject.name = this.name;
  45852. serializationObject.property = this.targetProperty;
  45853. serializationObject.framePerSecond = this.framePerSecond;
  45854. serializationObject.dataType = this.dataType;
  45855. serializationObject.loopBehavior = this.loopMode;
  45856. serializationObject.enableBlending = this.enableBlending;
  45857. serializationObject.blendingSpeed = this.blendingSpeed;
  45858. var dataType = this.dataType;
  45859. serializationObject.keys = [];
  45860. var keys = this.getKeys();
  45861. for (var index = 0; index < keys.length; index++) {
  45862. var animationKey = keys[index];
  45863. var key = {};
  45864. key.frame = animationKey.frame;
  45865. switch (dataType) {
  45866. case Animation.ANIMATIONTYPE_FLOAT:
  45867. key.values = [animationKey.value];
  45868. break;
  45869. case Animation.ANIMATIONTYPE_QUATERNION:
  45870. case Animation.ANIMATIONTYPE_MATRIX:
  45871. case Animation.ANIMATIONTYPE_VECTOR3:
  45872. case Animation.ANIMATIONTYPE_COLOR3:
  45873. key.values = animationKey.value.asArray();
  45874. break;
  45875. }
  45876. serializationObject.keys.push(key);
  45877. }
  45878. serializationObject.ranges = [];
  45879. for (var name in this._ranges) {
  45880. var source = this._ranges[name];
  45881. if (!source) {
  45882. continue;
  45883. }
  45884. var range = {};
  45885. range.name = name;
  45886. range.from = source.from;
  45887. range.to = source.to;
  45888. serializationObject.ranges.push(range);
  45889. }
  45890. return serializationObject;
  45891. };
  45892. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  45893. get: function () {
  45894. return Animation._ANIMATIONTYPE_FLOAT;
  45895. },
  45896. enumerable: true,
  45897. configurable: true
  45898. });
  45899. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  45900. get: function () {
  45901. return Animation._ANIMATIONTYPE_VECTOR3;
  45902. },
  45903. enumerable: true,
  45904. configurable: true
  45905. });
  45906. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  45907. get: function () {
  45908. return Animation._ANIMATIONTYPE_VECTOR2;
  45909. },
  45910. enumerable: true,
  45911. configurable: true
  45912. });
  45913. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  45914. get: function () {
  45915. return Animation._ANIMATIONTYPE_SIZE;
  45916. },
  45917. enumerable: true,
  45918. configurable: true
  45919. });
  45920. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  45921. get: function () {
  45922. return Animation._ANIMATIONTYPE_QUATERNION;
  45923. },
  45924. enumerable: true,
  45925. configurable: true
  45926. });
  45927. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  45928. get: function () {
  45929. return Animation._ANIMATIONTYPE_MATRIX;
  45930. },
  45931. enumerable: true,
  45932. configurable: true
  45933. });
  45934. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  45935. get: function () {
  45936. return Animation._ANIMATIONTYPE_COLOR3;
  45937. },
  45938. enumerable: true,
  45939. configurable: true
  45940. });
  45941. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  45942. get: function () {
  45943. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  45944. },
  45945. enumerable: true,
  45946. configurable: true
  45947. });
  45948. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  45949. get: function () {
  45950. return Animation._ANIMATIONLOOPMODE_CYCLE;
  45951. },
  45952. enumerable: true,
  45953. configurable: true
  45954. });
  45955. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  45956. get: function () {
  45957. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  45958. },
  45959. enumerable: true,
  45960. configurable: true
  45961. });
  45962. Animation.Parse = function (parsedAnimation) {
  45963. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  45964. var dataType = parsedAnimation.dataType;
  45965. var keys = [];
  45966. var data;
  45967. var index;
  45968. if (parsedAnimation.enableBlending) {
  45969. animation.enableBlending = parsedAnimation.enableBlending;
  45970. }
  45971. if (parsedAnimation.blendingSpeed) {
  45972. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  45973. }
  45974. for (index = 0; index < parsedAnimation.keys.length; index++) {
  45975. var key = parsedAnimation.keys[index];
  45976. var inTangent;
  45977. var outTangent;
  45978. switch (dataType) {
  45979. case Animation.ANIMATIONTYPE_FLOAT:
  45980. data = key.values[0];
  45981. if (key.values.length >= 1) {
  45982. inTangent = key.values[1];
  45983. }
  45984. if (key.values.length >= 2) {
  45985. outTangent = key.values[2];
  45986. }
  45987. break;
  45988. case Animation.ANIMATIONTYPE_QUATERNION:
  45989. data = BABYLON.Quaternion.FromArray(key.values);
  45990. if (key.values.length >= 8) {
  45991. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  45992. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  45993. inTangent = _inTangent;
  45994. }
  45995. }
  45996. if (key.values.length >= 12) {
  45997. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  45998. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  45999. outTangent = _outTangent;
  46000. }
  46001. }
  46002. break;
  46003. case Animation.ANIMATIONTYPE_MATRIX:
  46004. data = BABYLON.Matrix.FromArray(key.values);
  46005. break;
  46006. case Animation.ANIMATIONTYPE_COLOR3:
  46007. data = BABYLON.Color3.FromArray(key.values);
  46008. break;
  46009. case Animation.ANIMATIONTYPE_VECTOR3:
  46010. default:
  46011. data = BABYLON.Vector3.FromArray(key.values);
  46012. break;
  46013. }
  46014. var keyData = {};
  46015. keyData.frame = key.frame;
  46016. keyData.value = data;
  46017. if (inTangent != undefined) {
  46018. keyData.inTangent = inTangent;
  46019. }
  46020. if (outTangent != undefined) {
  46021. keyData.outTangent = outTangent;
  46022. }
  46023. keys.push(keyData);
  46024. }
  46025. animation.setKeys(keys);
  46026. if (parsedAnimation.ranges) {
  46027. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  46028. data = parsedAnimation.ranges[index];
  46029. animation.createRange(data.name, data.from, data.to);
  46030. }
  46031. }
  46032. return animation;
  46033. };
  46034. Animation.AppendSerializedAnimations = function (source, destination) {
  46035. if (source.animations) {
  46036. destination.animations = [];
  46037. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  46038. var animation = source.animations[animationIndex];
  46039. destination.animations.push(animation.serialize());
  46040. }
  46041. }
  46042. };
  46043. Animation.AllowMatricesInterpolation = false;
  46044. // Statics
  46045. Animation._ANIMATIONTYPE_FLOAT = 0;
  46046. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  46047. Animation._ANIMATIONTYPE_QUATERNION = 2;
  46048. Animation._ANIMATIONTYPE_MATRIX = 3;
  46049. Animation._ANIMATIONTYPE_COLOR3 = 4;
  46050. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  46051. Animation._ANIMATIONTYPE_SIZE = 6;
  46052. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  46053. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  46054. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  46055. return Animation;
  46056. }());
  46057. BABYLON.Animation = Animation;
  46058. })(BABYLON || (BABYLON = {}));
  46059. //# sourceMappingURL=babylon.animation.js.map
  46060. var BABYLON;
  46061. (function (BABYLON) {
  46062. /**
  46063. * This class defines the direct association between an animation and a target
  46064. */
  46065. var TargetedAnimation = /** @class */ (function () {
  46066. function TargetedAnimation() {
  46067. }
  46068. return TargetedAnimation;
  46069. }());
  46070. BABYLON.TargetedAnimation = TargetedAnimation;
  46071. /**
  46072. * Use this class to create coordinated animations on multiple targets
  46073. */
  46074. var AnimationGroup = /** @class */ (function () {
  46075. function AnimationGroup(name, scene) {
  46076. if (scene === void 0) { scene = null; }
  46077. this.name = name;
  46078. this._targetedAnimations = new Array();
  46079. this._animatables = new Array();
  46080. this._from = Number.MAX_VALUE;
  46081. this._to = -Number.MAX_VALUE;
  46082. this._speedRatio = 1;
  46083. this.onAnimationEndObservable = new BABYLON.Observable();
  46084. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  46085. this._scene.animationGroups.push(this);
  46086. }
  46087. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  46088. /**
  46089. * Define if the animations are started
  46090. */
  46091. get: function () {
  46092. return this._isStarted;
  46093. },
  46094. enumerable: true,
  46095. configurable: true
  46096. });
  46097. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  46098. /**
  46099. * Gets or sets the speed ratio to use for all animations
  46100. */
  46101. get: function () {
  46102. return this._speedRatio;
  46103. },
  46104. /**
  46105. * Gets or sets the speed ratio to use for all animations
  46106. */
  46107. set: function (value) {
  46108. if (this._speedRatio === value) {
  46109. return;
  46110. }
  46111. this._speedRatio = value;
  46112. for (var index = 0; index < this._animatables.length; index++) {
  46113. var animatable = this._animatables[index];
  46114. animatable.speedRatio = this._speedRatio;
  46115. }
  46116. },
  46117. enumerable: true,
  46118. configurable: true
  46119. });
  46120. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  46121. /**
  46122. * Gets the targeted animations for this animation group
  46123. */
  46124. get: function () {
  46125. return this._targetedAnimations;
  46126. },
  46127. enumerable: true,
  46128. configurable: true
  46129. });
  46130. /**
  46131. * Add an animation (with its target) in the group
  46132. * @param animation defines the animation we want to add
  46133. * @param target defines the target of the animation
  46134. * @returns the {BABYLON.TargetedAnimation} object
  46135. */
  46136. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  46137. var targetedAnimation = {
  46138. animation: animation,
  46139. target: target
  46140. };
  46141. var keys = animation.getKeys();
  46142. if (this._from > keys[0].frame) {
  46143. this._from = keys[0].frame;
  46144. }
  46145. if (this._to < keys[keys.length - 1].frame) {
  46146. this._to = keys[keys.length - 1].frame;
  46147. }
  46148. this._targetedAnimations.push(targetedAnimation);
  46149. return targetedAnimation;
  46150. };
  46151. /**
  46152. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  46153. * It can add constant keys at begin or end
  46154. * @param beginFrame defines the new begin frame for all animations. It can't be bigger than the smallest begin frame of all animations
  46155. * @param endFrame defines the new end frame for all animations. It can't be smaller than the largest end frame of all animations
  46156. */
  46157. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  46158. if (beginFrame === void 0) { beginFrame = -Number.MAX_VALUE; }
  46159. if (endFrame === void 0) { endFrame = Number.MAX_VALUE; }
  46160. beginFrame = Math.max(beginFrame, this._from);
  46161. endFrame = Math.min(endFrame, this._to);
  46162. for (var index = 0; index < this._targetedAnimations.length; index++) {
  46163. var targetedAnimation = this._targetedAnimations[index];
  46164. var keys = targetedAnimation.animation.getKeys();
  46165. var startKey = keys[0];
  46166. var endKey = keys[keys.length - 1];
  46167. if (startKey.frame > beginFrame) {
  46168. var newKey = {
  46169. frame: beginFrame,
  46170. value: startKey.value,
  46171. inTangent: startKey.inTangent,
  46172. outTangent: startKey.outTangent,
  46173. interpolation: startKey.interpolation
  46174. };
  46175. keys.splice(0, 0, newKey);
  46176. }
  46177. if (endKey.frame < endFrame) {
  46178. var newKey = {
  46179. frame: endFrame,
  46180. value: endKey.value,
  46181. inTangent: endKey.outTangent,
  46182. outTangent: endKey.outTangent,
  46183. interpolation: endKey.interpolation
  46184. };
  46185. keys.push(newKey);
  46186. }
  46187. }
  46188. return this;
  46189. };
  46190. /**
  46191. * Start all animations on given targets
  46192. * @param loop defines if animations must loop
  46193. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  46194. */
  46195. AnimationGroup.prototype.start = function (loop, speedRatio) {
  46196. var _this = this;
  46197. if (loop === void 0) { loop = false; }
  46198. if (speedRatio === void 0) { speedRatio = 1; }
  46199. if (this._isStarted || this._targetedAnimations.length === 0) {
  46200. return this;
  46201. }
  46202. var _loop_1 = function () {
  46203. var targetedAnimation = this_1._targetedAnimations[index];
  46204. this_1._animatables.push(this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], this_1._from, this_1._to, loop, speedRatio, function () {
  46205. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  46206. }));
  46207. };
  46208. var this_1 = this;
  46209. for (var index = 0; index < this._targetedAnimations.length; index++) {
  46210. _loop_1();
  46211. }
  46212. this._speedRatio = speedRatio;
  46213. this._isStarted = true;
  46214. return this;
  46215. };
  46216. /**
  46217. * Pause all animations
  46218. */
  46219. AnimationGroup.prototype.pause = function () {
  46220. if (!this._isStarted) {
  46221. return this;
  46222. }
  46223. for (var index = 0; index < this._animatables.length; index++) {
  46224. var animatable = this._animatables[index];
  46225. animatable.pause();
  46226. }
  46227. return this;
  46228. };
  46229. /**
  46230. * Play all animations to initial state
  46231. * This function will start() the animations if they were not started or will restart() them if they were paused
  46232. * @param loop defines if animations must loop
  46233. */
  46234. AnimationGroup.prototype.play = function (loop) {
  46235. if (this.isStarted) {
  46236. if (loop !== undefined) {
  46237. for (var index = 0; index < this._animatables.length; index++) {
  46238. var animatable = this._animatables[index];
  46239. animatable.loopAnimation = loop;
  46240. }
  46241. }
  46242. this.restart();
  46243. }
  46244. else {
  46245. this.start(loop, this._speedRatio);
  46246. }
  46247. return this;
  46248. };
  46249. /**
  46250. * Reset all animations to initial state
  46251. */
  46252. AnimationGroup.prototype.reset = function () {
  46253. if (!this._isStarted) {
  46254. return this;
  46255. }
  46256. for (var index = 0; index < this._animatables.length; index++) {
  46257. var animatable = this._animatables[index];
  46258. animatable.reset();
  46259. }
  46260. return this;
  46261. };
  46262. /**
  46263. * Restart animations from key 0
  46264. */
  46265. AnimationGroup.prototype.restart = function () {
  46266. if (!this._isStarted) {
  46267. return this;
  46268. }
  46269. for (var index = 0; index < this._animatables.length; index++) {
  46270. var animatable = this._animatables[index];
  46271. animatable.restart();
  46272. }
  46273. return this;
  46274. };
  46275. /**
  46276. * Stop all animations
  46277. */
  46278. AnimationGroup.prototype.stop = function () {
  46279. if (!this._isStarted) {
  46280. return this;
  46281. }
  46282. for (var index = 0; index < this._animatables.length; index++) {
  46283. var animatable = this._animatables[index];
  46284. animatable.stop();
  46285. }
  46286. this._isStarted = false;
  46287. return this;
  46288. };
  46289. /**
  46290. * Dispose all associated resources
  46291. */
  46292. AnimationGroup.prototype.dispose = function () {
  46293. this._targetedAnimations = [];
  46294. this._animatables = [];
  46295. var index = this._scene.animationGroups.indexOf(this);
  46296. if (index > -1) {
  46297. this._scene.animationGroups.splice(index, 1);
  46298. }
  46299. };
  46300. return AnimationGroup;
  46301. }());
  46302. BABYLON.AnimationGroup = AnimationGroup;
  46303. })(BABYLON || (BABYLON = {}));
  46304. //# sourceMappingURL=babylon.animationGroup.js.map
  46305. var BABYLON;
  46306. (function (BABYLON) {
  46307. var RuntimeAnimation = /** @class */ (function () {
  46308. function RuntimeAnimation(target, animation) {
  46309. this._offsetsCache = {};
  46310. this._highLimitsCache = {};
  46311. this._stopped = false;
  46312. this._blendingFactor = 0;
  46313. this._ratioOffset = 0;
  46314. this._animation = animation;
  46315. this._target = target;
  46316. animation._runtimeAnimations.push(this);
  46317. }
  46318. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  46319. get: function () {
  46320. return this._animation;
  46321. },
  46322. enumerable: true,
  46323. configurable: true
  46324. });
  46325. RuntimeAnimation.prototype.reset = function () {
  46326. this._offsetsCache = {};
  46327. this._highLimitsCache = {};
  46328. this.currentFrame = 0;
  46329. this._blendingFactor = 0;
  46330. this._originalBlendValue = null;
  46331. };
  46332. RuntimeAnimation.prototype.isStopped = function () {
  46333. return this._stopped;
  46334. };
  46335. RuntimeAnimation.prototype.dispose = function () {
  46336. var index = this._animation.runtimeAnimations.indexOf(this);
  46337. if (index > -1) {
  46338. this._animation.runtimeAnimations.splice(index, 1);
  46339. }
  46340. };
  46341. RuntimeAnimation.prototype._getKeyValue = function (value) {
  46342. if (typeof value === "function") {
  46343. return value();
  46344. }
  46345. return value;
  46346. };
  46347. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  46348. if (loopMode === BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  46349. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  46350. }
  46351. this.currentFrame = currentFrame;
  46352. var keys = this._animation.getKeys();
  46353. // Try to get a hash to find the right key
  46354. 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));
  46355. if (keys[startKeyIndex].frame >= currentFrame) {
  46356. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  46357. startKeyIndex--;
  46358. }
  46359. }
  46360. for (var key = startKeyIndex; key < keys.length; key++) {
  46361. var endKey = keys[key + 1];
  46362. if (endKey.frame >= currentFrame) {
  46363. var startKey = keys[key];
  46364. var startValue = this._getKeyValue(startKey.value);
  46365. if (startKey.interpolation === BABYLON.AnimationKeyInterpolation.STEP) {
  46366. return startValue;
  46367. }
  46368. var endValue = this._getKeyValue(endKey.value);
  46369. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  46370. var frameDelta = endKey.frame - startKey.frame;
  46371. // gradient : percent of currentFrame between the frame inf and the frame sup
  46372. var gradient = (currentFrame - startKey.frame) / frameDelta;
  46373. // check for easingFunction and correction of gradient
  46374. var easingFunction = this._animation.getEasingFunction();
  46375. if (easingFunction != null) {
  46376. gradient = easingFunction.ease(gradient);
  46377. }
  46378. switch (this._animation.dataType) {
  46379. // Float
  46380. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  46381. var floatValue = useTangent ? this._animation.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this._animation.floatInterpolateFunction(startValue, endValue, gradient);
  46382. switch (loopMode) {
  46383. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  46384. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  46385. return floatValue;
  46386. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  46387. return offsetValue * repeatCount + floatValue;
  46388. }
  46389. break;
  46390. // Quaternion
  46391. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  46392. var quatValue = useTangent ? this._animation.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.quaternionInterpolateFunction(startValue, endValue, gradient);
  46393. switch (loopMode) {
  46394. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  46395. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  46396. return quatValue;
  46397. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  46398. return quatValue.add(offsetValue.scale(repeatCount));
  46399. }
  46400. return quatValue;
  46401. // Vector3
  46402. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  46403. var vec3Value = useTangent ? this._animation.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector3InterpolateFunction(startValue, endValue, gradient);
  46404. switch (loopMode) {
  46405. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  46406. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  46407. return vec3Value;
  46408. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  46409. return vec3Value.add(offsetValue.scale(repeatCount));
  46410. }
  46411. // Vector2
  46412. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  46413. var vec2Value = useTangent ? this._animation.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector2InterpolateFunction(startValue, endValue, gradient);
  46414. switch (loopMode) {
  46415. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  46416. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  46417. return vec2Value;
  46418. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  46419. return vec2Value.add(offsetValue.scale(repeatCount));
  46420. }
  46421. // Size
  46422. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  46423. switch (loopMode) {
  46424. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  46425. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  46426. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient);
  46427. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  46428. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  46429. }
  46430. // Color3
  46431. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  46432. switch (loopMode) {
  46433. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  46434. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  46435. return this._animation.color3InterpolateFunction(startValue, endValue, gradient);
  46436. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  46437. return this._animation.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  46438. }
  46439. // Matrix
  46440. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  46441. switch (loopMode) {
  46442. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  46443. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  46444. if (BABYLON.Animation.AllowMatricesInterpolation) {
  46445. return this._animation.matrixInterpolateFunction(startValue, endValue, gradient);
  46446. }
  46447. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  46448. return startValue;
  46449. }
  46450. default:
  46451. break;
  46452. }
  46453. break;
  46454. }
  46455. }
  46456. return this._getKeyValue(keys[keys.length - 1].value);
  46457. };
  46458. RuntimeAnimation.prototype.setValue = function (currentValue, blend) {
  46459. if (blend === void 0) { blend = false; }
  46460. // Set value
  46461. var path;
  46462. var destination;
  46463. var targetPropertyPath = this._animation.targetPropertyPath;
  46464. if (targetPropertyPath.length > 1) {
  46465. var property = this._target[targetPropertyPath[0]];
  46466. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  46467. property = property[targetPropertyPath[index]];
  46468. }
  46469. path = targetPropertyPath[targetPropertyPath.length - 1];
  46470. destination = property;
  46471. }
  46472. else {
  46473. path = targetPropertyPath[0];
  46474. destination = this._target;
  46475. }
  46476. // Blending
  46477. if (this._animation.enableBlending && this._blendingFactor <= 1.0) {
  46478. if (!this._originalBlendValue) {
  46479. if (destination[path].clone) {
  46480. this._originalBlendValue = destination[path].clone();
  46481. }
  46482. else {
  46483. this._originalBlendValue = destination[path];
  46484. }
  46485. }
  46486. if (this._originalBlendValue.prototype) {
  46487. if (this._originalBlendValue.prototype.Lerp) {
  46488. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  46489. }
  46490. else {
  46491. destination[path] = currentValue;
  46492. }
  46493. }
  46494. else if (this._originalBlendValue.m) {
  46495. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  46496. }
  46497. else {
  46498. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  46499. }
  46500. this._blendingFactor += this._animation.blendingSpeed;
  46501. }
  46502. else {
  46503. destination[path] = currentValue;
  46504. }
  46505. if (this._target.markAsDirty) {
  46506. this._target.markAsDirty(this._animation.targetProperty);
  46507. }
  46508. };
  46509. RuntimeAnimation.prototype.goToFrame = function (frame) {
  46510. var keys = this._animation.getKeys();
  46511. if (frame < keys[0].frame) {
  46512. frame = keys[0].frame;
  46513. }
  46514. else if (frame > keys[keys.length - 1].frame) {
  46515. frame = keys[keys.length - 1].frame;
  46516. }
  46517. var currentValue = this._interpolate(frame, 0, this._animation.loopMode);
  46518. this.setValue(currentValue);
  46519. };
  46520. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  46521. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  46522. this._ratioOffset = this._previousRatio - newRatio;
  46523. };
  46524. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  46525. if (blend === void 0) { blend = false; }
  46526. var targetPropertyPath = this._animation.targetPropertyPath;
  46527. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  46528. this._stopped = true;
  46529. return false;
  46530. }
  46531. var returnValue = true;
  46532. var keys = this._animation.getKeys();
  46533. // Adding a start key at frame 0 if missing
  46534. if (keys[0].frame !== 0) {
  46535. var newKey = { frame: 0, value: keys[0].value };
  46536. keys.splice(0, 0, newKey);
  46537. }
  46538. // Check limits
  46539. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  46540. from = keys[0].frame;
  46541. }
  46542. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  46543. to = keys[keys.length - 1].frame;
  46544. }
  46545. //to and from cannot be the same key
  46546. if (from === to) {
  46547. if (from > keys[0].frame) {
  46548. from--;
  46549. }
  46550. else if (to < keys[keys.length - 1].frame) {
  46551. to++;
  46552. }
  46553. }
  46554. // Compute ratio
  46555. var range = to - from;
  46556. var offsetValue;
  46557. // ratio represents the frame delta between from and to
  46558. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  46559. var highLimitValue = 0;
  46560. this._previousDelay = delay;
  46561. this._previousRatio = ratio;
  46562. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) {
  46563. returnValue = false;
  46564. highLimitValue = this._getKeyValue(keys[keys.length - 1].value);
  46565. }
  46566. else {
  46567. // Get max value if required
  46568. if (this._animation.loopMode !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  46569. var keyOffset = to.toString() + from.toString();
  46570. if (!this._offsetsCache[keyOffset]) {
  46571. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  46572. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  46573. switch (this._animation.dataType) {
  46574. // Float
  46575. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  46576. this._offsetsCache[keyOffset] = toValue - fromValue;
  46577. break;
  46578. // Quaternion
  46579. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  46580. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  46581. break;
  46582. // Vector3
  46583. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  46584. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  46585. // Vector2
  46586. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  46587. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  46588. // Size
  46589. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  46590. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  46591. // Color3
  46592. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  46593. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  46594. default:
  46595. break;
  46596. }
  46597. this._highLimitsCache[keyOffset] = toValue;
  46598. }
  46599. highLimitValue = this._highLimitsCache[keyOffset];
  46600. offsetValue = this._offsetsCache[keyOffset];
  46601. }
  46602. }
  46603. if (offsetValue === undefined) {
  46604. switch (this._animation.dataType) {
  46605. // Float
  46606. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  46607. offsetValue = 0;
  46608. break;
  46609. // Quaternion
  46610. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  46611. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  46612. break;
  46613. // Vector3
  46614. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  46615. offsetValue = BABYLON.Vector3.Zero();
  46616. break;
  46617. // Vector2
  46618. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  46619. offsetValue = BABYLON.Vector2.Zero();
  46620. break;
  46621. // Size
  46622. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  46623. offsetValue = BABYLON.Size.Zero();
  46624. break;
  46625. // Color3
  46626. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  46627. offsetValue = BABYLON.Color3.Black();
  46628. }
  46629. }
  46630. // Compute value
  46631. var repeatCount = (ratio / range) >> 0;
  46632. var currentFrame = returnValue ? from + ratio % range : to;
  46633. var currentValue = this._interpolate(currentFrame, repeatCount, this._animation.loopMode, offsetValue, highLimitValue);
  46634. // Set value
  46635. this.setValue(currentValue);
  46636. // Check events
  46637. var events = this._animation.getEvents();
  46638. for (var index = 0; index < events.length; index++) {
  46639. // Make sure current frame has passed event frame and that event frame is within the current range
  46640. // Also, handle both forward and reverse animations
  46641. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  46642. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  46643. var event = events[index];
  46644. if (!event.isDone) {
  46645. // If event should be done only once, remove it.
  46646. if (event.onlyOnce) {
  46647. events.splice(index, 1);
  46648. index--;
  46649. }
  46650. event.isDone = true;
  46651. event.action();
  46652. } // Don't do anything if the event has already be done.
  46653. }
  46654. else if (events[index].isDone && !events[index].onlyOnce) {
  46655. // reset event, the animation is looping
  46656. events[index].isDone = false;
  46657. }
  46658. }
  46659. if (!returnValue) {
  46660. this._stopped = true;
  46661. }
  46662. return returnValue;
  46663. };
  46664. return RuntimeAnimation;
  46665. }());
  46666. BABYLON.RuntimeAnimation = RuntimeAnimation;
  46667. })(BABYLON || (BABYLON = {}));
  46668. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  46669. var BABYLON;
  46670. (function (BABYLON) {
  46671. var Animatable = /** @class */ (function () {
  46672. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  46673. if (fromFrame === void 0) { fromFrame = 0; }
  46674. if (toFrame === void 0) { toFrame = 100; }
  46675. if (loopAnimation === void 0) { loopAnimation = false; }
  46676. if (speedRatio === void 0) { speedRatio = 1.0; }
  46677. this.target = target;
  46678. this.fromFrame = fromFrame;
  46679. this.toFrame = toFrame;
  46680. this.loopAnimation = loopAnimation;
  46681. this.onAnimationEnd = onAnimationEnd;
  46682. this._localDelayOffset = null;
  46683. this._pausedDelay = null;
  46684. this._runtimeAnimations = new Array();
  46685. this._paused = false;
  46686. this._speedRatio = 1;
  46687. this.animationStarted = false;
  46688. if (animations) {
  46689. this.appendAnimations(target, animations);
  46690. }
  46691. this._speedRatio = speedRatio;
  46692. this._scene = scene;
  46693. scene._activeAnimatables.push(this);
  46694. }
  46695. Object.defineProperty(Animatable.prototype, "speedRatio", {
  46696. get: function () {
  46697. return this._speedRatio;
  46698. },
  46699. set: function (value) {
  46700. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  46701. var animation = this._runtimeAnimations[index];
  46702. animation._prepareForSpeedRatioChange(value);
  46703. }
  46704. this._speedRatio = value;
  46705. },
  46706. enumerable: true,
  46707. configurable: true
  46708. });
  46709. // Methods
  46710. Animatable.prototype.getAnimations = function () {
  46711. return this._runtimeAnimations;
  46712. };
  46713. Animatable.prototype.appendAnimations = function (target, animations) {
  46714. for (var index = 0; index < animations.length; index++) {
  46715. var animation = animations[index];
  46716. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation));
  46717. }
  46718. };
  46719. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  46720. var runtimeAnimations = this._runtimeAnimations;
  46721. for (var index = 0; index < runtimeAnimations.length; index++) {
  46722. if (runtimeAnimations[index].animation.targetProperty === property) {
  46723. return runtimeAnimations[index].animation;
  46724. }
  46725. }
  46726. return null;
  46727. };
  46728. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  46729. var runtimeAnimations = this._runtimeAnimations;
  46730. for (var index = 0; index < runtimeAnimations.length; index++) {
  46731. if (runtimeAnimations[index].animation.targetProperty === property) {
  46732. return runtimeAnimations[index];
  46733. }
  46734. }
  46735. return null;
  46736. };
  46737. Animatable.prototype.reset = function () {
  46738. var runtimeAnimations = this._runtimeAnimations;
  46739. for (var index = 0; index < runtimeAnimations.length; index++) {
  46740. runtimeAnimations[index].reset();
  46741. }
  46742. // Reset to original value
  46743. for (index = 0; index < runtimeAnimations.length; index++) {
  46744. var animation = runtimeAnimations[index];
  46745. animation.animate(0, this.fromFrame, this.toFrame, false, this._speedRatio);
  46746. }
  46747. this._localDelayOffset = null;
  46748. this._pausedDelay = null;
  46749. };
  46750. Animatable.prototype.enableBlending = function (blendingSpeed) {
  46751. var runtimeAnimations = this._runtimeAnimations;
  46752. for (var index = 0; index < runtimeAnimations.length; index++) {
  46753. runtimeAnimations[index].animation.enableBlending = true;
  46754. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  46755. }
  46756. };
  46757. Animatable.prototype.disableBlending = function () {
  46758. var runtimeAnimations = this._runtimeAnimations;
  46759. for (var index = 0; index < runtimeAnimations.length; index++) {
  46760. runtimeAnimations[index].animation.enableBlending = false;
  46761. }
  46762. };
  46763. Animatable.prototype.goToFrame = function (frame) {
  46764. var runtimeAnimations = this._runtimeAnimations;
  46765. if (runtimeAnimations[0]) {
  46766. var fps = runtimeAnimations[0].animation.framePerSecond;
  46767. var currentFrame = runtimeAnimations[0].currentFrame;
  46768. var adjustTime = frame - currentFrame;
  46769. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  46770. if (this._localDelayOffset === null) {
  46771. this._localDelayOffset = 0;
  46772. }
  46773. this._localDelayOffset -= delay;
  46774. }
  46775. for (var index = 0; index < runtimeAnimations.length; index++) {
  46776. runtimeAnimations[index].goToFrame(frame);
  46777. }
  46778. };
  46779. Animatable.prototype.pause = function () {
  46780. if (this._paused) {
  46781. return;
  46782. }
  46783. this._paused = true;
  46784. };
  46785. Animatable.prototype.restart = function () {
  46786. this._paused = false;
  46787. };
  46788. Animatable.prototype.stop = function (animationName) {
  46789. if (animationName) {
  46790. var idx = this._scene._activeAnimatables.indexOf(this);
  46791. if (idx > -1) {
  46792. var runtimeAnimations = this._runtimeAnimations;
  46793. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  46794. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  46795. continue;
  46796. }
  46797. runtimeAnimations[index].dispose();
  46798. runtimeAnimations.splice(index, 1);
  46799. }
  46800. if (runtimeAnimations.length == 0) {
  46801. this._scene._activeAnimatables.splice(idx, 1);
  46802. if (this.onAnimationEnd) {
  46803. this.onAnimationEnd();
  46804. }
  46805. }
  46806. }
  46807. }
  46808. else {
  46809. var index = this._scene._activeAnimatables.indexOf(this);
  46810. if (index > -1) {
  46811. this._scene._activeAnimatables.splice(index, 1);
  46812. var runtimeAnimations = this._runtimeAnimations;
  46813. for (var index = 0; index < runtimeAnimations.length; index++) {
  46814. runtimeAnimations[index].dispose();
  46815. }
  46816. if (this.onAnimationEnd) {
  46817. this.onAnimationEnd();
  46818. }
  46819. }
  46820. }
  46821. };
  46822. Animatable.prototype._animate = function (delay) {
  46823. if (this._paused) {
  46824. this.animationStarted = false;
  46825. if (this._pausedDelay === null) {
  46826. this._pausedDelay = delay;
  46827. }
  46828. return true;
  46829. }
  46830. if (this._localDelayOffset === null) {
  46831. this._localDelayOffset = delay;
  46832. this._pausedDelay = null;
  46833. }
  46834. else if (this._pausedDelay !== null) {
  46835. this._localDelayOffset += delay - this._pausedDelay;
  46836. this._pausedDelay = null;
  46837. }
  46838. // Animating
  46839. var running = false;
  46840. var runtimeAnimations = this._runtimeAnimations;
  46841. var index;
  46842. for (index = 0; index < runtimeAnimations.length; index++) {
  46843. var animation = runtimeAnimations[index];
  46844. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio);
  46845. running = running || isRunning;
  46846. }
  46847. this.animationStarted = running;
  46848. if (!running) {
  46849. // Remove from active animatables
  46850. index = this._scene._activeAnimatables.indexOf(this);
  46851. this._scene._activeAnimatables.splice(index, 1);
  46852. // Dispose all runtime animations
  46853. for (index = 0; index < runtimeAnimations.length; index++) {
  46854. runtimeAnimations[index].dispose();
  46855. }
  46856. }
  46857. if (!running && this.onAnimationEnd) {
  46858. this.onAnimationEnd();
  46859. this.onAnimationEnd = null;
  46860. }
  46861. return running;
  46862. };
  46863. return Animatable;
  46864. }());
  46865. BABYLON.Animatable = Animatable;
  46866. })(BABYLON || (BABYLON = {}));
  46867. //# sourceMappingURL=babylon.animatable.js.map
  46868. var BABYLON;
  46869. (function (BABYLON) {
  46870. var EasingFunction = /** @class */ (function () {
  46871. function EasingFunction() {
  46872. // Properties
  46873. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  46874. }
  46875. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  46876. get: function () {
  46877. return EasingFunction._EASINGMODE_EASEIN;
  46878. },
  46879. enumerable: true,
  46880. configurable: true
  46881. });
  46882. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  46883. get: function () {
  46884. return EasingFunction._EASINGMODE_EASEOUT;
  46885. },
  46886. enumerable: true,
  46887. configurable: true
  46888. });
  46889. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  46890. get: function () {
  46891. return EasingFunction._EASINGMODE_EASEINOUT;
  46892. },
  46893. enumerable: true,
  46894. configurable: true
  46895. });
  46896. EasingFunction.prototype.setEasingMode = function (easingMode) {
  46897. var n = Math.min(Math.max(easingMode, 0), 2);
  46898. this._easingMode = n;
  46899. };
  46900. EasingFunction.prototype.getEasingMode = function () {
  46901. return this._easingMode;
  46902. };
  46903. EasingFunction.prototype.easeInCore = function (gradient) {
  46904. throw new Error('You must implement this method');
  46905. };
  46906. EasingFunction.prototype.ease = function (gradient) {
  46907. switch (this._easingMode) {
  46908. case EasingFunction.EASINGMODE_EASEIN:
  46909. return this.easeInCore(gradient);
  46910. case EasingFunction.EASINGMODE_EASEOUT:
  46911. return (1 - this.easeInCore(1 - gradient));
  46912. }
  46913. if (gradient >= 0.5) {
  46914. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  46915. }
  46916. return (this.easeInCore(gradient * 2) * 0.5);
  46917. };
  46918. //Statics
  46919. EasingFunction._EASINGMODE_EASEIN = 0;
  46920. EasingFunction._EASINGMODE_EASEOUT = 1;
  46921. EasingFunction._EASINGMODE_EASEINOUT = 2;
  46922. return EasingFunction;
  46923. }());
  46924. BABYLON.EasingFunction = EasingFunction;
  46925. var CircleEase = /** @class */ (function (_super) {
  46926. __extends(CircleEase, _super);
  46927. function CircleEase() {
  46928. return _super !== null && _super.apply(this, arguments) || this;
  46929. }
  46930. CircleEase.prototype.easeInCore = function (gradient) {
  46931. gradient = Math.max(0, Math.min(1, gradient));
  46932. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  46933. };
  46934. return CircleEase;
  46935. }(EasingFunction));
  46936. BABYLON.CircleEase = CircleEase;
  46937. var BackEase = /** @class */ (function (_super) {
  46938. __extends(BackEase, _super);
  46939. function BackEase(amplitude) {
  46940. if (amplitude === void 0) { amplitude = 1; }
  46941. var _this = _super.call(this) || this;
  46942. _this.amplitude = amplitude;
  46943. return _this;
  46944. }
  46945. BackEase.prototype.easeInCore = function (gradient) {
  46946. var num = Math.max(0, this.amplitude);
  46947. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  46948. };
  46949. return BackEase;
  46950. }(EasingFunction));
  46951. BABYLON.BackEase = BackEase;
  46952. var BounceEase = /** @class */ (function (_super) {
  46953. __extends(BounceEase, _super);
  46954. function BounceEase(bounces, bounciness) {
  46955. if (bounces === void 0) { bounces = 3; }
  46956. if (bounciness === void 0) { bounciness = 2; }
  46957. var _this = _super.call(this) || this;
  46958. _this.bounces = bounces;
  46959. _this.bounciness = bounciness;
  46960. return _this;
  46961. }
  46962. BounceEase.prototype.easeInCore = function (gradient) {
  46963. var y = Math.max(0.0, this.bounces);
  46964. var bounciness = this.bounciness;
  46965. if (bounciness <= 1.0) {
  46966. bounciness = 1.001;
  46967. }
  46968. var num9 = Math.pow(bounciness, y);
  46969. var num5 = 1.0 - bounciness;
  46970. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  46971. var num15 = gradient * num4;
  46972. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  46973. var num3 = Math.floor(num65);
  46974. var num13 = num3 + 1.0;
  46975. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  46976. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  46977. var num7 = (num8 + num12) * 0.5;
  46978. var num6 = gradient - num7;
  46979. var num2 = num7 - num8;
  46980. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  46981. };
  46982. return BounceEase;
  46983. }(EasingFunction));
  46984. BABYLON.BounceEase = BounceEase;
  46985. var CubicEase = /** @class */ (function (_super) {
  46986. __extends(CubicEase, _super);
  46987. function CubicEase() {
  46988. return _super !== null && _super.apply(this, arguments) || this;
  46989. }
  46990. CubicEase.prototype.easeInCore = function (gradient) {
  46991. return (gradient * gradient * gradient);
  46992. };
  46993. return CubicEase;
  46994. }(EasingFunction));
  46995. BABYLON.CubicEase = CubicEase;
  46996. var ElasticEase = /** @class */ (function (_super) {
  46997. __extends(ElasticEase, _super);
  46998. function ElasticEase(oscillations, springiness) {
  46999. if (oscillations === void 0) { oscillations = 3; }
  47000. if (springiness === void 0) { springiness = 3; }
  47001. var _this = _super.call(this) || this;
  47002. _this.oscillations = oscillations;
  47003. _this.springiness = springiness;
  47004. return _this;
  47005. }
  47006. ElasticEase.prototype.easeInCore = function (gradient) {
  47007. var num2;
  47008. var num3 = Math.max(0.0, this.oscillations);
  47009. var num = Math.max(0.0, this.springiness);
  47010. if (num == 0) {
  47011. num2 = gradient;
  47012. }
  47013. else {
  47014. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  47015. }
  47016. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  47017. };
  47018. return ElasticEase;
  47019. }(EasingFunction));
  47020. BABYLON.ElasticEase = ElasticEase;
  47021. var ExponentialEase = /** @class */ (function (_super) {
  47022. __extends(ExponentialEase, _super);
  47023. function ExponentialEase(exponent) {
  47024. if (exponent === void 0) { exponent = 2; }
  47025. var _this = _super.call(this) || this;
  47026. _this.exponent = exponent;
  47027. return _this;
  47028. }
  47029. ExponentialEase.prototype.easeInCore = function (gradient) {
  47030. if (this.exponent <= 0) {
  47031. return gradient;
  47032. }
  47033. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  47034. };
  47035. return ExponentialEase;
  47036. }(EasingFunction));
  47037. BABYLON.ExponentialEase = ExponentialEase;
  47038. var PowerEase = /** @class */ (function (_super) {
  47039. __extends(PowerEase, _super);
  47040. function PowerEase(power) {
  47041. if (power === void 0) { power = 2; }
  47042. var _this = _super.call(this) || this;
  47043. _this.power = power;
  47044. return _this;
  47045. }
  47046. PowerEase.prototype.easeInCore = function (gradient) {
  47047. var y = Math.max(0.0, this.power);
  47048. return Math.pow(gradient, y);
  47049. };
  47050. return PowerEase;
  47051. }(EasingFunction));
  47052. BABYLON.PowerEase = PowerEase;
  47053. var QuadraticEase = /** @class */ (function (_super) {
  47054. __extends(QuadraticEase, _super);
  47055. function QuadraticEase() {
  47056. return _super !== null && _super.apply(this, arguments) || this;
  47057. }
  47058. QuadraticEase.prototype.easeInCore = function (gradient) {
  47059. return (gradient * gradient);
  47060. };
  47061. return QuadraticEase;
  47062. }(EasingFunction));
  47063. BABYLON.QuadraticEase = QuadraticEase;
  47064. var QuarticEase = /** @class */ (function (_super) {
  47065. __extends(QuarticEase, _super);
  47066. function QuarticEase() {
  47067. return _super !== null && _super.apply(this, arguments) || this;
  47068. }
  47069. QuarticEase.prototype.easeInCore = function (gradient) {
  47070. return (gradient * gradient * gradient * gradient);
  47071. };
  47072. return QuarticEase;
  47073. }(EasingFunction));
  47074. BABYLON.QuarticEase = QuarticEase;
  47075. var QuinticEase = /** @class */ (function (_super) {
  47076. __extends(QuinticEase, _super);
  47077. function QuinticEase() {
  47078. return _super !== null && _super.apply(this, arguments) || this;
  47079. }
  47080. QuinticEase.prototype.easeInCore = function (gradient) {
  47081. return (gradient * gradient * gradient * gradient * gradient);
  47082. };
  47083. return QuinticEase;
  47084. }(EasingFunction));
  47085. BABYLON.QuinticEase = QuinticEase;
  47086. var SineEase = /** @class */ (function (_super) {
  47087. __extends(SineEase, _super);
  47088. function SineEase() {
  47089. return _super !== null && _super.apply(this, arguments) || this;
  47090. }
  47091. SineEase.prototype.easeInCore = function (gradient) {
  47092. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  47093. };
  47094. return SineEase;
  47095. }(EasingFunction));
  47096. BABYLON.SineEase = SineEase;
  47097. var BezierCurveEase = /** @class */ (function (_super) {
  47098. __extends(BezierCurveEase, _super);
  47099. function BezierCurveEase(x1, y1, x2, y2) {
  47100. if (x1 === void 0) { x1 = 0; }
  47101. if (y1 === void 0) { y1 = 0; }
  47102. if (x2 === void 0) { x2 = 1; }
  47103. if (y2 === void 0) { y2 = 1; }
  47104. var _this = _super.call(this) || this;
  47105. _this.x1 = x1;
  47106. _this.y1 = y1;
  47107. _this.x2 = x2;
  47108. _this.y2 = y2;
  47109. return _this;
  47110. }
  47111. BezierCurveEase.prototype.easeInCore = function (gradient) {
  47112. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  47113. };
  47114. return BezierCurveEase;
  47115. }(EasingFunction));
  47116. BABYLON.BezierCurveEase = BezierCurveEase;
  47117. })(BABYLON || (BABYLON = {}));
  47118. //# sourceMappingURL=babylon.easing.js.map
  47119. var BABYLON;
  47120. (function (BABYLON) {
  47121. var Condition = /** @class */ (function () {
  47122. function Condition(actionManager) {
  47123. this._actionManager = actionManager;
  47124. }
  47125. Condition.prototype.isValid = function () {
  47126. return true;
  47127. };
  47128. Condition.prototype._getProperty = function (propertyPath) {
  47129. return this._actionManager._getProperty(propertyPath);
  47130. };
  47131. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  47132. return this._actionManager._getEffectiveTarget(target, propertyPath);
  47133. };
  47134. Condition.prototype.serialize = function () {
  47135. };
  47136. Condition.prototype._serialize = function (serializedCondition) {
  47137. return {
  47138. type: 2,
  47139. children: [],
  47140. name: serializedCondition.name,
  47141. properties: serializedCondition.properties
  47142. };
  47143. };
  47144. return Condition;
  47145. }());
  47146. BABYLON.Condition = Condition;
  47147. var ValueCondition = /** @class */ (function (_super) {
  47148. __extends(ValueCondition, _super);
  47149. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  47150. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  47151. var _this = _super.call(this, actionManager) || this;
  47152. _this.propertyPath = propertyPath;
  47153. _this.value = value;
  47154. _this.operator = operator;
  47155. _this._target = target;
  47156. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  47157. _this._property = _this._getProperty(_this.propertyPath);
  47158. return _this;
  47159. }
  47160. Object.defineProperty(ValueCondition, "IsEqual", {
  47161. get: function () {
  47162. return ValueCondition._IsEqual;
  47163. },
  47164. enumerable: true,
  47165. configurable: true
  47166. });
  47167. Object.defineProperty(ValueCondition, "IsDifferent", {
  47168. get: function () {
  47169. return ValueCondition._IsDifferent;
  47170. },
  47171. enumerable: true,
  47172. configurable: true
  47173. });
  47174. Object.defineProperty(ValueCondition, "IsGreater", {
  47175. get: function () {
  47176. return ValueCondition._IsGreater;
  47177. },
  47178. enumerable: true,
  47179. configurable: true
  47180. });
  47181. Object.defineProperty(ValueCondition, "IsLesser", {
  47182. get: function () {
  47183. return ValueCondition._IsLesser;
  47184. },
  47185. enumerable: true,
  47186. configurable: true
  47187. });
  47188. // Methods
  47189. ValueCondition.prototype.isValid = function () {
  47190. switch (this.operator) {
  47191. case ValueCondition.IsGreater:
  47192. return this._effectiveTarget[this._property] > this.value;
  47193. case ValueCondition.IsLesser:
  47194. return this._effectiveTarget[this._property] < this.value;
  47195. case ValueCondition.IsEqual:
  47196. case ValueCondition.IsDifferent:
  47197. var check;
  47198. if (this.value.equals) {
  47199. check = this.value.equals(this._effectiveTarget[this._property]);
  47200. }
  47201. else {
  47202. check = this.value === this._effectiveTarget[this._property];
  47203. }
  47204. return this.operator === ValueCondition.IsEqual ? check : !check;
  47205. }
  47206. return false;
  47207. };
  47208. ValueCondition.prototype.serialize = function () {
  47209. return this._serialize({
  47210. name: "ValueCondition",
  47211. properties: [
  47212. BABYLON.Action._GetTargetProperty(this._target),
  47213. { name: "propertyPath", value: this.propertyPath },
  47214. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  47215. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  47216. ]
  47217. });
  47218. };
  47219. ValueCondition.GetOperatorName = function (operator) {
  47220. switch (operator) {
  47221. case ValueCondition._IsEqual: return "IsEqual";
  47222. case ValueCondition._IsDifferent: return "IsDifferent";
  47223. case ValueCondition._IsGreater: return "IsGreater";
  47224. case ValueCondition._IsLesser: return "IsLesser";
  47225. default: return "";
  47226. }
  47227. };
  47228. // Statics
  47229. ValueCondition._IsEqual = 0;
  47230. ValueCondition._IsDifferent = 1;
  47231. ValueCondition._IsGreater = 2;
  47232. ValueCondition._IsLesser = 3;
  47233. return ValueCondition;
  47234. }(Condition));
  47235. BABYLON.ValueCondition = ValueCondition;
  47236. var PredicateCondition = /** @class */ (function (_super) {
  47237. __extends(PredicateCondition, _super);
  47238. function PredicateCondition(actionManager, predicate) {
  47239. var _this = _super.call(this, actionManager) || this;
  47240. _this.predicate = predicate;
  47241. return _this;
  47242. }
  47243. PredicateCondition.prototype.isValid = function () {
  47244. return this.predicate();
  47245. };
  47246. return PredicateCondition;
  47247. }(Condition));
  47248. BABYLON.PredicateCondition = PredicateCondition;
  47249. var StateCondition = /** @class */ (function (_super) {
  47250. __extends(StateCondition, _super);
  47251. function StateCondition(actionManager, target, value) {
  47252. var _this = _super.call(this, actionManager) || this;
  47253. _this.value = value;
  47254. _this._target = target;
  47255. return _this;
  47256. }
  47257. // Methods
  47258. StateCondition.prototype.isValid = function () {
  47259. return this._target.state === this.value;
  47260. };
  47261. StateCondition.prototype.serialize = function () {
  47262. return this._serialize({
  47263. name: "StateCondition",
  47264. properties: [
  47265. BABYLON.Action._GetTargetProperty(this._target),
  47266. { name: "value", value: this.value }
  47267. ]
  47268. });
  47269. };
  47270. return StateCondition;
  47271. }(Condition));
  47272. BABYLON.StateCondition = StateCondition;
  47273. })(BABYLON || (BABYLON = {}));
  47274. //# sourceMappingURL=babylon.condition.js.map
  47275. var BABYLON;
  47276. (function (BABYLON) {
  47277. var Action = /** @class */ (function () {
  47278. function Action(triggerOptions, condition) {
  47279. this.triggerOptions = triggerOptions;
  47280. this.onBeforeExecuteObservable = new BABYLON.Observable();
  47281. if (triggerOptions.parameter) {
  47282. this.trigger = triggerOptions.trigger;
  47283. this._triggerParameter = triggerOptions.parameter;
  47284. }
  47285. else {
  47286. this.trigger = triggerOptions;
  47287. }
  47288. this._nextActiveAction = this;
  47289. this._condition = condition;
  47290. }
  47291. // Methods
  47292. Action.prototype._prepare = function () {
  47293. };
  47294. Action.prototype.getTriggerParameter = function () {
  47295. return this._triggerParameter;
  47296. };
  47297. Action.prototype._executeCurrent = function (evt) {
  47298. if (this._nextActiveAction._condition) {
  47299. var condition = this._nextActiveAction._condition;
  47300. var currentRenderId = this._actionManager.getScene().getRenderId();
  47301. // We cache the current evaluation for the current frame
  47302. if (condition._evaluationId === currentRenderId) {
  47303. if (!condition._currentResult) {
  47304. return;
  47305. }
  47306. }
  47307. else {
  47308. condition._evaluationId = currentRenderId;
  47309. if (!condition.isValid()) {
  47310. condition._currentResult = false;
  47311. return;
  47312. }
  47313. condition._currentResult = true;
  47314. }
  47315. }
  47316. this.onBeforeExecuteObservable.notifyObservers(this);
  47317. this._nextActiveAction.execute(evt);
  47318. this.skipToNextActiveAction();
  47319. };
  47320. Action.prototype.execute = function (evt) {
  47321. };
  47322. Action.prototype.skipToNextActiveAction = function () {
  47323. if (this._nextActiveAction._child) {
  47324. if (!this._nextActiveAction._child._actionManager) {
  47325. this._nextActiveAction._child._actionManager = this._actionManager;
  47326. }
  47327. this._nextActiveAction = this._nextActiveAction._child;
  47328. }
  47329. else {
  47330. this._nextActiveAction = this;
  47331. }
  47332. };
  47333. Action.prototype.then = function (action) {
  47334. this._child = action;
  47335. action._actionManager = this._actionManager;
  47336. action._prepare();
  47337. return action;
  47338. };
  47339. Action.prototype._getProperty = function (propertyPath) {
  47340. return this._actionManager._getProperty(propertyPath);
  47341. };
  47342. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  47343. return this._actionManager._getEffectiveTarget(target, propertyPath);
  47344. };
  47345. Action.prototype.serialize = function (parent) {
  47346. };
  47347. // Called by BABYLON.Action objects in serialize(...). Internal use
  47348. Action.prototype._serialize = function (serializedAction, parent) {
  47349. var serializationObject = {
  47350. type: 1,
  47351. children: [],
  47352. name: serializedAction.name,
  47353. properties: serializedAction.properties || []
  47354. };
  47355. // Serialize child
  47356. if (this._child) {
  47357. this._child.serialize(serializationObject);
  47358. }
  47359. // Check if "this" has a condition
  47360. if (this._condition) {
  47361. var serializedCondition = this._condition.serialize();
  47362. serializedCondition.children.push(serializationObject);
  47363. if (parent) {
  47364. parent.children.push(serializedCondition);
  47365. }
  47366. return serializedCondition;
  47367. }
  47368. if (parent) {
  47369. parent.children.push(serializationObject);
  47370. }
  47371. return serializationObject;
  47372. };
  47373. Action._SerializeValueAsString = function (value) {
  47374. if (typeof value === "number") {
  47375. return value.toString();
  47376. }
  47377. if (typeof value === "boolean") {
  47378. return value ? "true" : "false";
  47379. }
  47380. if (value instanceof BABYLON.Vector2) {
  47381. return value.x + ", " + value.y;
  47382. }
  47383. if (value instanceof BABYLON.Vector3) {
  47384. return value.x + ", " + value.y + ", " + value.z;
  47385. }
  47386. if (value instanceof BABYLON.Color3) {
  47387. return value.r + ", " + value.g + ", " + value.b;
  47388. }
  47389. if (value instanceof BABYLON.Color4) {
  47390. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  47391. }
  47392. return value; // string
  47393. };
  47394. Action._GetTargetProperty = function (target) {
  47395. return {
  47396. name: "target",
  47397. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  47398. : target instanceof BABYLON.Light ? "LightProperties"
  47399. : target instanceof BABYLON.Camera ? "CameraProperties"
  47400. : "SceneProperties",
  47401. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  47402. };
  47403. };
  47404. return Action;
  47405. }());
  47406. BABYLON.Action = Action;
  47407. })(BABYLON || (BABYLON = {}));
  47408. //# sourceMappingURL=babylon.action.js.map
  47409. var BABYLON;
  47410. (function (BABYLON) {
  47411. /**
  47412. * ActionEvent is the event beint sent when an action is triggered.
  47413. */
  47414. var ActionEvent = /** @class */ (function () {
  47415. /**
  47416. * @param source The mesh or sprite that triggered the action.
  47417. * @param pointerX The X mouse cursor position at the time of the event
  47418. * @param pointerY The Y mouse cursor position at the time of the event
  47419. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  47420. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  47421. */
  47422. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  47423. this.source = source;
  47424. this.pointerX = pointerX;
  47425. this.pointerY = pointerY;
  47426. this.meshUnderPointer = meshUnderPointer;
  47427. this.sourceEvent = sourceEvent;
  47428. this.additionalData = additionalData;
  47429. }
  47430. /**
  47431. * Helper function to auto-create an ActionEvent from a source mesh.
  47432. * @param source The source mesh that triggered the event
  47433. * @param evt {Event} The original (browser) event
  47434. */
  47435. ActionEvent.CreateNew = function (source, evt, additionalData) {
  47436. var scene = source.getScene();
  47437. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  47438. };
  47439. /**
  47440. * Helper function to auto-create an ActionEvent from a source mesh.
  47441. * @param source The source sprite that triggered the event
  47442. * @param scene Scene associated with the sprite
  47443. * @param evt {Event} The original (browser) event
  47444. */
  47445. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  47446. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  47447. };
  47448. /**
  47449. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  47450. * @param scene the scene where the event occurred
  47451. * @param evt {Event} The original (browser) event
  47452. */
  47453. ActionEvent.CreateNewFromScene = function (scene, evt) {
  47454. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  47455. };
  47456. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  47457. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  47458. };
  47459. return ActionEvent;
  47460. }());
  47461. BABYLON.ActionEvent = ActionEvent;
  47462. /**
  47463. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  47464. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  47465. */
  47466. var ActionManager = /** @class */ (function () {
  47467. function ActionManager(scene) {
  47468. // Members
  47469. this.actions = new Array();
  47470. this.hoverCursor = '';
  47471. this._scene = scene;
  47472. scene._actionManagers.push(this);
  47473. }
  47474. Object.defineProperty(ActionManager, "NothingTrigger", {
  47475. get: function () {
  47476. return ActionManager._NothingTrigger;
  47477. },
  47478. enumerable: true,
  47479. configurable: true
  47480. });
  47481. Object.defineProperty(ActionManager, "OnPickTrigger", {
  47482. get: function () {
  47483. return ActionManager._OnPickTrigger;
  47484. },
  47485. enumerable: true,
  47486. configurable: true
  47487. });
  47488. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  47489. get: function () {
  47490. return ActionManager._OnLeftPickTrigger;
  47491. },
  47492. enumerable: true,
  47493. configurable: true
  47494. });
  47495. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  47496. get: function () {
  47497. return ActionManager._OnRightPickTrigger;
  47498. },
  47499. enumerable: true,
  47500. configurable: true
  47501. });
  47502. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  47503. get: function () {
  47504. return ActionManager._OnCenterPickTrigger;
  47505. },
  47506. enumerable: true,
  47507. configurable: true
  47508. });
  47509. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  47510. get: function () {
  47511. return ActionManager._OnPickDownTrigger;
  47512. },
  47513. enumerable: true,
  47514. configurable: true
  47515. });
  47516. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  47517. get: function () {
  47518. return ActionManager._OnDoublePickTrigger;
  47519. },
  47520. enumerable: true,
  47521. configurable: true
  47522. });
  47523. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  47524. get: function () {
  47525. return ActionManager._OnPickUpTrigger;
  47526. },
  47527. enumerable: true,
  47528. configurable: true
  47529. });
  47530. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  47531. /// This trigger will only be raised if you also declared a OnPickDown
  47532. get: function () {
  47533. return ActionManager._OnPickOutTrigger;
  47534. },
  47535. enumerable: true,
  47536. configurable: true
  47537. });
  47538. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  47539. get: function () {
  47540. return ActionManager._OnLongPressTrigger;
  47541. },
  47542. enumerable: true,
  47543. configurable: true
  47544. });
  47545. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  47546. get: function () {
  47547. return ActionManager._OnPointerOverTrigger;
  47548. },
  47549. enumerable: true,
  47550. configurable: true
  47551. });
  47552. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  47553. get: function () {
  47554. return ActionManager._OnPointerOutTrigger;
  47555. },
  47556. enumerable: true,
  47557. configurable: true
  47558. });
  47559. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  47560. get: function () {
  47561. return ActionManager._OnEveryFrameTrigger;
  47562. },
  47563. enumerable: true,
  47564. configurable: true
  47565. });
  47566. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  47567. get: function () {
  47568. return ActionManager._OnIntersectionEnterTrigger;
  47569. },
  47570. enumerable: true,
  47571. configurable: true
  47572. });
  47573. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  47574. get: function () {
  47575. return ActionManager._OnIntersectionExitTrigger;
  47576. },
  47577. enumerable: true,
  47578. configurable: true
  47579. });
  47580. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  47581. get: function () {
  47582. return ActionManager._OnKeyDownTrigger;
  47583. },
  47584. enumerable: true,
  47585. configurable: true
  47586. });
  47587. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  47588. get: function () {
  47589. return ActionManager._OnKeyUpTrigger;
  47590. },
  47591. enumerable: true,
  47592. configurable: true
  47593. });
  47594. // Methods
  47595. ActionManager.prototype.dispose = function () {
  47596. var index = this._scene._actionManagers.indexOf(this);
  47597. for (var i = 0; i < this.actions.length; i++) {
  47598. var action = this.actions[i];
  47599. ActionManager.Triggers[action.trigger]--;
  47600. if (ActionManager.Triggers[action.trigger] === 0) {
  47601. delete ActionManager.Triggers[action.trigger];
  47602. }
  47603. }
  47604. if (index > -1) {
  47605. this._scene._actionManagers.splice(index, 1);
  47606. }
  47607. };
  47608. ActionManager.prototype.getScene = function () {
  47609. return this._scene;
  47610. };
  47611. /**
  47612. * Does this action manager handles actions of any of the given triggers
  47613. * @param {number[]} triggers - the triggers to be tested
  47614. * @return {boolean} whether one (or more) of the triggers is handeled
  47615. */
  47616. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  47617. for (var index = 0; index < this.actions.length; index++) {
  47618. var action = this.actions[index];
  47619. if (triggers.indexOf(action.trigger) > -1) {
  47620. return true;
  47621. }
  47622. }
  47623. return false;
  47624. };
  47625. /**
  47626. * Does this action manager handles actions of a given trigger
  47627. * @param {number} trigger - the trigger to be tested
  47628. * @return {boolean} whether the trigger is handeled
  47629. */
  47630. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  47631. for (var index = 0; index < this.actions.length; index++) {
  47632. var action = this.actions[index];
  47633. if (action.trigger === trigger) {
  47634. return true;
  47635. }
  47636. }
  47637. return false;
  47638. };
  47639. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  47640. /**
  47641. * Does this action manager has pointer triggers
  47642. * @return {boolean} whether or not it has pointer triggers
  47643. */
  47644. get: function () {
  47645. for (var index = 0; index < this.actions.length; index++) {
  47646. var action = this.actions[index];
  47647. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  47648. return true;
  47649. }
  47650. }
  47651. return false;
  47652. },
  47653. enumerable: true,
  47654. configurable: true
  47655. });
  47656. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  47657. /**
  47658. * Does this action manager has pick triggers
  47659. * @return {boolean} whether or not it has pick triggers
  47660. */
  47661. get: function () {
  47662. for (var index = 0; index < this.actions.length; index++) {
  47663. var action = this.actions[index];
  47664. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  47665. return true;
  47666. }
  47667. }
  47668. return false;
  47669. },
  47670. enumerable: true,
  47671. configurable: true
  47672. });
  47673. Object.defineProperty(ActionManager, "HasTriggers", {
  47674. /**
  47675. * Does exist one action manager with at least one trigger
  47676. * @return {boolean} whether or not it exists one action manager with one trigger
  47677. **/
  47678. get: function () {
  47679. for (var t in ActionManager.Triggers) {
  47680. if (ActionManager.Triggers.hasOwnProperty(t)) {
  47681. return true;
  47682. }
  47683. }
  47684. return false;
  47685. },
  47686. enumerable: true,
  47687. configurable: true
  47688. });
  47689. Object.defineProperty(ActionManager, "HasPickTriggers", {
  47690. /**
  47691. * Does exist one action manager with at least one pick trigger
  47692. * @return {boolean} whether or not it exists one action manager with one pick trigger
  47693. **/
  47694. get: function () {
  47695. for (var t in ActionManager.Triggers) {
  47696. if (ActionManager.Triggers.hasOwnProperty(t)) {
  47697. var t_int = parseInt(t);
  47698. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  47699. return true;
  47700. }
  47701. }
  47702. }
  47703. return false;
  47704. },
  47705. enumerable: true,
  47706. configurable: true
  47707. });
  47708. /**
  47709. * Does exist one action manager that handles actions of a given trigger
  47710. * @param {number} trigger - the trigger to be tested
  47711. * @return {boolean} whether the trigger is handeled by at least one action manager
  47712. **/
  47713. ActionManager.HasSpecificTrigger = function (trigger) {
  47714. for (var t in ActionManager.Triggers) {
  47715. if (ActionManager.Triggers.hasOwnProperty(t)) {
  47716. var t_int = parseInt(t);
  47717. if (t_int === trigger) {
  47718. return true;
  47719. }
  47720. }
  47721. }
  47722. return false;
  47723. };
  47724. /**
  47725. * Registers an action to this action manager
  47726. * @param {BABYLON.Action} action - the action to be registered
  47727. * @return {BABYLON.Action} the action amended (prepared) after registration
  47728. */
  47729. ActionManager.prototype.registerAction = function (action) {
  47730. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  47731. if (this.getScene().actionManager !== this) {
  47732. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  47733. return null;
  47734. }
  47735. }
  47736. this.actions.push(action);
  47737. if (ActionManager.Triggers[action.trigger]) {
  47738. ActionManager.Triggers[action.trigger]++;
  47739. }
  47740. else {
  47741. ActionManager.Triggers[action.trigger] = 1;
  47742. }
  47743. action._actionManager = this;
  47744. action._prepare();
  47745. return action;
  47746. };
  47747. /**
  47748. * Unregisters an action to this action manager
  47749. * @param action The action to be unregistered
  47750. * @return whether the action has been unregistered
  47751. */
  47752. ActionManager.prototype.unregisterAction = function (action) {
  47753. var index = this.actions.indexOf(action);
  47754. if (index !== -1) {
  47755. this.actions.splice(index, 1);
  47756. ActionManager.Triggers[action.trigger] -= 1;
  47757. if (ActionManager.Triggers[action.trigger] === 0) {
  47758. delete ActionManager.Triggers[action.trigger];
  47759. }
  47760. delete action._actionManager;
  47761. return true;
  47762. }
  47763. return false;
  47764. };
  47765. /**
  47766. * Process a specific trigger
  47767. * @param {number} trigger - the trigger to process
  47768. * @param evt {BABYLON.ActionEvent} the event details to be processed
  47769. */
  47770. ActionManager.prototype.processTrigger = function (trigger, evt) {
  47771. for (var index = 0; index < this.actions.length; index++) {
  47772. var action = this.actions[index];
  47773. if (action.trigger === trigger) {
  47774. if (evt) {
  47775. if (trigger === ActionManager.OnKeyUpTrigger
  47776. || trigger === ActionManager.OnKeyDownTrigger) {
  47777. var parameter = action.getTriggerParameter();
  47778. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  47779. if (!parameter.toLowerCase) {
  47780. continue;
  47781. }
  47782. var lowerCase = parameter.toLowerCase();
  47783. if (lowerCase !== evt.sourceEvent.key) {
  47784. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  47785. var actualkey = String.fromCharCode(unicode).toLowerCase();
  47786. if (actualkey !== lowerCase) {
  47787. continue;
  47788. }
  47789. }
  47790. }
  47791. }
  47792. }
  47793. action._executeCurrent(evt);
  47794. }
  47795. }
  47796. };
  47797. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  47798. var properties = propertyPath.split(".");
  47799. for (var index = 0; index < properties.length - 1; index++) {
  47800. target = target[properties[index]];
  47801. }
  47802. return target;
  47803. };
  47804. ActionManager.prototype._getProperty = function (propertyPath) {
  47805. var properties = propertyPath.split(".");
  47806. return properties[properties.length - 1];
  47807. };
  47808. ActionManager.prototype.serialize = function (name) {
  47809. var root = {
  47810. children: new Array(),
  47811. name: name,
  47812. type: 3,
  47813. properties: new Array() // Empty for root but required
  47814. };
  47815. for (var i = 0; i < this.actions.length; i++) {
  47816. var triggerObject = {
  47817. type: 0,
  47818. children: new Array(),
  47819. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  47820. properties: new Array()
  47821. };
  47822. var triggerOptions = this.actions[i].triggerOptions;
  47823. if (triggerOptions && typeof triggerOptions !== "number") {
  47824. if (triggerOptions.parameter instanceof BABYLON.Node) {
  47825. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  47826. }
  47827. else {
  47828. var parameter = {};
  47829. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  47830. if (triggerOptions.parameter.mesh) {
  47831. parameter._meshId = triggerOptions.parameter.mesh.id;
  47832. }
  47833. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  47834. }
  47835. }
  47836. // Serialize child action, recursively
  47837. this.actions[i].serialize(triggerObject);
  47838. // Add serialized trigger
  47839. root.children.push(triggerObject);
  47840. }
  47841. return root;
  47842. };
  47843. ActionManager.Parse = function (parsedActions, object, scene) {
  47844. var actionManager = new ActionManager(scene);
  47845. if (object === null)
  47846. scene.actionManager = actionManager;
  47847. else
  47848. object.actionManager = actionManager;
  47849. // instanciate a new object
  47850. var instanciate = function (name, params) {
  47851. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  47852. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  47853. newInstance.constructor.apply(newInstance, params);
  47854. return newInstance;
  47855. };
  47856. var parseParameter = function (name, value, target, propertyPath) {
  47857. if (propertyPath === null) {
  47858. // String, boolean or float
  47859. var floatValue = parseFloat(value);
  47860. if (value === "true" || value === "false")
  47861. return value === "true";
  47862. else
  47863. return isNaN(floatValue) ? value : floatValue;
  47864. }
  47865. var effectiveTarget = propertyPath.split(".");
  47866. var values = value.split(",");
  47867. // Get effective Target
  47868. for (var i = 0; i < effectiveTarget.length; i++) {
  47869. target = target[effectiveTarget[i]];
  47870. }
  47871. // Return appropriate value with its type
  47872. if (typeof (target) === "boolean")
  47873. return values[0] === "true";
  47874. if (typeof (target) === "string")
  47875. return values[0];
  47876. // Parameters with multiple values such as Vector3 etc.
  47877. var split = new Array();
  47878. for (var i = 0; i < values.length; i++)
  47879. split.push(parseFloat(values[i]));
  47880. if (target instanceof BABYLON.Vector3)
  47881. return BABYLON.Vector3.FromArray(split);
  47882. if (target instanceof BABYLON.Vector4)
  47883. return BABYLON.Vector4.FromArray(split);
  47884. if (target instanceof BABYLON.Color3)
  47885. return BABYLON.Color3.FromArray(split);
  47886. if (target instanceof BABYLON.Color4)
  47887. return BABYLON.Color4.FromArray(split);
  47888. return parseFloat(values[0]);
  47889. };
  47890. // traverse graph per trigger
  47891. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  47892. if (combineArray === void 0) { combineArray = null; }
  47893. if (parsedAction.detached)
  47894. return;
  47895. var parameters = new Array();
  47896. var target = null;
  47897. var propertyPath = null;
  47898. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  47899. // Parameters
  47900. if (parsedAction.type === 2)
  47901. parameters.push(actionManager);
  47902. else
  47903. parameters.push(trigger);
  47904. if (combine) {
  47905. var actions = new Array();
  47906. for (var j = 0; j < parsedAction.combine.length; j++) {
  47907. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  47908. }
  47909. parameters.push(actions);
  47910. }
  47911. else {
  47912. for (var i = 0; i < parsedAction.properties.length; i++) {
  47913. var value = parsedAction.properties[i].value;
  47914. var name = parsedAction.properties[i].name;
  47915. var targetType = parsedAction.properties[i].targetType;
  47916. if (name === "target")
  47917. if (targetType !== null && targetType === "SceneProperties")
  47918. value = target = scene;
  47919. else
  47920. value = target = scene.getNodeByName(value);
  47921. else if (name === "parent")
  47922. value = scene.getNodeByName(value);
  47923. else if (name === "sound")
  47924. value = scene.getSoundByName(value);
  47925. else if (name !== "propertyPath") {
  47926. if (parsedAction.type === 2 && name === "operator")
  47927. value = BABYLON.ValueCondition[value];
  47928. else
  47929. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  47930. }
  47931. else {
  47932. propertyPath = value;
  47933. }
  47934. parameters.push(value);
  47935. }
  47936. }
  47937. if (combineArray === null) {
  47938. parameters.push(condition);
  47939. }
  47940. else {
  47941. parameters.push(null);
  47942. }
  47943. // If interpolate value action
  47944. if (parsedAction.name === "InterpolateValueAction") {
  47945. var param = parameters[parameters.length - 2];
  47946. parameters[parameters.length - 1] = param;
  47947. parameters[parameters.length - 2] = condition;
  47948. }
  47949. // Action or condition(s) and not CombineAction
  47950. var newAction = instanciate(parsedAction.name, parameters);
  47951. if (newAction instanceof BABYLON.Condition && condition !== null) {
  47952. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  47953. if (action)
  47954. action.then(nothing);
  47955. else
  47956. actionManager.registerAction(nothing);
  47957. action = nothing;
  47958. }
  47959. if (combineArray === null) {
  47960. if (newAction instanceof BABYLON.Condition) {
  47961. condition = newAction;
  47962. newAction = action;
  47963. }
  47964. else {
  47965. condition = null;
  47966. if (action)
  47967. action.then(newAction);
  47968. else
  47969. actionManager.registerAction(newAction);
  47970. }
  47971. }
  47972. else {
  47973. combineArray.push(newAction);
  47974. }
  47975. for (var i = 0; i < parsedAction.children.length; i++)
  47976. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  47977. };
  47978. // triggers
  47979. for (var i = 0; i < parsedActions.children.length; i++) {
  47980. var triggerParams;
  47981. var trigger = parsedActions.children[i];
  47982. if (trigger.properties.length > 0) {
  47983. var param = trigger.properties[0].value;
  47984. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  47985. if (value._meshId) {
  47986. value.mesh = scene.getMeshByID(value._meshId);
  47987. }
  47988. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  47989. }
  47990. else
  47991. triggerParams = ActionManager[trigger.name];
  47992. for (var j = 0; j < trigger.children.length; j++) {
  47993. if (!trigger.detached)
  47994. traverse(trigger.children[j], triggerParams, null, null);
  47995. }
  47996. }
  47997. };
  47998. ActionManager.GetTriggerName = function (trigger) {
  47999. switch (trigger) {
  48000. case 0: return "NothingTrigger";
  48001. case 1: return "OnPickTrigger";
  48002. case 2: return "OnLeftPickTrigger";
  48003. case 3: return "OnRightPickTrigger";
  48004. case 4: return "OnCenterPickTrigger";
  48005. case 5: return "OnPickDownTrigger";
  48006. case 6: return "OnPickUpTrigger";
  48007. case 7: return "OnLongPressTrigger";
  48008. case 8: return "OnPointerOverTrigger";
  48009. case 9: return "OnPointerOutTrigger";
  48010. case 10: return "OnEveryFrameTrigger";
  48011. case 11: return "OnIntersectionEnterTrigger";
  48012. case 12: return "OnIntersectionExitTrigger";
  48013. case 13: return "OnKeyDownTrigger";
  48014. case 14: return "OnKeyUpTrigger";
  48015. case 15: return "OnPickOutTrigger";
  48016. default: return "";
  48017. }
  48018. };
  48019. // Statics
  48020. ActionManager._NothingTrigger = 0;
  48021. ActionManager._OnPickTrigger = 1;
  48022. ActionManager._OnLeftPickTrigger = 2;
  48023. ActionManager._OnRightPickTrigger = 3;
  48024. ActionManager._OnCenterPickTrigger = 4;
  48025. ActionManager._OnPickDownTrigger = 5;
  48026. ActionManager._OnDoublePickTrigger = 6;
  48027. ActionManager._OnPickUpTrigger = 7;
  48028. ActionManager._OnLongPressTrigger = 8;
  48029. ActionManager._OnPointerOverTrigger = 9;
  48030. ActionManager._OnPointerOutTrigger = 10;
  48031. ActionManager._OnEveryFrameTrigger = 11;
  48032. ActionManager._OnIntersectionEnterTrigger = 12;
  48033. ActionManager._OnIntersectionExitTrigger = 13;
  48034. ActionManager._OnKeyDownTrigger = 14;
  48035. ActionManager._OnKeyUpTrigger = 15;
  48036. ActionManager._OnPickOutTrigger = 16;
  48037. ActionManager.Triggers = {};
  48038. return ActionManager;
  48039. }());
  48040. BABYLON.ActionManager = ActionManager;
  48041. })(BABYLON || (BABYLON = {}));
  48042. //# sourceMappingURL=babylon.actionManager.js.map
  48043. var BABYLON;
  48044. (function (BABYLON) {
  48045. var InterpolateValueAction = /** @class */ (function (_super) {
  48046. __extends(InterpolateValueAction, _super);
  48047. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  48048. if (duration === void 0) { duration = 1000; }
  48049. var _this = _super.call(this, triggerOptions, condition) || this;
  48050. _this.propertyPath = propertyPath;
  48051. _this.value = value;
  48052. _this.duration = duration;
  48053. _this.stopOtherAnimations = stopOtherAnimations;
  48054. _this.onInterpolationDone = onInterpolationDone;
  48055. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  48056. _this._target = _this._effectiveTarget = target;
  48057. return _this;
  48058. }
  48059. InterpolateValueAction.prototype._prepare = function () {
  48060. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  48061. this._property = this._getProperty(this.propertyPath);
  48062. };
  48063. InterpolateValueAction.prototype.execute = function () {
  48064. var _this = this;
  48065. var scene = this._actionManager.getScene();
  48066. var keys = [
  48067. {
  48068. frame: 0,
  48069. value: this._effectiveTarget[this._property]
  48070. }, {
  48071. frame: 100,
  48072. value: this.value
  48073. }
  48074. ];
  48075. var dataType;
  48076. if (typeof this.value === "number") {
  48077. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  48078. }
  48079. else if (this.value instanceof BABYLON.Color3) {
  48080. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  48081. }
  48082. else if (this.value instanceof BABYLON.Vector3) {
  48083. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  48084. }
  48085. else if (this.value instanceof BABYLON.Matrix) {
  48086. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  48087. }
  48088. else if (this.value instanceof BABYLON.Quaternion) {
  48089. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  48090. }
  48091. else {
  48092. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  48093. return;
  48094. }
  48095. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  48096. animation.setKeys(keys);
  48097. if (this.stopOtherAnimations) {
  48098. scene.stopAnimation(this._effectiveTarget);
  48099. }
  48100. var wrapper = function () {
  48101. _this.onInterpolationDoneObservable.notifyObservers(_this);
  48102. if (_this.onInterpolationDone) {
  48103. _this.onInterpolationDone();
  48104. }
  48105. };
  48106. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  48107. };
  48108. InterpolateValueAction.prototype.serialize = function (parent) {
  48109. return _super.prototype._serialize.call(this, {
  48110. name: "InterpolateValueAction",
  48111. properties: [
  48112. BABYLON.Action._GetTargetProperty(this._target),
  48113. { name: "propertyPath", value: this.propertyPath },
  48114. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  48115. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  48116. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  48117. ]
  48118. }, parent);
  48119. };
  48120. return InterpolateValueAction;
  48121. }(BABYLON.Action));
  48122. BABYLON.InterpolateValueAction = InterpolateValueAction;
  48123. })(BABYLON || (BABYLON = {}));
  48124. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  48125. var BABYLON;
  48126. (function (BABYLON) {
  48127. var SwitchBooleanAction = /** @class */ (function (_super) {
  48128. __extends(SwitchBooleanAction, _super);
  48129. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  48130. var _this = _super.call(this, triggerOptions, condition) || this;
  48131. _this.propertyPath = propertyPath;
  48132. _this._target = _this._effectiveTarget = target;
  48133. return _this;
  48134. }
  48135. SwitchBooleanAction.prototype._prepare = function () {
  48136. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  48137. this._property = this._getProperty(this.propertyPath);
  48138. };
  48139. SwitchBooleanAction.prototype.execute = function () {
  48140. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  48141. };
  48142. SwitchBooleanAction.prototype.serialize = function (parent) {
  48143. return _super.prototype._serialize.call(this, {
  48144. name: "SwitchBooleanAction",
  48145. properties: [
  48146. BABYLON.Action._GetTargetProperty(this._target),
  48147. { name: "propertyPath", value: this.propertyPath }
  48148. ]
  48149. }, parent);
  48150. };
  48151. return SwitchBooleanAction;
  48152. }(BABYLON.Action));
  48153. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  48154. var SetStateAction = /** @class */ (function (_super) {
  48155. __extends(SetStateAction, _super);
  48156. function SetStateAction(triggerOptions, target, value, condition) {
  48157. var _this = _super.call(this, triggerOptions, condition) || this;
  48158. _this.value = value;
  48159. _this._target = target;
  48160. return _this;
  48161. }
  48162. SetStateAction.prototype.execute = function () {
  48163. this._target.state = this.value;
  48164. };
  48165. SetStateAction.prototype.serialize = function (parent) {
  48166. return _super.prototype._serialize.call(this, {
  48167. name: "SetStateAction",
  48168. properties: [
  48169. BABYLON.Action._GetTargetProperty(this._target),
  48170. { name: "value", value: this.value }
  48171. ]
  48172. }, parent);
  48173. };
  48174. return SetStateAction;
  48175. }(BABYLON.Action));
  48176. BABYLON.SetStateAction = SetStateAction;
  48177. var SetValueAction = /** @class */ (function (_super) {
  48178. __extends(SetValueAction, _super);
  48179. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  48180. var _this = _super.call(this, triggerOptions, condition) || this;
  48181. _this.propertyPath = propertyPath;
  48182. _this.value = value;
  48183. _this._target = _this._effectiveTarget = target;
  48184. return _this;
  48185. }
  48186. SetValueAction.prototype._prepare = function () {
  48187. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  48188. this._property = this._getProperty(this.propertyPath);
  48189. };
  48190. SetValueAction.prototype.execute = function () {
  48191. this._effectiveTarget[this._property] = this.value;
  48192. if (this._target.markAsDirty) {
  48193. this._target.markAsDirty(this._property);
  48194. }
  48195. };
  48196. SetValueAction.prototype.serialize = function (parent) {
  48197. return _super.prototype._serialize.call(this, {
  48198. name: "SetValueAction",
  48199. properties: [
  48200. BABYLON.Action._GetTargetProperty(this._target),
  48201. { name: "propertyPath", value: this.propertyPath },
  48202. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  48203. ]
  48204. }, parent);
  48205. };
  48206. return SetValueAction;
  48207. }(BABYLON.Action));
  48208. BABYLON.SetValueAction = SetValueAction;
  48209. var IncrementValueAction = /** @class */ (function (_super) {
  48210. __extends(IncrementValueAction, _super);
  48211. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  48212. var _this = _super.call(this, triggerOptions, condition) || this;
  48213. _this.propertyPath = propertyPath;
  48214. _this.value = value;
  48215. _this._target = _this._effectiveTarget = target;
  48216. return _this;
  48217. }
  48218. IncrementValueAction.prototype._prepare = function () {
  48219. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  48220. this._property = this._getProperty(this.propertyPath);
  48221. if (typeof this._effectiveTarget[this._property] !== "number") {
  48222. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  48223. }
  48224. };
  48225. IncrementValueAction.prototype.execute = function () {
  48226. this._effectiveTarget[this._property] += this.value;
  48227. if (this._target.markAsDirty) {
  48228. this._target.markAsDirty(this._property);
  48229. }
  48230. };
  48231. IncrementValueAction.prototype.serialize = function (parent) {
  48232. return _super.prototype._serialize.call(this, {
  48233. name: "IncrementValueAction",
  48234. properties: [
  48235. BABYLON.Action._GetTargetProperty(this._target),
  48236. { name: "propertyPath", value: this.propertyPath },
  48237. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  48238. ]
  48239. }, parent);
  48240. };
  48241. return IncrementValueAction;
  48242. }(BABYLON.Action));
  48243. BABYLON.IncrementValueAction = IncrementValueAction;
  48244. var PlayAnimationAction = /** @class */ (function (_super) {
  48245. __extends(PlayAnimationAction, _super);
  48246. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  48247. var _this = _super.call(this, triggerOptions, condition) || this;
  48248. _this.from = from;
  48249. _this.to = to;
  48250. _this.loop = loop;
  48251. _this._target = target;
  48252. return _this;
  48253. }
  48254. PlayAnimationAction.prototype._prepare = function () {
  48255. };
  48256. PlayAnimationAction.prototype.execute = function () {
  48257. var scene = this._actionManager.getScene();
  48258. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  48259. };
  48260. PlayAnimationAction.prototype.serialize = function (parent) {
  48261. return _super.prototype._serialize.call(this, {
  48262. name: "PlayAnimationAction",
  48263. properties: [
  48264. BABYLON.Action._GetTargetProperty(this._target),
  48265. { name: "from", value: String(this.from) },
  48266. { name: "to", value: String(this.to) },
  48267. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  48268. ]
  48269. }, parent);
  48270. };
  48271. return PlayAnimationAction;
  48272. }(BABYLON.Action));
  48273. BABYLON.PlayAnimationAction = PlayAnimationAction;
  48274. var StopAnimationAction = /** @class */ (function (_super) {
  48275. __extends(StopAnimationAction, _super);
  48276. function StopAnimationAction(triggerOptions, target, condition) {
  48277. var _this = _super.call(this, triggerOptions, condition) || this;
  48278. _this._target = target;
  48279. return _this;
  48280. }
  48281. StopAnimationAction.prototype._prepare = function () {
  48282. };
  48283. StopAnimationAction.prototype.execute = function () {
  48284. var scene = this._actionManager.getScene();
  48285. scene.stopAnimation(this._target);
  48286. };
  48287. StopAnimationAction.prototype.serialize = function (parent) {
  48288. return _super.prototype._serialize.call(this, {
  48289. name: "StopAnimationAction",
  48290. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  48291. }, parent);
  48292. };
  48293. return StopAnimationAction;
  48294. }(BABYLON.Action));
  48295. BABYLON.StopAnimationAction = StopAnimationAction;
  48296. var DoNothingAction = /** @class */ (function (_super) {
  48297. __extends(DoNothingAction, _super);
  48298. function DoNothingAction(triggerOptions, condition) {
  48299. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  48300. return _super.call(this, triggerOptions, condition) || this;
  48301. }
  48302. DoNothingAction.prototype.execute = function () {
  48303. };
  48304. DoNothingAction.prototype.serialize = function (parent) {
  48305. return _super.prototype._serialize.call(this, {
  48306. name: "DoNothingAction",
  48307. properties: []
  48308. }, parent);
  48309. };
  48310. return DoNothingAction;
  48311. }(BABYLON.Action));
  48312. BABYLON.DoNothingAction = DoNothingAction;
  48313. var CombineAction = /** @class */ (function (_super) {
  48314. __extends(CombineAction, _super);
  48315. function CombineAction(triggerOptions, children, condition) {
  48316. var _this = _super.call(this, triggerOptions, condition) || this;
  48317. _this.children = children;
  48318. return _this;
  48319. }
  48320. CombineAction.prototype._prepare = function () {
  48321. for (var index = 0; index < this.children.length; index++) {
  48322. this.children[index]._actionManager = this._actionManager;
  48323. this.children[index]._prepare();
  48324. }
  48325. };
  48326. CombineAction.prototype.execute = function (evt) {
  48327. for (var index = 0; index < this.children.length; index++) {
  48328. this.children[index].execute(evt);
  48329. }
  48330. };
  48331. CombineAction.prototype.serialize = function (parent) {
  48332. var serializationObject = _super.prototype._serialize.call(this, {
  48333. name: "CombineAction",
  48334. properties: [],
  48335. combine: []
  48336. }, parent);
  48337. for (var i = 0; i < this.children.length; i++) {
  48338. serializationObject.combine.push(this.children[i].serialize(null));
  48339. }
  48340. return serializationObject;
  48341. };
  48342. return CombineAction;
  48343. }(BABYLON.Action));
  48344. BABYLON.CombineAction = CombineAction;
  48345. var ExecuteCodeAction = /** @class */ (function (_super) {
  48346. __extends(ExecuteCodeAction, _super);
  48347. function ExecuteCodeAction(triggerOptions, func, condition) {
  48348. var _this = _super.call(this, triggerOptions, condition) || this;
  48349. _this.func = func;
  48350. return _this;
  48351. }
  48352. ExecuteCodeAction.prototype.execute = function (evt) {
  48353. this.func(evt);
  48354. };
  48355. return ExecuteCodeAction;
  48356. }(BABYLON.Action));
  48357. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  48358. var SetParentAction = /** @class */ (function (_super) {
  48359. __extends(SetParentAction, _super);
  48360. function SetParentAction(triggerOptions, target, parent, condition) {
  48361. var _this = _super.call(this, triggerOptions, condition) || this;
  48362. _this._target = target;
  48363. _this._parent = parent;
  48364. return _this;
  48365. }
  48366. SetParentAction.prototype._prepare = function () {
  48367. };
  48368. SetParentAction.prototype.execute = function () {
  48369. if (this._target.parent === this._parent) {
  48370. return;
  48371. }
  48372. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  48373. invertParentWorldMatrix.invert();
  48374. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  48375. this._target.parent = this._parent;
  48376. };
  48377. SetParentAction.prototype.serialize = function (parent) {
  48378. return _super.prototype._serialize.call(this, {
  48379. name: "SetParentAction",
  48380. properties: [
  48381. BABYLON.Action._GetTargetProperty(this._target),
  48382. BABYLON.Action._GetTargetProperty(this._parent),
  48383. ]
  48384. }, parent);
  48385. };
  48386. return SetParentAction;
  48387. }(BABYLON.Action));
  48388. BABYLON.SetParentAction = SetParentAction;
  48389. var PlaySoundAction = /** @class */ (function (_super) {
  48390. __extends(PlaySoundAction, _super);
  48391. function PlaySoundAction(triggerOptions, sound, condition) {
  48392. var _this = _super.call(this, triggerOptions, condition) || this;
  48393. _this._sound = sound;
  48394. return _this;
  48395. }
  48396. PlaySoundAction.prototype._prepare = function () {
  48397. };
  48398. PlaySoundAction.prototype.execute = function () {
  48399. if (this._sound !== undefined)
  48400. this._sound.play();
  48401. };
  48402. PlaySoundAction.prototype.serialize = function (parent) {
  48403. return _super.prototype._serialize.call(this, {
  48404. name: "PlaySoundAction",
  48405. properties: [{ name: "sound", value: this._sound.name }]
  48406. }, parent);
  48407. };
  48408. return PlaySoundAction;
  48409. }(BABYLON.Action));
  48410. BABYLON.PlaySoundAction = PlaySoundAction;
  48411. var StopSoundAction = /** @class */ (function (_super) {
  48412. __extends(StopSoundAction, _super);
  48413. function StopSoundAction(triggerOptions, sound, condition) {
  48414. var _this = _super.call(this, triggerOptions, condition) || this;
  48415. _this._sound = sound;
  48416. return _this;
  48417. }
  48418. StopSoundAction.prototype._prepare = function () {
  48419. };
  48420. StopSoundAction.prototype.execute = function () {
  48421. if (this._sound !== undefined)
  48422. this._sound.stop();
  48423. };
  48424. StopSoundAction.prototype.serialize = function (parent) {
  48425. return _super.prototype._serialize.call(this, {
  48426. name: "StopSoundAction",
  48427. properties: [{ name: "sound", value: this._sound.name }]
  48428. }, parent);
  48429. };
  48430. return StopSoundAction;
  48431. }(BABYLON.Action));
  48432. BABYLON.StopSoundAction = StopSoundAction;
  48433. })(BABYLON || (BABYLON = {}));
  48434. //# sourceMappingURL=babylon.directActions.js.map
  48435. var BABYLON;
  48436. (function (BABYLON) {
  48437. var SpriteManager = /** @class */ (function () {
  48438. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  48439. if (epsilon === void 0) { epsilon = 0.01; }
  48440. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  48441. this.name = name;
  48442. this.sprites = new Array();
  48443. this.renderingGroupId = 0;
  48444. this.layerMask = 0x0FFFFFFF;
  48445. this.fogEnabled = true;
  48446. this.isPickable = false;
  48447. /**
  48448. * An event triggered when the manager is disposed.
  48449. * @type {BABYLON.Observable}
  48450. */
  48451. this.onDisposeObservable = new BABYLON.Observable();
  48452. this._vertexBuffers = {};
  48453. this._capacity = capacity;
  48454. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  48455. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  48456. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  48457. if (cellSize.width && cellSize.height) {
  48458. this.cellWidth = cellSize.width;
  48459. this.cellHeight = cellSize.height;
  48460. }
  48461. else if (cellSize !== undefined) {
  48462. this.cellWidth = cellSize;
  48463. this.cellHeight = cellSize;
  48464. }
  48465. else {
  48466. return;
  48467. }
  48468. this._epsilon = epsilon;
  48469. this._scene = scene;
  48470. this._scene.spriteManagers.push(this);
  48471. var indices = [];
  48472. var index = 0;
  48473. for (var count = 0; count < capacity; count++) {
  48474. indices.push(index);
  48475. indices.push(index + 1);
  48476. indices.push(index + 2);
  48477. indices.push(index);
  48478. indices.push(index + 2);
  48479. indices.push(index + 3);
  48480. index += 4;
  48481. }
  48482. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  48483. // VBO
  48484. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  48485. this._vertexData = new Float32Array(capacity * 16 * 4);
  48486. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  48487. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  48488. var options = this._buffer.createVertexBuffer("options", 4, 4);
  48489. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  48490. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  48491. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  48492. this._vertexBuffers["options"] = options;
  48493. this._vertexBuffers["cellInfo"] = cellInfo;
  48494. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  48495. // Effects
  48496. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  48497. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  48498. }
  48499. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  48500. set: function (callback) {
  48501. if (this._onDisposeObserver) {
  48502. this.onDisposeObservable.remove(this._onDisposeObserver);
  48503. }
  48504. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  48505. },
  48506. enumerable: true,
  48507. configurable: true
  48508. });
  48509. Object.defineProperty(SpriteManager.prototype, "texture", {
  48510. get: function () {
  48511. return this._spriteTexture;
  48512. },
  48513. set: function (value) {
  48514. this._spriteTexture = value;
  48515. },
  48516. enumerable: true,
  48517. configurable: true
  48518. });
  48519. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  48520. var arrayOffset = index * 16;
  48521. if (offsetX === 0)
  48522. offsetX = this._epsilon;
  48523. else if (offsetX === 1)
  48524. offsetX = 1 - this._epsilon;
  48525. if (offsetY === 0)
  48526. offsetY = this._epsilon;
  48527. else if (offsetY === 1)
  48528. offsetY = 1 - this._epsilon;
  48529. this._vertexData[arrayOffset] = sprite.position.x;
  48530. this._vertexData[arrayOffset + 1] = sprite.position.y;
  48531. this._vertexData[arrayOffset + 2] = sprite.position.z;
  48532. this._vertexData[arrayOffset + 3] = sprite.angle;
  48533. this._vertexData[arrayOffset + 4] = sprite.width;
  48534. this._vertexData[arrayOffset + 5] = sprite.height;
  48535. this._vertexData[arrayOffset + 6] = offsetX;
  48536. this._vertexData[arrayOffset + 7] = offsetY;
  48537. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  48538. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  48539. var offset = (sprite.cellIndex / rowSize) >> 0;
  48540. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  48541. this._vertexData[arrayOffset + 11] = offset;
  48542. // Color
  48543. this._vertexData[arrayOffset + 12] = sprite.color.r;
  48544. this._vertexData[arrayOffset + 13] = sprite.color.g;
  48545. this._vertexData[arrayOffset + 14] = sprite.color.b;
  48546. this._vertexData[arrayOffset + 15] = sprite.color.a;
  48547. };
  48548. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  48549. var count = Math.min(this._capacity, this.sprites.length);
  48550. var min = BABYLON.Vector3.Zero();
  48551. var max = BABYLON.Vector3.Zero();
  48552. var distance = Number.MAX_VALUE;
  48553. var currentSprite = null;
  48554. var cameraSpacePosition = BABYLON.Vector3.Zero();
  48555. var cameraView = camera.getViewMatrix();
  48556. for (var index = 0; index < count; index++) {
  48557. var sprite = this.sprites[index];
  48558. if (!sprite) {
  48559. continue;
  48560. }
  48561. if (predicate) {
  48562. if (!predicate(sprite)) {
  48563. continue;
  48564. }
  48565. }
  48566. else if (!sprite.isPickable) {
  48567. continue;
  48568. }
  48569. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  48570. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  48571. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  48572. if (ray.intersectsBoxMinMax(min, max)) {
  48573. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  48574. if (distance > currentDistance) {
  48575. distance = currentDistance;
  48576. currentSprite = sprite;
  48577. if (fastCheck) {
  48578. break;
  48579. }
  48580. }
  48581. }
  48582. }
  48583. if (currentSprite) {
  48584. var result = new BABYLON.PickingInfo();
  48585. result.hit = true;
  48586. result.pickedSprite = currentSprite;
  48587. result.distance = distance;
  48588. return result;
  48589. }
  48590. return null;
  48591. };
  48592. SpriteManager.prototype.render = function () {
  48593. // Check
  48594. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  48595. return;
  48596. var engine = this._scene.getEngine();
  48597. var baseSize = this._spriteTexture.getBaseSize();
  48598. // Sprites
  48599. var deltaTime = engine.getDeltaTime();
  48600. var max = Math.min(this._capacity, this.sprites.length);
  48601. var rowSize = baseSize.width / this.cellWidth;
  48602. var offset = 0;
  48603. for (var index = 0; index < max; index++) {
  48604. var sprite = this.sprites[index];
  48605. if (!sprite) {
  48606. continue;
  48607. }
  48608. sprite._animate(deltaTime);
  48609. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  48610. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  48611. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  48612. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  48613. }
  48614. this._buffer.update(this._vertexData);
  48615. // Render
  48616. var effect = this._effectBase;
  48617. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  48618. effect = this._effectFog;
  48619. }
  48620. engine.enableEffect(effect);
  48621. var viewMatrix = this._scene.getViewMatrix();
  48622. effect.setTexture("diffuseSampler", this._spriteTexture);
  48623. effect.setMatrix("view", viewMatrix);
  48624. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  48625. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  48626. // Fog
  48627. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  48628. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  48629. effect.setColor3("vFogColor", this._scene.fogColor);
  48630. }
  48631. // VBOs
  48632. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  48633. // Draw order
  48634. engine.setDepthFunctionToLessOrEqual();
  48635. effect.setBool("alphaTest", true);
  48636. engine.setColorWrite(false);
  48637. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  48638. engine.setColorWrite(true);
  48639. effect.setBool("alphaTest", false);
  48640. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  48641. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  48642. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  48643. };
  48644. SpriteManager.prototype.dispose = function () {
  48645. if (this._buffer) {
  48646. this._buffer.dispose();
  48647. this._buffer = null;
  48648. }
  48649. if (this._indexBuffer) {
  48650. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  48651. this._indexBuffer = null;
  48652. }
  48653. if (this._spriteTexture) {
  48654. this._spriteTexture.dispose();
  48655. this._spriteTexture = null;
  48656. }
  48657. // Remove from scene
  48658. var index = this._scene.spriteManagers.indexOf(this);
  48659. this._scene.spriteManagers.splice(index, 1);
  48660. // Callback
  48661. this.onDisposeObservable.notifyObservers(this);
  48662. this.onDisposeObservable.clear();
  48663. };
  48664. return SpriteManager;
  48665. }());
  48666. BABYLON.SpriteManager = SpriteManager;
  48667. })(BABYLON || (BABYLON = {}));
  48668. //# sourceMappingURL=babylon.spriteManager.js.map
  48669. var BABYLON;
  48670. (function (BABYLON) {
  48671. var Sprite = /** @class */ (function () {
  48672. function Sprite(name, manager) {
  48673. this.name = name;
  48674. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  48675. this.width = 1.0;
  48676. this.height = 1.0;
  48677. this.angle = 0;
  48678. this.cellIndex = 0;
  48679. this.invertU = 0;
  48680. this.invertV = 0;
  48681. this.animations = new Array();
  48682. this.isPickable = false;
  48683. this._animationStarted = false;
  48684. this._loopAnimation = false;
  48685. this._fromIndex = 0;
  48686. this._toIndex = 0;
  48687. this._delay = 0;
  48688. this._direction = 1;
  48689. this._time = 0;
  48690. this._manager = manager;
  48691. this._manager.sprites.push(this);
  48692. this.position = BABYLON.Vector3.Zero();
  48693. }
  48694. Object.defineProperty(Sprite.prototype, "size", {
  48695. get: function () {
  48696. return this.width;
  48697. },
  48698. set: function (value) {
  48699. this.width = value;
  48700. this.height = value;
  48701. },
  48702. enumerable: true,
  48703. configurable: true
  48704. });
  48705. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  48706. this._fromIndex = from;
  48707. this._toIndex = to;
  48708. this._loopAnimation = loop;
  48709. this._delay = delay;
  48710. this._animationStarted = true;
  48711. this._direction = from < to ? 1 : -1;
  48712. this.cellIndex = from;
  48713. this._time = 0;
  48714. this._onAnimationEnd = onAnimationEnd;
  48715. };
  48716. Sprite.prototype.stopAnimation = function () {
  48717. this._animationStarted = false;
  48718. };
  48719. Sprite.prototype._animate = function (deltaTime) {
  48720. if (!this._animationStarted)
  48721. return;
  48722. this._time += deltaTime;
  48723. if (this._time > this._delay) {
  48724. this._time = this._time % this._delay;
  48725. this.cellIndex += this._direction;
  48726. if (this.cellIndex > this._toIndex) {
  48727. if (this._loopAnimation) {
  48728. this.cellIndex = this._fromIndex;
  48729. }
  48730. else {
  48731. this.cellIndex = this._toIndex;
  48732. this._animationStarted = false;
  48733. if (this._onAnimationEnd) {
  48734. this._onAnimationEnd();
  48735. }
  48736. if (this.disposeWhenFinishedAnimating) {
  48737. this.dispose();
  48738. }
  48739. }
  48740. }
  48741. }
  48742. };
  48743. Sprite.prototype.dispose = function () {
  48744. for (var i = 0; i < this._manager.sprites.length; i++) {
  48745. if (this._manager.sprites[i] == this) {
  48746. this._manager.sprites.splice(i, 1);
  48747. }
  48748. }
  48749. };
  48750. return Sprite;
  48751. }());
  48752. BABYLON.Sprite = Sprite;
  48753. })(BABYLON || (BABYLON = {}));
  48754. //# sourceMappingURL=babylon.sprite.js.map
  48755. var BABYLON;
  48756. (function (BABYLON) {
  48757. var IntersectionInfo = /** @class */ (function () {
  48758. function IntersectionInfo(bu, bv, distance) {
  48759. this.bu = bu;
  48760. this.bv = bv;
  48761. this.distance = distance;
  48762. this.faceId = 0;
  48763. this.subMeshId = 0;
  48764. }
  48765. return IntersectionInfo;
  48766. }());
  48767. BABYLON.IntersectionInfo = IntersectionInfo;
  48768. var PickingInfo = /** @class */ (function () {
  48769. function PickingInfo() {
  48770. this.hit = false;
  48771. this.distance = 0;
  48772. this.pickedPoint = null;
  48773. this.pickedMesh = null;
  48774. this.bu = 0;
  48775. this.bv = 0;
  48776. this.faceId = -1;
  48777. this.subMeshId = 0;
  48778. this.pickedSprite = null;
  48779. }
  48780. // Methods
  48781. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  48782. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  48783. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  48784. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  48785. return null;
  48786. }
  48787. var indices = this.pickedMesh.getIndices();
  48788. if (!indices) {
  48789. return null;
  48790. }
  48791. var result;
  48792. if (useVerticesNormals) {
  48793. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  48794. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  48795. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  48796. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  48797. normal0 = normal0.scale(this.bu);
  48798. normal1 = normal1.scale(this.bv);
  48799. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  48800. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  48801. }
  48802. else {
  48803. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  48804. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  48805. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  48806. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  48807. var p1p2 = vertex1.subtract(vertex2);
  48808. var p3p2 = vertex3.subtract(vertex2);
  48809. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  48810. }
  48811. if (useWorldCoordinates) {
  48812. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  48813. }
  48814. return BABYLON.Vector3.Normalize(result);
  48815. };
  48816. PickingInfo.prototype.getTextureCoordinates = function () {
  48817. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  48818. return null;
  48819. }
  48820. var indices = this.pickedMesh.getIndices();
  48821. if (!indices) {
  48822. return null;
  48823. }
  48824. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  48825. if (!uvs) {
  48826. return null;
  48827. }
  48828. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  48829. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  48830. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  48831. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  48832. uv1 = uv1.scale(this.bu);
  48833. uv2 = uv2.scale(this.bv);
  48834. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  48835. };
  48836. return PickingInfo;
  48837. }());
  48838. BABYLON.PickingInfo = PickingInfo;
  48839. })(BABYLON || (BABYLON = {}));
  48840. //# sourceMappingURL=babylon.pickingInfo.js.map
  48841. var BABYLON;
  48842. (function (BABYLON) {
  48843. var Ray = /** @class */ (function () {
  48844. function Ray(origin, direction, length) {
  48845. if (length === void 0) { length = Number.MAX_VALUE; }
  48846. this.origin = origin;
  48847. this.direction = direction;
  48848. this.length = length;
  48849. }
  48850. // Methods
  48851. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  48852. var d = 0.0;
  48853. var maxValue = Number.MAX_VALUE;
  48854. var inv;
  48855. var min;
  48856. var max;
  48857. var temp;
  48858. if (Math.abs(this.direction.x) < 0.0000001) {
  48859. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  48860. return false;
  48861. }
  48862. }
  48863. else {
  48864. inv = 1.0 / this.direction.x;
  48865. min = (minimum.x - this.origin.x) * inv;
  48866. max = (maximum.x - this.origin.x) * inv;
  48867. if (max === -Infinity) {
  48868. max = Infinity;
  48869. }
  48870. if (min > max) {
  48871. temp = min;
  48872. min = max;
  48873. max = temp;
  48874. }
  48875. d = Math.max(min, d);
  48876. maxValue = Math.min(max, maxValue);
  48877. if (d > maxValue) {
  48878. return false;
  48879. }
  48880. }
  48881. if (Math.abs(this.direction.y) < 0.0000001) {
  48882. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  48883. return false;
  48884. }
  48885. }
  48886. else {
  48887. inv = 1.0 / this.direction.y;
  48888. min = (minimum.y - this.origin.y) * inv;
  48889. max = (maximum.y - this.origin.y) * inv;
  48890. if (max === -Infinity) {
  48891. max = Infinity;
  48892. }
  48893. if (min > max) {
  48894. temp = min;
  48895. min = max;
  48896. max = temp;
  48897. }
  48898. d = Math.max(min, d);
  48899. maxValue = Math.min(max, maxValue);
  48900. if (d > maxValue) {
  48901. return false;
  48902. }
  48903. }
  48904. if (Math.abs(this.direction.z) < 0.0000001) {
  48905. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  48906. return false;
  48907. }
  48908. }
  48909. else {
  48910. inv = 1.0 / this.direction.z;
  48911. min = (minimum.z - this.origin.z) * inv;
  48912. max = (maximum.z - this.origin.z) * inv;
  48913. if (max === -Infinity) {
  48914. max = Infinity;
  48915. }
  48916. if (min > max) {
  48917. temp = min;
  48918. min = max;
  48919. max = temp;
  48920. }
  48921. d = Math.max(min, d);
  48922. maxValue = Math.min(max, maxValue);
  48923. if (d > maxValue) {
  48924. return false;
  48925. }
  48926. }
  48927. return true;
  48928. };
  48929. Ray.prototype.intersectsBox = function (box) {
  48930. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  48931. };
  48932. Ray.prototype.intersectsSphere = function (sphere) {
  48933. var x = sphere.center.x - this.origin.x;
  48934. var y = sphere.center.y - this.origin.y;
  48935. var z = sphere.center.z - this.origin.z;
  48936. var pyth = (x * x) + (y * y) + (z * z);
  48937. var rr = sphere.radius * sphere.radius;
  48938. if (pyth <= rr) {
  48939. return true;
  48940. }
  48941. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  48942. if (dot < 0.0) {
  48943. return false;
  48944. }
  48945. var temp = pyth - (dot * dot);
  48946. return temp <= rr;
  48947. };
  48948. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  48949. if (!this._edge1) {
  48950. this._edge1 = BABYLON.Vector3.Zero();
  48951. this._edge2 = BABYLON.Vector3.Zero();
  48952. this._pvec = BABYLON.Vector3.Zero();
  48953. this._tvec = BABYLON.Vector3.Zero();
  48954. this._qvec = BABYLON.Vector3.Zero();
  48955. }
  48956. vertex1.subtractToRef(vertex0, this._edge1);
  48957. vertex2.subtractToRef(vertex0, this._edge2);
  48958. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  48959. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  48960. if (det === 0) {
  48961. return null;
  48962. }
  48963. var invdet = 1 / det;
  48964. this.origin.subtractToRef(vertex0, this._tvec);
  48965. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  48966. if (bu < 0 || bu > 1.0) {
  48967. return null;
  48968. }
  48969. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  48970. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  48971. if (bv < 0 || bu + bv > 1.0) {
  48972. return null;
  48973. }
  48974. //check if the distance is longer than the predefined length.
  48975. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  48976. if (distance > this.length) {
  48977. return null;
  48978. }
  48979. return new BABYLON.IntersectionInfo(bu, bv, distance);
  48980. };
  48981. Ray.prototype.intersectsPlane = function (plane) {
  48982. var distance;
  48983. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  48984. if (Math.abs(result1) < 9.99999997475243E-07) {
  48985. return null;
  48986. }
  48987. else {
  48988. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  48989. distance = (-plane.d - result2) / result1;
  48990. if (distance < 0.0) {
  48991. if (distance < -9.99999997475243E-07) {
  48992. return null;
  48993. }
  48994. else {
  48995. return 0;
  48996. }
  48997. }
  48998. return distance;
  48999. }
  49000. };
  49001. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  49002. var tm = BABYLON.Tmp.Matrix[0];
  49003. mesh.getWorldMatrix().invertToRef(tm);
  49004. if (this._tmpRay) {
  49005. Ray.TransformToRef(this, tm, this._tmpRay);
  49006. }
  49007. else {
  49008. this._tmpRay = Ray.Transform(this, tm);
  49009. }
  49010. return mesh.intersects(this._tmpRay, fastCheck);
  49011. };
  49012. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  49013. if (results) {
  49014. results.length = 0;
  49015. }
  49016. else {
  49017. results = [];
  49018. }
  49019. for (var i = 0; i < meshes.length; i++) {
  49020. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  49021. if (pickInfo.hit) {
  49022. results.push(pickInfo);
  49023. }
  49024. }
  49025. results.sort(this._comparePickingInfo);
  49026. return results;
  49027. };
  49028. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  49029. if (pickingInfoA.distance < pickingInfoB.distance) {
  49030. return -1;
  49031. }
  49032. else if (pickingInfoA.distance > pickingInfoB.distance) {
  49033. return 1;
  49034. }
  49035. else {
  49036. return 0;
  49037. }
  49038. };
  49039. /**
  49040. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  49041. * @param sega the first point of the segment to test the intersection against
  49042. * @param segb the second point of the segment to test the intersection against
  49043. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  49044. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  49045. */
  49046. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  49047. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  49048. var u = segb.subtract(sega);
  49049. var v = rsegb.subtract(this.origin);
  49050. var w = sega.subtract(this.origin);
  49051. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  49052. var b = BABYLON.Vector3.Dot(u, v);
  49053. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  49054. var d = BABYLON.Vector3.Dot(u, w);
  49055. var e = BABYLON.Vector3.Dot(v, w);
  49056. var D = a * c - b * b; // always >= 0
  49057. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  49058. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  49059. // compute the line parameters of the two closest points
  49060. if (D < Ray.smallnum) {
  49061. sN = 0.0; // force using point P0 on segment S1
  49062. sD = 1.0; // to prevent possible division by 0.0 later
  49063. tN = e;
  49064. tD = c;
  49065. }
  49066. else {
  49067. sN = (b * e - c * d);
  49068. tN = (a * e - b * d);
  49069. if (sN < 0.0) {
  49070. sN = 0.0;
  49071. tN = e;
  49072. tD = c;
  49073. }
  49074. else if (sN > sD) {
  49075. sN = sD;
  49076. tN = e + b;
  49077. tD = c;
  49078. }
  49079. }
  49080. if (tN < 0.0) {
  49081. tN = 0.0;
  49082. // recompute sc for this edge
  49083. if (-d < 0.0) {
  49084. sN = 0.0;
  49085. }
  49086. else if (-d > a)
  49087. sN = sD;
  49088. else {
  49089. sN = -d;
  49090. sD = a;
  49091. }
  49092. }
  49093. else if (tN > tD) {
  49094. tN = tD;
  49095. // recompute sc for this edge
  49096. if ((-d + b) < 0.0) {
  49097. sN = 0;
  49098. }
  49099. else if ((-d + b) > a) {
  49100. sN = sD;
  49101. }
  49102. else {
  49103. sN = (-d + b);
  49104. sD = a;
  49105. }
  49106. }
  49107. // finally do the division to get sc and tc
  49108. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  49109. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  49110. // get the difference of the two closest points
  49111. var qtc = v.multiplyByFloats(tc, tc, tc);
  49112. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  49113. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  49114. if (isIntersected) {
  49115. return qtc.length();
  49116. }
  49117. return -1;
  49118. };
  49119. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  49120. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  49121. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  49122. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  49123. this.direction.normalize();
  49124. return this;
  49125. };
  49126. // Statics
  49127. Ray.Zero = function () {
  49128. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  49129. };
  49130. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  49131. var result = Ray.Zero();
  49132. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  49133. };
  49134. /**
  49135. * 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
  49136. * transformed to the given world matrix.
  49137. * @param origin The origin point
  49138. * @param end The end point
  49139. * @param world a matrix to transform the ray to. Default is the identity matrix.
  49140. */
  49141. Ray.CreateNewFromTo = function (origin, end, world) {
  49142. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  49143. var direction = end.subtract(origin);
  49144. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  49145. direction.normalize();
  49146. return Ray.Transform(new Ray(origin, direction, length), world);
  49147. };
  49148. Ray.Transform = function (ray, matrix) {
  49149. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  49150. Ray.TransformToRef(ray, matrix, result);
  49151. return result;
  49152. };
  49153. Ray.TransformToRef = function (ray, matrix, result) {
  49154. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  49155. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  49156. result.length = ray.length;
  49157. var dir = result.direction;
  49158. var len = dir.length();
  49159. if (!(len === 0 || len === 1)) {
  49160. var num = 1.0 / len;
  49161. dir.x *= num;
  49162. dir.y *= num;
  49163. dir.z *= num;
  49164. result.length *= len;
  49165. }
  49166. };
  49167. Ray.smallnum = 0.00000001;
  49168. Ray.rayl = 10e8;
  49169. return Ray;
  49170. }());
  49171. BABYLON.Ray = Ray;
  49172. })(BABYLON || (BABYLON = {}));
  49173. //# sourceMappingURL=babylon.ray.js.map
  49174. var BABYLON;
  49175. (function (BABYLON) {
  49176. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  49177. if (boxMin.x > sphereCenter.x + sphereRadius)
  49178. return false;
  49179. if (sphereCenter.x - sphereRadius > boxMax.x)
  49180. return false;
  49181. if (boxMin.y > sphereCenter.y + sphereRadius)
  49182. return false;
  49183. if (sphereCenter.y - sphereRadius > boxMax.y)
  49184. return false;
  49185. if (boxMin.z > sphereCenter.z + sphereRadius)
  49186. return false;
  49187. if (sphereCenter.z - sphereRadius > boxMax.z)
  49188. return false;
  49189. return true;
  49190. };
  49191. var getLowestRoot = (function () {
  49192. var result = { root: 0, found: false };
  49193. return function (a, b, c, maxR) {
  49194. result.root = 0;
  49195. result.found = false;
  49196. var determinant = b * b - 4.0 * a * c;
  49197. if (determinant < 0)
  49198. return result;
  49199. var sqrtD = Math.sqrt(determinant);
  49200. var r1 = (-b - sqrtD) / (2.0 * a);
  49201. var r2 = (-b + sqrtD) / (2.0 * a);
  49202. if (r1 > r2) {
  49203. var temp = r2;
  49204. r2 = r1;
  49205. r1 = temp;
  49206. }
  49207. if (r1 > 0 && r1 < maxR) {
  49208. result.root = r1;
  49209. result.found = true;
  49210. return result;
  49211. }
  49212. if (r2 > 0 && r2 < maxR) {
  49213. result.root = r2;
  49214. result.found = true;
  49215. return result;
  49216. }
  49217. return result;
  49218. };
  49219. })();
  49220. var Collider = /** @class */ (function () {
  49221. function Collider() {
  49222. this._collisionPoint = BABYLON.Vector3.Zero();
  49223. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  49224. this._tempVector = BABYLON.Vector3.Zero();
  49225. this._tempVector2 = BABYLON.Vector3.Zero();
  49226. this._tempVector3 = BABYLON.Vector3.Zero();
  49227. this._tempVector4 = BABYLON.Vector3.Zero();
  49228. this._edge = BABYLON.Vector3.Zero();
  49229. this._baseToVertex = BABYLON.Vector3.Zero();
  49230. this._destinationPoint = BABYLON.Vector3.Zero();
  49231. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  49232. this._displacementVector = BABYLON.Vector3.Zero();
  49233. this._radius = BABYLON.Vector3.One();
  49234. this._retry = 0;
  49235. this._basePointWorld = BABYLON.Vector3.Zero();
  49236. this._velocityWorld = BABYLON.Vector3.Zero();
  49237. this._normalizedVelocity = BABYLON.Vector3.Zero();
  49238. this._collisionMask = -1;
  49239. }
  49240. Object.defineProperty(Collider.prototype, "collisionMask", {
  49241. get: function () {
  49242. return this._collisionMask;
  49243. },
  49244. set: function (mask) {
  49245. this._collisionMask = !isNaN(mask) ? mask : -1;
  49246. },
  49247. enumerable: true,
  49248. configurable: true
  49249. });
  49250. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  49251. /**
  49252. * Gets the plane normal used to compute the sliding response (in local space)
  49253. */
  49254. get: function () {
  49255. return this._slidePlaneNormal;
  49256. },
  49257. enumerable: true,
  49258. configurable: true
  49259. });
  49260. // Methods
  49261. Collider.prototype._initialize = function (source, dir, e) {
  49262. this._velocity = dir;
  49263. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  49264. this._basePoint = source;
  49265. source.multiplyToRef(this._radius, this._basePointWorld);
  49266. dir.multiplyToRef(this._radius, this._velocityWorld);
  49267. this._velocityWorldLength = this._velocityWorld.length();
  49268. this._epsilon = e;
  49269. this.collisionFound = false;
  49270. };
  49271. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  49272. pa.subtractToRef(point, this._tempVector);
  49273. pb.subtractToRef(point, this._tempVector2);
  49274. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  49275. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  49276. if (d < 0)
  49277. return false;
  49278. pc.subtractToRef(point, this._tempVector3);
  49279. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  49280. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  49281. if (d < 0)
  49282. return false;
  49283. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  49284. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  49285. return d >= 0;
  49286. };
  49287. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  49288. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  49289. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  49290. if (distance > this._velocityWorldLength + max + sphereRadius) {
  49291. return false;
  49292. }
  49293. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  49294. return false;
  49295. return true;
  49296. };
  49297. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  49298. var t0;
  49299. var embeddedInPlane = false;
  49300. //defensive programming, actually not needed.
  49301. if (!trianglePlaneArray) {
  49302. trianglePlaneArray = [];
  49303. }
  49304. if (!trianglePlaneArray[faceIndex]) {
  49305. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  49306. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  49307. }
  49308. var trianglePlane = trianglePlaneArray[faceIndex];
  49309. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  49310. return;
  49311. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  49312. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  49313. if (normalDotVelocity == 0) {
  49314. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  49315. return;
  49316. embeddedInPlane = true;
  49317. t0 = 0;
  49318. }
  49319. else {
  49320. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  49321. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  49322. if (t0 > t1) {
  49323. var temp = t1;
  49324. t1 = t0;
  49325. t0 = temp;
  49326. }
  49327. if (t0 > 1.0 || t1 < 0.0)
  49328. return;
  49329. if (t0 < 0)
  49330. t0 = 0;
  49331. if (t0 > 1.0)
  49332. t0 = 1.0;
  49333. }
  49334. this._collisionPoint.copyFromFloats(0, 0, 0);
  49335. var found = false;
  49336. var t = 1.0;
  49337. if (!embeddedInPlane) {
  49338. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  49339. this._velocity.scaleToRef(t0, this._tempVector);
  49340. this._planeIntersectionPoint.addInPlace(this._tempVector);
  49341. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  49342. found = true;
  49343. t = t0;
  49344. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  49345. }
  49346. }
  49347. if (!found) {
  49348. var velocitySquaredLength = this._velocity.lengthSquared();
  49349. var a = velocitySquaredLength;
  49350. this._basePoint.subtractToRef(p1, this._tempVector);
  49351. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  49352. var c = this._tempVector.lengthSquared() - 1.0;
  49353. var lowestRoot = getLowestRoot(a, b, c, t);
  49354. if (lowestRoot.found) {
  49355. t = lowestRoot.root;
  49356. found = true;
  49357. this._collisionPoint.copyFrom(p1);
  49358. }
  49359. this._basePoint.subtractToRef(p2, this._tempVector);
  49360. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  49361. c = this._tempVector.lengthSquared() - 1.0;
  49362. lowestRoot = getLowestRoot(a, b, c, t);
  49363. if (lowestRoot.found) {
  49364. t = lowestRoot.root;
  49365. found = true;
  49366. this._collisionPoint.copyFrom(p2);
  49367. }
  49368. this._basePoint.subtractToRef(p3, this._tempVector);
  49369. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  49370. c = this._tempVector.lengthSquared() - 1.0;
  49371. lowestRoot = getLowestRoot(a, b, c, t);
  49372. if (lowestRoot.found) {
  49373. t = lowestRoot.root;
  49374. found = true;
  49375. this._collisionPoint.copyFrom(p3);
  49376. }
  49377. p2.subtractToRef(p1, this._edge);
  49378. p1.subtractToRef(this._basePoint, this._baseToVertex);
  49379. var edgeSquaredLength = this._edge.lengthSquared();
  49380. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  49381. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  49382. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  49383. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  49384. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  49385. lowestRoot = getLowestRoot(a, b, c, t);
  49386. if (lowestRoot.found) {
  49387. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  49388. if (f >= 0.0 && f <= 1.0) {
  49389. t = lowestRoot.root;
  49390. found = true;
  49391. this._edge.scaleInPlace(f);
  49392. p1.addToRef(this._edge, this._collisionPoint);
  49393. }
  49394. }
  49395. p3.subtractToRef(p2, this._edge);
  49396. p2.subtractToRef(this._basePoint, this._baseToVertex);
  49397. edgeSquaredLength = this._edge.lengthSquared();
  49398. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  49399. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  49400. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  49401. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  49402. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  49403. lowestRoot = getLowestRoot(a, b, c, t);
  49404. if (lowestRoot.found) {
  49405. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  49406. if (f >= 0.0 && f <= 1.0) {
  49407. t = lowestRoot.root;
  49408. found = true;
  49409. this._edge.scaleInPlace(f);
  49410. p2.addToRef(this._edge, this._collisionPoint);
  49411. }
  49412. }
  49413. p1.subtractToRef(p3, this._edge);
  49414. p3.subtractToRef(this._basePoint, this._baseToVertex);
  49415. edgeSquaredLength = this._edge.lengthSquared();
  49416. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  49417. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  49418. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  49419. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  49420. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  49421. lowestRoot = getLowestRoot(a, b, c, t);
  49422. if (lowestRoot.found) {
  49423. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  49424. if (f >= 0.0 && f <= 1.0) {
  49425. t = lowestRoot.root;
  49426. found = true;
  49427. this._edge.scaleInPlace(f);
  49428. p3.addToRef(this._edge, this._collisionPoint);
  49429. }
  49430. }
  49431. }
  49432. if (found) {
  49433. var distToCollision = t * this._velocity.length();
  49434. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  49435. if (!this.intersectionPoint) {
  49436. this.intersectionPoint = this._collisionPoint.clone();
  49437. }
  49438. else {
  49439. this.intersectionPoint.copyFrom(this._collisionPoint);
  49440. }
  49441. this._nearestDistance = distToCollision;
  49442. this.collisionFound = true;
  49443. }
  49444. }
  49445. };
  49446. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  49447. for (var i = indexStart; i < indexEnd; i += 3) {
  49448. var p1 = pts[indices[i] - decal];
  49449. var p2 = pts[indices[i + 1] - decal];
  49450. var p3 = pts[indices[i + 2] - decal];
  49451. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  49452. }
  49453. };
  49454. Collider.prototype._getResponse = function (pos, vel) {
  49455. pos.addToRef(vel, this._destinationPoint);
  49456. vel.scaleInPlace((this._nearestDistance / vel.length()));
  49457. this._basePoint.addToRef(vel, pos);
  49458. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  49459. this._slidePlaneNormal.normalize();
  49460. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  49461. pos.addInPlace(this._displacementVector);
  49462. this.intersectionPoint.addInPlace(this._displacementVector);
  49463. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  49464. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  49465. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  49466. };
  49467. return Collider;
  49468. }());
  49469. BABYLON.Collider = Collider;
  49470. })(BABYLON || (BABYLON = {}));
  49471. //# sourceMappingURL=babylon.collider.js.map
  49472. var BABYLON;
  49473. (function (BABYLON) {
  49474. //WebWorker code will be inserted to this variable.
  49475. BABYLON.CollisionWorker = "";
  49476. var WorkerTaskType;
  49477. (function (WorkerTaskType) {
  49478. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  49479. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  49480. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  49481. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  49482. var WorkerReplyType;
  49483. (function (WorkerReplyType) {
  49484. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  49485. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  49486. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  49487. var CollisionCoordinatorWorker = /** @class */ (function () {
  49488. function CollisionCoordinatorWorker() {
  49489. var _this = this;
  49490. this._scaledPosition = BABYLON.Vector3.Zero();
  49491. this._scaledVelocity = BABYLON.Vector3.Zero();
  49492. this.onMeshUpdated = function (transformNode) {
  49493. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  49494. };
  49495. this.onGeometryUpdated = function (geometry) {
  49496. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  49497. };
  49498. this._afterRender = function () {
  49499. if (!_this._init)
  49500. return;
  49501. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  49502. return;
  49503. }
  49504. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  49505. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  49506. if (_this._runningUpdated > 4) {
  49507. return;
  49508. }
  49509. ++_this._runningUpdated;
  49510. var payload = {
  49511. updatedMeshes: _this._addUpdateMeshesList,
  49512. updatedGeometries: _this._addUpdateGeometriesList,
  49513. removedGeometries: _this._toRemoveGeometryArray,
  49514. removedMeshes: _this._toRemoveMeshesArray
  49515. };
  49516. var message = {
  49517. payload: payload,
  49518. taskType: WorkerTaskType.UPDATE
  49519. };
  49520. var serializable = [];
  49521. for (var id in payload.updatedGeometries) {
  49522. if (payload.updatedGeometries.hasOwnProperty(id)) {
  49523. //prepare transferables
  49524. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  49525. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  49526. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  49527. }
  49528. }
  49529. _this._worker.postMessage(message, serializable);
  49530. _this._addUpdateMeshesList = {};
  49531. _this._addUpdateGeometriesList = {};
  49532. _this._toRemoveGeometryArray = [];
  49533. _this._toRemoveMeshesArray = [];
  49534. };
  49535. this._onMessageFromWorker = function (e) {
  49536. var returnData = e.data;
  49537. if (returnData.error != WorkerReplyType.SUCCESS) {
  49538. //TODO what errors can be returned from the worker?
  49539. BABYLON.Tools.Warn("error returned from worker!");
  49540. return;
  49541. }
  49542. switch (returnData.taskType) {
  49543. case WorkerTaskType.INIT:
  49544. _this._init = true;
  49545. //Update the worked with ALL of the scene's current state
  49546. _this._scene.meshes.forEach(function (mesh) {
  49547. _this.onMeshAdded(mesh);
  49548. });
  49549. _this._scene.getGeometries().forEach(function (geometry) {
  49550. _this.onGeometryAdded(geometry);
  49551. });
  49552. break;
  49553. case WorkerTaskType.UPDATE:
  49554. _this._runningUpdated--;
  49555. break;
  49556. case WorkerTaskType.COLLIDE:
  49557. var returnPayload = returnData.payload;
  49558. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  49559. return;
  49560. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  49561. if (callback) {
  49562. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  49563. if (mesh) {
  49564. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  49565. }
  49566. }
  49567. //cleanup
  49568. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  49569. break;
  49570. }
  49571. };
  49572. this._collisionsCallbackArray = [];
  49573. this._init = false;
  49574. this._runningUpdated = 0;
  49575. this._addUpdateMeshesList = {};
  49576. this._addUpdateGeometriesList = {};
  49577. this._toRemoveGeometryArray = [];
  49578. this._toRemoveMeshesArray = [];
  49579. }
  49580. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  49581. if (!this._init)
  49582. return;
  49583. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  49584. return;
  49585. position.divideToRef(collider._radius, this._scaledPosition);
  49586. displacement.divideToRef(collider._radius, this._scaledVelocity);
  49587. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  49588. var payload = {
  49589. collider: {
  49590. position: this._scaledPosition.asArray(),
  49591. velocity: this._scaledVelocity.asArray(),
  49592. radius: collider._radius.asArray()
  49593. },
  49594. collisionId: collisionIndex,
  49595. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  49596. maximumRetry: maximumRetry
  49597. };
  49598. var message = {
  49599. payload: payload,
  49600. taskType: WorkerTaskType.COLLIDE
  49601. };
  49602. this._worker.postMessage(message);
  49603. };
  49604. CollisionCoordinatorWorker.prototype.init = function (scene) {
  49605. this._scene = scene;
  49606. this._scene.registerAfterRender(this._afterRender);
  49607. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  49608. this._worker = new Worker(workerUrl);
  49609. this._worker.onmessage = this._onMessageFromWorker;
  49610. var message = {
  49611. payload: {},
  49612. taskType: WorkerTaskType.INIT
  49613. };
  49614. this._worker.postMessage(message);
  49615. };
  49616. CollisionCoordinatorWorker.prototype.destroy = function () {
  49617. this._scene.unregisterAfterRender(this._afterRender);
  49618. this._worker.terminate();
  49619. };
  49620. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  49621. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  49622. this.onMeshUpdated(mesh);
  49623. };
  49624. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  49625. this._toRemoveMeshesArray.push(mesh.uniqueId);
  49626. };
  49627. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  49628. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  49629. geometry.onGeometryUpdated = this.onGeometryUpdated;
  49630. this.onGeometryUpdated(geometry);
  49631. };
  49632. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  49633. this._toRemoveGeometryArray.push(geometry.id);
  49634. };
  49635. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  49636. var submeshes = [];
  49637. if (mesh.subMeshes) {
  49638. submeshes = mesh.subMeshes.map(function (sm, idx) {
  49639. var boundingInfo = sm.getBoundingInfo();
  49640. return {
  49641. position: idx,
  49642. verticesStart: sm.verticesStart,
  49643. verticesCount: sm.verticesCount,
  49644. indexStart: sm.indexStart,
  49645. indexCount: sm.indexCount,
  49646. hasMaterial: !!sm.getMaterial(),
  49647. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  49648. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  49649. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  49650. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  49651. };
  49652. });
  49653. }
  49654. var geometryId = null;
  49655. if (mesh instanceof BABYLON.Mesh) {
  49656. var geometry = mesh.geometry;
  49657. geometryId = geometry ? geometry.id : null;
  49658. }
  49659. else if (mesh instanceof BABYLON.InstancedMesh) {
  49660. var geometry = mesh.sourceMesh.geometry;
  49661. geometryId = geometry ? geometry.id : null;
  49662. }
  49663. var boundingInfo = mesh.getBoundingInfo();
  49664. return {
  49665. uniqueId: mesh.uniqueId,
  49666. id: mesh.id,
  49667. name: mesh.name,
  49668. geometryId: geometryId,
  49669. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  49670. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  49671. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  49672. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  49673. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  49674. subMeshes: submeshes,
  49675. checkCollisions: mesh.checkCollisions
  49676. };
  49677. };
  49678. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  49679. return {
  49680. id: geometry.id,
  49681. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  49682. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  49683. indices: new Uint32Array(geometry.getIndices() || []),
  49684. };
  49685. };
  49686. return CollisionCoordinatorWorker;
  49687. }());
  49688. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  49689. var CollisionCoordinatorLegacy = /** @class */ (function () {
  49690. function CollisionCoordinatorLegacy() {
  49691. this._scaledPosition = BABYLON.Vector3.Zero();
  49692. this._scaledVelocity = BABYLON.Vector3.Zero();
  49693. this._finalPosition = BABYLON.Vector3.Zero();
  49694. }
  49695. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  49696. position.divideToRef(collider._radius, this._scaledPosition);
  49697. displacement.divideToRef(collider._radius, this._scaledVelocity);
  49698. collider.collidedMesh = null;
  49699. collider._retry = 0;
  49700. collider._initialVelocity = this._scaledVelocity;
  49701. collider._initialPosition = this._scaledPosition;
  49702. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  49703. this._finalPosition.multiplyInPlace(collider._radius);
  49704. //run the callback
  49705. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  49706. };
  49707. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  49708. this._scene = scene;
  49709. };
  49710. CollisionCoordinatorLegacy.prototype.destroy = function () {
  49711. //Legacy need no destruction method.
  49712. };
  49713. //No update in legacy mode
  49714. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  49715. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  49716. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  49717. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  49718. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  49719. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  49720. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  49721. if (excludedMesh === void 0) { excludedMesh = null; }
  49722. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  49723. if (collider._retry >= maximumRetry) {
  49724. finalPosition.copyFrom(position);
  49725. return;
  49726. }
  49727. // Check if this is a mesh else camera or -1
  49728. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  49729. collider._initialize(position, velocity, closeDistance);
  49730. // Check all meshes
  49731. for (var index = 0; index < this._scene.meshes.length; index++) {
  49732. var mesh = this._scene.meshes[index];
  49733. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  49734. mesh._checkCollision(collider);
  49735. }
  49736. }
  49737. if (!collider.collisionFound) {
  49738. position.addToRef(velocity, finalPosition);
  49739. return;
  49740. }
  49741. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  49742. collider._getResponse(position, velocity);
  49743. }
  49744. if (velocity.length() <= closeDistance) {
  49745. finalPosition.copyFrom(position);
  49746. return;
  49747. }
  49748. collider._retry++;
  49749. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  49750. };
  49751. return CollisionCoordinatorLegacy;
  49752. }());
  49753. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  49754. })(BABYLON || (BABYLON = {}));
  49755. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  49756. var BABYLON;
  49757. (function (BABYLON) {
  49758. /**
  49759. * A particle represents one of the element emitted by a particle system.
  49760. * This is mainly define by its coordinates, direction, velocity and age.
  49761. */
  49762. var Particle = /** @class */ (function () {
  49763. /**
  49764. * Creates a new instance of @see Particle
  49765. * @param particleSystem the particle system the particle belongs to
  49766. */
  49767. function Particle(particleSystem) {
  49768. this.particleSystem = particleSystem;
  49769. /**
  49770. * The world position of the particle in the scene.
  49771. */
  49772. this.position = BABYLON.Vector3.Zero();
  49773. /**
  49774. * The world direction of the particle in the scene.
  49775. */
  49776. this.direction = BABYLON.Vector3.Zero();
  49777. /**
  49778. * The color of the particle.
  49779. */
  49780. this.color = new BABYLON.Color4(0, 0, 0, 0);
  49781. /**
  49782. * The color change of the particle per step.
  49783. */
  49784. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  49785. /**
  49786. * Defines how long will the life of the particle be.
  49787. */
  49788. this.lifeTime = 1.0;
  49789. /**
  49790. * The current age of the particle.
  49791. */
  49792. this.age = 0;
  49793. /**
  49794. * The current size of the particle.
  49795. */
  49796. this.size = 0;
  49797. /**
  49798. * The current angle of the particle.
  49799. */
  49800. this.angle = 0;
  49801. /**
  49802. * Defines how fast is the angle changing.
  49803. */
  49804. this.angularSpeed = 0;
  49805. /**
  49806. * Defines the cell index used by the particle to be rendered from a sprite.
  49807. */
  49808. this.cellIndex = 0;
  49809. this._currentFrameCounter = 0;
  49810. if (!this.particleSystem.isAnimationSheetEnabled) {
  49811. return;
  49812. }
  49813. this.cellIndex = this.particleSystem.startSpriteCellID;
  49814. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  49815. this.updateCellIndex = this.updateCellIndexWithSpeedCalculated;
  49816. }
  49817. else {
  49818. this.updateCellIndex = this.updateCellIndexWithCustomSpeed;
  49819. }
  49820. }
  49821. Particle.prototype.updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  49822. // (ageOffset / scaledUpdateSpeed) / available cells
  49823. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  49824. this._currentFrameCounter += scaledUpdateSpeed;
  49825. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  49826. this._currentFrameCounter = 0;
  49827. this.cellIndex++;
  49828. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  49829. this.cellIndex = this.particleSystem.endSpriteCellID;
  49830. }
  49831. }
  49832. };
  49833. Particle.prototype.updateCellIndexWithCustomSpeed = function () {
  49834. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  49835. this.cellIndex++;
  49836. this._currentFrameCounter = 0;
  49837. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  49838. if (this.particleSystem.spriteCellLoop) {
  49839. this.cellIndex = this.particleSystem.startSpriteCellID;
  49840. }
  49841. else {
  49842. this.cellIndex = this.particleSystem.endSpriteCellID;
  49843. }
  49844. }
  49845. }
  49846. else {
  49847. this._currentFrameCounter++;
  49848. }
  49849. };
  49850. /**
  49851. * Copy the properties of particle to another one.
  49852. * @param other the particle to copy the information to.
  49853. */
  49854. Particle.prototype.copyTo = function (other) {
  49855. other.position.copyFrom(this.position);
  49856. other.direction.copyFrom(this.direction);
  49857. other.color.copyFrom(this.color);
  49858. other.colorStep.copyFrom(this.colorStep);
  49859. other.lifeTime = this.lifeTime;
  49860. other.age = this.age;
  49861. other.size = this.size;
  49862. other.angle = this.angle;
  49863. other.angularSpeed = this.angularSpeed;
  49864. other.particleSystem = this.particleSystem;
  49865. other.cellIndex = this.cellIndex;
  49866. };
  49867. return Particle;
  49868. }());
  49869. BABYLON.Particle = Particle;
  49870. })(BABYLON || (BABYLON = {}));
  49871. //# sourceMappingURL=babylon.particle.js.map
  49872. var BABYLON;
  49873. (function (BABYLON) {
  49874. /**
  49875. * This represents a particle system in Babylon.
  49876. * 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.
  49877. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  49878. * @example https://doc.babylonjs.com/babylon101/particles
  49879. */
  49880. var ParticleSystem = /** @class */ (function () {
  49881. /**
  49882. * Instantiates a particle system.
  49883. * 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.
  49884. * @param name The name of the particle system
  49885. * @param capacity The max number of particles alive at the same time
  49886. * @param scene The scene the particle system belongs to
  49887. * @param customEffect a custom effect used to change the way particles are rendered by default
  49888. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  49889. * @param epsilon Offset used to render the particles
  49890. */
  49891. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  49892. if (customEffect === void 0) { customEffect = null; }
  49893. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  49894. if (epsilon === void 0) { epsilon = 0.01; }
  49895. var _this = this;
  49896. /**
  49897. * List of animations used by the particle system.
  49898. */
  49899. this.animations = [];
  49900. /**
  49901. * The rendering group used by the Particle system to chose when to render.
  49902. */
  49903. this.renderingGroupId = 0;
  49904. /**
  49905. * The emitter represents the Mesh or position we are attaching the particle system to.
  49906. */
  49907. this.emitter = null;
  49908. /**
  49909. * The density of particles, the rate of particle flow
  49910. */
  49911. this.emitRate = 10;
  49912. /**
  49913. * If you want to launch only a few particles at once, that can be done, as well.
  49914. */
  49915. this.manualEmitCount = -1;
  49916. /**
  49917. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  49918. */
  49919. this.updateSpeed = 0.01;
  49920. /**
  49921. * The amount of time the particle system is running (depends of the overall speed above).
  49922. */
  49923. this.targetStopDuration = 0;
  49924. /**
  49925. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  49926. */
  49927. this.disposeOnStop = false;
  49928. /**
  49929. * Minimum power of emitting particles.
  49930. */
  49931. this.minEmitPower = 1;
  49932. /**
  49933. * Maximum power of emitting particles.
  49934. */
  49935. this.maxEmitPower = 1;
  49936. /**
  49937. * Minimum life time of emitting particles.
  49938. */
  49939. this.minLifeTime = 1;
  49940. /**
  49941. * Maximum life time of emitting particles.
  49942. */
  49943. this.maxLifeTime = 1;
  49944. /**
  49945. * Minimum Size of emitting particles.
  49946. */
  49947. this.minSize = 1;
  49948. /**
  49949. * Maximum Size of emitting particles.
  49950. */
  49951. this.maxSize = 1;
  49952. /**
  49953. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  49954. */
  49955. this.minAngularSpeed = 0;
  49956. /**
  49957. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  49958. */
  49959. this.maxAngularSpeed = 0;
  49960. /**
  49961. * The layer mask we are rendering the particles through.
  49962. */
  49963. this.layerMask = 0x0FFFFFFF;
  49964. /**
  49965. * This can help using your own shader to render the particle system.
  49966. * The according effect will be created
  49967. */
  49968. this.customShader = null;
  49969. /**
  49970. * By default particle system starts as soon as they are created. This prevents the
  49971. * automatic start to happen and let you decide when to start emitting particles.
  49972. */
  49973. this.preventAutoStart = false;
  49974. /**
  49975. * Callback triggered when the particle animation is ending.
  49976. */
  49977. this.onAnimationEnd = null;
  49978. /**
  49979. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  49980. */
  49981. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  49982. /**
  49983. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  49984. * to override the particles.
  49985. */
  49986. this.forceDepthWrite = false;
  49987. /**
  49988. * You can use gravity if you want to give an orientation to your particles.
  49989. */
  49990. this.gravity = BABYLON.Vector3.Zero();
  49991. /**
  49992. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  49993. */
  49994. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  49995. /**
  49996. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  49997. */
  49998. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  49999. /**
  50000. * 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.
  50001. */
  50002. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  50003. /**
  50004. * 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.
  50005. */
  50006. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  50007. /**
  50008. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  50009. */
  50010. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  50011. /**
  50012. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  50013. */
  50014. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  50015. /**
  50016. * Color the particle will have at the end of its lifetime.
  50017. */
  50018. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  50019. /**
  50020. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel.
  50021. */
  50022. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  50023. /**
  50024. * If using a spritesheet (isAnimationSheetEnabled), defines if the sprite animation should loop between startSpriteCellID and endSpriteCellID or not.
  50025. */
  50026. this.spriteCellLoop = true;
  50027. /**
  50028. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the speed of the sprite loop.
  50029. */
  50030. this.spriteCellChangeSpeed = 0;
  50031. /**
  50032. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the first sprite cell to display.
  50033. */
  50034. this.startSpriteCellID = 0;
  50035. /**
  50036. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the last sprite cell to display.
  50037. */
  50038. this.endSpriteCellID = 0;
  50039. /**
  50040. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use.
  50041. */
  50042. this.spriteCellWidth = 0;
  50043. /**
  50044. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use.
  50045. */
  50046. this.spriteCellHeight = 0;
  50047. /**
  50048. * An event triggered when the system is disposed.
  50049. */
  50050. this.onDisposeObservable = new BABYLON.Observable();
  50051. this._particles = new Array();
  50052. this._stockParticles = new Array();
  50053. this._newPartsExcess = 0;
  50054. this._vertexBuffers = {};
  50055. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  50056. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  50057. this._scaledDirection = BABYLON.Vector3.Zero();
  50058. this._scaledGravity = BABYLON.Vector3.Zero();
  50059. this._currentRenderId = -1;
  50060. this._started = false;
  50061. this._stopped = false;
  50062. this._actualFrame = 0;
  50063. this._vertexBufferSize = 11;
  50064. this._appendParticleVertexes = null;
  50065. this.id = name;
  50066. this.name = name;
  50067. this._capacity = capacity;
  50068. this._epsilon = epsilon;
  50069. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  50070. if (isAnimationSheetEnabled) {
  50071. this._vertexBufferSize = 12;
  50072. }
  50073. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  50074. this._customEffect = customEffect;
  50075. scene.particleSystems.push(this);
  50076. this._createIndexBuffer();
  50077. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  50078. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4);
  50079. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize);
  50080. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  50081. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  50082. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  50083. if (this._isAnimationSheetEnabled) {
  50084. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", 11, 1);
  50085. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  50086. }
  50087. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  50088. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  50089. this._vertexBuffers["options"] = options;
  50090. // Default behaviors
  50091. this.particleEmitterType = new BABYLON.BoxParticleEmitter(this);
  50092. this.updateFunction = function (particles) {
  50093. for (var index = 0; index < particles.length; index++) {
  50094. var particle = particles[index];
  50095. particle.age += _this._scaledUpdateSpeed;
  50096. if (particle.age >= particle.lifeTime) {
  50097. _this.recycleParticle(particle);
  50098. index--;
  50099. continue;
  50100. }
  50101. else {
  50102. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  50103. particle.color.addInPlace(_this._scaledColorStep);
  50104. if (particle.color.a < 0)
  50105. particle.color.a = 0;
  50106. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  50107. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  50108. particle.position.addInPlace(_this._scaledDirection);
  50109. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  50110. particle.direction.addInPlace(_this._scaledGravity);
  50111. if (_this._isAnimationSheetEnabled) {
  50112. particle.updateCellIndex(_this._scaledUpdateSpeed);
  50113. }
  50114. }
  50115. }
  50116. };
  50117. }
  50118. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  50119. /**
  50120. * Sets a callback that will be triggered when the system is disposed.
  50121. */
  50122. set: function (callback) {
  50123. if (this._onDisposeObserver) {
  50124. this.onDisposeObservable.remove(this._onDisposeObserver);
  50125. }
  50126. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  50127. },
  50128. enumerable: true,
  50129. configurable: true
  50130. });
  50131. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  50132. /**
  50133. * Gets wether an animation sprite sheet is enabled or not on the particle system.
  50134. */
  50135. get: function () {
  50136. return this._isAnimationSheetEnabled;
  50137. },
  50138. enumerable: true,
  50139. configurable: true
  50140. });
  50141. ParticleSystem.prototype._createIndexBuffer = function () {
  50142. var indices = [];
  50143. var index = 0;
  50144. for (var count = 0; count < this._capacity; count++) {
  50145. indices.push(index);
  50146. indices.push(index + 1);
  50147. indices.push(index + 2);
  50148. indices.push(index);
  50149. indices.push(index + 2);
  50150. indices.push(index + 3);
  50151. index += 4;
  50152. }
  50153. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  50154. };
  50155. /**
  50156. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  50157. * Its lifetime will start back at 0.
  50158. * @param particle The particle to recycle
  50159. */
  50160. ParticleSystem.prototype.recycleParticle = function (particle) {
  50161. var lastParticle = this._particles.pop();
  50162. if (lastParticle !== particle) {
  50163. lastParticle.copyTo(particle);
  50164. this._stockParticles.push(lastParticle);
  50165. }
  50166. };
  50167. /**
  50168. * Gets the maximum number of particles active at the same time.
  50169. * @returns The max number of active particles.
  50170. */
  50171. ParticleSystem.prototype.getCapacity = function () {
  50172. return this._capacity;
  50173. };
  50174. /**
  50175. * Gets Wether there are still active particles in the system.
  50176. * @returns True if it is alive, otherwise false.
  50177. */
  50178. ParticleSystem.prototype.isAlive = function () {
  50179. return this._alive;
  50180. };
  50181. /**
  50182. * Gets Wether the system has been started.
  50183. * @returns True if it has been started, otherwise false.
  50184. */
  50185. ParticleSystem.prototype.isStarted = function () {
  50186. return this._started;
  50187. };
  50188. /**
  50189. * Starts the particle system and begins to emit.
  50190. */
  50191. ParticleSystem.prototype.start = function () {
  50192. this._started = true;
  50193. this._stopped = false;
  50194. this._actualFrame = 0;
  50195. };
  50196. /**
  50197. * Stops the particle system.
  50198. */
  50199. ParticleSystem.prototype.stop = function () {
  50200. this._stopped = true;
  50201. };
  50202. /**
  50203. * @ignore (for internal use only)
  50204. */
  50205. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  50206. var offset = index * this._vertexBufferSize;
  50207. this._vertexData[offset] = particle.position.x;
  50208. this._vertexData[offset + 1] = particle.position.y;
  50209. this._vertexData[offset + 2] = particle.position.z;
  50210. this._vertexData[offset + 3] = particle.color.r;
  50211. this._vertexData[offset + 4] = particle.color.g;
  50212. this._vertexData[offset + 5] = particle.color.b;
  50213. this._vertexData[offset + 6] = particle.color.a;
  50214. this._vertexData[offset + 7] = particle.angle;
  50215. this._vertexData[offset + 8] = particle.size;
  50216. this._vertexData[offset + 9] = offsetX;
  50217. this._vertexData[offset + 10] = offsetY;
  50218. };
  50219. /**
  50220. * @ignore (for internal use only)
  50221. */
  50222. ParticleSystem.prototype._appendParticleVertexWithAnimation = function (index, particle, offsetX, offsetY) {
  50223. if (offsetX === 0)
  50224. offsetX = this._epsilon;
  50225. else if (offsetX === 1)
  50226. offsetX = 1 - this._epsilon;
  50227. if (offsetY === 0)
  50228. offsetY = this._epsilon;
  50229. else if (offsetY === 1)
  50230. offsetY = 1 - this._epsilon;
  50231. var offset = index * this._vertexBufferSize;
  50232. this._vertexData[offset] = particle.position.x;
  50233. this._vertexData[offset + 1] = particle.position.y;
  50234. this._vertexData[offset + 2] = particle.position.z;
  50235. this._vertexData[offset + 3] = particle.color.r;
  50236. this._vertexData[offset + 4] = particle.color.g;
  50237. this._vertexData[offset + 5] = particle.color.b;
  50238. this._vertexData[offset + 6] = particle.color.a;
  50239. this._vertexData[offset + 7] = particle.angle;
  50240. this._vertexData[offset + 8] = particle.size;
  50241. this._vertexData[offset + 9] = offsetX;
  50242. this._vertexData[offset + 10] = offsetY;
  50243. this._vertexData[offset + 11] = particle.cellIndex;
  50244. };
  50245. ParticleSystem.prototype._update = function (newParticles) {
  50246. // Update current
  50247. this._alive = this._particles.length > 0;
  50248. this.updateFunction(this._particles);
  50249. // Add new ones
  50250. var worldMatrix;
  50251. if (this.emitter.position) {
  50252. var emitterMesh = this.emitter;
  50253. worldMatrix = emitterMesh.getWorldMatrix();
  50254. }
  50255. else {
  50256. var emitterPosition = this.emitter;
  50257. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  50258. }
  50259. var particle;
  50260. for (var index = 0; index < newParticles; index++) {
  50261. if (this._particles.length === this._capacity) {
  50262. break;
  50263. }
  50264. if (this._stockParticles.length !== 0) {
  50265. particle = this._stockParticles.pop();
  50266. particle.age = 0;
  50267. particle.cellIndex = this.startSpriteCellID;
  50268. }
  50269. else {
  50270. particle = new BABYLON.Particle(this);
  50271. }
  50272. this._particles.push(particle);
  50273. var emitPower = BABYLON.Scalar.RandomRange(this.minEmitPower, this.maxEmitPower);
  50274. if (this.startPositionFunction) {
  50275. this.startPositionFunction(worldMatrix, particle.position, particle);
  50276. }
  50277. else {
  50278. this.particleEmitterType.startPositionFunction(worldMatrix, particle.position, particle);
  50279. }
  50280. if (this.startDirectionFunction) {
  50281. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  50282. }
  50283. else {
  50284. this.particleEmitterType.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  50285. }
  50286. particle.lifeTime = BABYLON.Scalar.RandomRange(this.minLifeTime, this.maxLifeTime);
  50287. particle.size = BABYLON.Scalar.RandomRange(this.minSize, this.maxSize);
  50288. particle.angularSpeed = BABYLON.Scalar.RandomRange(this.minAngularSpeed, this.maxAngularSpeed);
  50289. var step = BABYLON.Scalar.RandomRange(0, 1.0);
  50290. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  50291. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  50292. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  50293. }
  50294. };
  50295. ParticleSystem.prototype._getEffect = function () {
  50296. if (this._customEffect) {
  50297. return this._customEffect;
  50298. }
  50299. ;
  50300. var defines = [];
  50301. if (this._scene.clipPlane) {
  50302. defines.push("#define CLIPPLANE");
  50303. }
  50304. if (this._isAnimationSheetEnabled) {
  50305. defines.push("#define ANIMATESHEET");
  50306. }
  50307. // Effect
  50308. var join = defines.join("\n");
  50309. if (this._cachedDefines !== join) {
  50310. this._cachedDefines = join;
  50311. var attributesNamesOrOptions;
  50312. var effectCreationOption;
  50313. if (this._isAnimationSheetEnabled) {
  50314. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "cellIndex"];
  50315. effectCreationOption = ["invView", "view", "projection", "particlesInfos", "vClipPlane", "textureMask"];
  50316. }
  50317. else {
  50318. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"];
  50319. effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  50320. }
  50321. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  50322. }
  50323. return this._effect;
  50324. };
  50325. /**
  50326. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  50327. */
  50328. ParticleSystem.prototype.animate = function () {
  50329. if (!this._started)
  50330. return;
  50331. var effect = this._getEffect();
  50332. // Check
  50333. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  50334. return;
  50335. if (this._currentRenderId === this._scene.getRenderId()) {
  50336. return;
  50337. }
  50338. this._currentRenderId = this._scene.getRenderId();
  50339. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  50340. // determine the number of particles we need to create
  50341. var newParticles;
  50342. if (this.manualEmitCount > -1) {
  50343. newParticles = this.manualEmitCount;
  50344. this._newPartsExcess = 0;
  50345. this.manualEmitCount = 0;
  50346. }
  50347. else {
  50348. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  50349. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  50350. }
  50351. if (this._newPartsExcess > 1.0) {
  50352. newParticles += this._newPartsExcess >> 0;
  50353. this._newPartsExcess -= this._newPartsExcess >> 0;
  50354. }
  50355. this._alive = false;
  50356. if (!this._stopped) {
  50357. this._actualFrame += this._scaledUpdateSpeed;
  50358. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  50359. this.stop();
  50360. }
  50361. else {
  50362. newParticles = 0;
  50363. }
  50364. this._update(newParticles);
  50365. // Stopped?
  50366. if (this._stopped) {
  50367. if (!this._alive) {
  50368. this._started = false;
  50369. if (this.onAnimationEnd) {
  50370. this.onAnimationEnd();
  50371. }
  50372. if (this.disposeOnStop) {
  50373. this._scene._toBeDisposed.push(this);
  50374. }
  50375. }
  50376. }
  50377. // Animation sheet
  50378. if (this._isAnimationSheetEnabled) {
  50379. this._appendParticleVertexes = this._appenedParticleVertexesWithSheet;
  50380. }
  50381. else {
  50382. this._appendParticleVertexes = this._appenedParticleVertexesNoSheet;
  50383. }
  50384. // Update VBO
  50385. var offset = 0;
  50386. for (var index = 0; index < this._particles.length; index++) {
  50387. var particle = this._particles[index];
  50388. this._appendParticleVertexes(offset, particle);
  50389. offset += 4;
  50390. }
  50391. if (this._vertexBuffer) {
  50392. this._vertexBuffer.update(this._vertexData);
  50393. }
  50394. };
  50395. ParticleSystem.prototype._appenedParticleVertexesWithSheet = function (offset, particle) {
  50396. this._appendParticleVertexWithAnimation(offset++, particle, 0, 0);
  50397. this._appendParticleVertexWithAnimation(offset++, particle, 1, 0);
  50398. this._appendParticleVertexWithAnimation(offset++, particle, 1, 1);
  50399. this._appendParticleVertexWithAnimation(offset++, particle, 0, 1);
  50400. };
  50401. ParticleSystem.prototype._appenedParticleVertexesNoSheet = function (offset, particle) {
  50402. this._appendParticleVertex(offset++, particle, 0, 0);
  50403. this._appendParticleVertex(offset++, particle, 1, 0);
  50404. this._appendParticleVertex(offset++, particle, 1, 1);
  50405. this._appendParticleVertex(offset++, particle, 0, 1);
  50406. };
  50407. /**
  50408. * Rebuilds the particle system.
  50409. */
  50410. ParticleSystem.prototype.rebuild = function () {
  50411. this._createIndexBuffer();
  50412. if (this._vertexBuffer) {
  50413. this._vertexBuffer._rebuild();
  50414. }
  50415. };
  50416. /**
  50417. * Renders the particle system in its current state.
  50418. * @returns the current number of particles.
  50419. */
  50420. ParticleSystem.prototype.render = function () {
  50421. var effect = this._getEffect();
  50422. // Check
  50423. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this._particles.length)
  50424. return 0;
  50425. var engine = this._scene.getEngine();
  50426. // Render
  50427. engine.enableEffect(effect);
  50428. engine.setState(false);
  50429. var viewMatrix = this._scene.getViewMatrix();
  50430. effect.setTexture("diffuseSampler", this.particleTexture);
  50431. effect.setMatrix("view", viewMatrix);
  50432. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  50433. if (this._isAnimationSheetEnabled) {
  50434. var baseSize = this.particleTexture.getBaseSize();
  50435. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  50436. }
  50437. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  50438. if (this._scene.clipPlane) {
  50439. var clipPlane = this._scene.clipPlane;
  50440. var invView = viewMatrix.clone();
  50441. invView.invert();
  50442. effect.setMatrix("invView", invView);
  50443. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  50444. }
  50445. // VBOs
  50446. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  50447. // Draw order
  50448. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  50449. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  50450. }
  50451. else {
  50452. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  50453. }
  50454. if (this.forceDepthWrite) {
  50455. engine.setDepthWrite(true);
  50456. }
  50457. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  50458. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  50459. return this._particles.length;
  50460. };
  50461. /**
  50462. * Disposes the particle system and free the associated resources.
  50463. */
  50464. ParticleSystem.prototype.dispose = function () {
  50465. if (this._vertexBuffer) {
  50466. this._vertexBuffer.dispose();
  50467. this._vertexBuffer = null;
  50468. }
  50469. if (this._indexBuffer) {
  50470. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  50471. this._indexBuffer = null;
  50472. }
  50473. if (this.particleTexture) {
  50474. this.particleTexture.dispose();
  50475. this.particleTexture = null;
  50476. }
  50477. // Remove from scene
  50478. var index = this._scene.particleSystems.indexOf(this);
  50479. if (index > -1) {
  50480. this._scene.particleSystems.splice(index, 1);
  50481. }
  50482. // Callback
  50483. this.onDisposeObservable.notifyObservers(this);
  50484. this.onDisposeObservable.clear();
  50485. };
  50486. /**
  50487. * Creates a Sphere Emitter for the particle system. (emits along the sphere radius)
  50488. * @param radius The radius of the sphere to emit from
  50489. * @returns the emitter
  50490. */
  50491. ParticleSystem.prototype.createSphereEmitter = function (radius) {
  50492. if (radius === void 0) { radius = 1; }
  50493. var particleEmitter = new BABYLON.SphereParticleEmitter(radius);
  50494. this.particleEmitterType = particleEmitter;
  50495. return particleEmitter;
  50496. };
  50497. /**
  50498. * Creates a Directed Sphere Emitter for the particle system. (emits between direction1 and direction2)
  50499. * @param radius The radius of the sphere to emit from
  50500. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  50501. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  50502. * @returns the emitter
  50503. */
  50504. ParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  50505. if (radius === void 0) { radius = 1; }
  50506. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  50507. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  50508. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  50509. this.particleEmitterType = particleEmitter;
  50510. return particleEmitter;
  50511. };
  50512. /**
  50513. * Creates a Cone Emitter for the particle system. (emits from the cone to the particle position)
  50514. * @param radius The radius of the cone to emit from
  50515. * @param angle The base angle of the cone
  50516. * @returns the emitter
  50517. */
  50518. ParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  50519. if (radius === void 0) { radius = 1; }
  50520. if (angle === void 0) { angle = Math.PI / 4; }
  50521. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  50522. this.particleEmitterType = particleEmitter;
  50523. return particleEmitter;
  50524. };
  50525. // 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.
  50526. /**
  50527. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  50528. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  50529. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  50530. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  50531. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  50532. * @returns the emitter
  50533. */
  50534. ParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  50535. var particleEmitter = new BABYLON.BoxParticleEmitter(this);
  50536. this.direction1 = direction1;
  50537. this.direction2 = direction2;
  50538. this.minEmitBox = minEmitBox;
  50539. this.maxEmitBox = maxEmitBox;
  50540. this.particleEmitterType = particleEmitter;
  50541. return particleEmitter;
  50542. };
  50543. /**
  50544. * Clones the particle system.
  50545. * @param name The name of the cloned object
  50546. * @param newEmitter The new emitter to use
  50547. * @returns the cloned particle system
  50548. */
  50549. ParticleSystem.prototype.clone = function (name, newEmitter) {
  50550. var custom = null;
  50551. var program = null;
  50552. if (this.customShader != null) {
  50553. program = this.customShader;
  50554. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  50555. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  50556. }
  50557. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  50558. result.customShader = program;
  50559. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  50560. if (newEmitter === undefined) {
  50561. newEmitter = this.emitter;
  50562. }
  50563. result.emitter = newEmitter;
  50564. if (this.particleTexture) {
  50565. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  50566. }
  50567. if (!this.preventAutoStart) {
  50568. result.start();
  50569. }
  50570. return result;
  50571. };
  50572. /**
  50573. * Serializes the particle system to a JSON object.
  50574. * @returns the JSON object
  50575. */
  50576. ParticleSystem.prototype.serialize = function () {
  50577. var serializationObject = {};
  50578. serializationObject.name = this.name;
  50579. serializationObject.id = this.id;
  50580. // Emitter
  50581. if (this.emitter.position) {
  50582. var emitterMesh = this.emitter;
  50583. serializationObject.emitterId = emitterMesh.id;
  50584. }
  50585. else {
  50586. var emitterPosition = this.emitter;
  50587. serializationObject.emitter = emitterPosition.asArray();
  50588. }
  50589. serializationObject.capacity = this.getCapacity();
  50590. if (this.particleTexture) {
  50591. serializationObject.textureName = this.particleTexture.name;
  50592. }
  50593. // Animations
  50594. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  50595. // Particle system
  50596. serializationObject.minAngularSpeed = this.minAngularSpeed;
  50597. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  50598. serializationObject.minSize = this.minSize;
  50599. serializationObject.maxSize = this.maxSize;
  50600. serializationObject.minEmitPower = this.minEmitPower;
  50601. serializationObject.maxEmitPower = this.maxEmitPower;
  50602. serializationObject.minLifeTime = this.minLifeTime;
  50603. serializationObject.maxLifeTime = this.maxLifeTime;
  50604. serializationObject.emitRate = this.emitRate;
  50605. serializationObject.minEmitBox = this.minEmitBox.asArray();
  50606. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  50607. serializationObject.gravity = this.gravity.asArray();
  50608. serializationObject.direction1 = this.direction1.asArray();
  50609. serializationObject.direction2 = this.direction2.asArray();
  50610. serializationObject.color1 = this.color1.asArray();
  50611. serializationObject.color2 = this.color2.asArray();
  50612. serializationObject.colorDead = this.colorDead.asArray();
  50613. serializationObject.updateSpeed = this.updateSpeed;
  50614. serializationObject.targetStopDuration = this.targetStopDuration;
  50615. serializationObject.textureMask = this.textureMask.asArray();
  50616. serializationObject.blendMode = this.blendMode;
  50617. serializationObject.customShader = this.customShader;
  50618. serializationObject.preventAutoStart = this.preventAutoStart;
  50619. serializationObject.startSpriteCellID = this.startSpriteCellID;
  50620. serializationObject.endSpriteCellID = this.endSpriteCellID;
  50621. serializationObject.spriteCellLoop = this.spriteCellLoop;
  50622. serializationObject.spriteCellChangeSpeed = this.spriteCellChangeSpeed;
  50623. serializationObject.spriteCellWidth = this.spriteCellWidth;
  50624. serializationObject.spriteCellHeight = this.spriteCellHeight;
  50625. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  50626. return serializationObject;
  50627. };
  50628. /**
  50629. * Parses a JSON object to create a particle system.
  50630. * @param parsedParticleSystem The JSON object to parse
  50631. * @param scene The scene to create the particle system in
  50632. * @param rootUrl The root url to use to load external dependencies like texture
  50633. * @returns the Parsed particle system
  50634. */
  50635. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  50636. var name = parsedParticleSystem.name;
  50637. var custom = null;
  50638. var program = null;
  50639. if (parsedParticleSystem.customShader) {
  50640. program = parsedParticleSystem.customShader;
  50641. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  50642. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  50643. }
  50644. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  50645. particleSystem.customShader = program;
  50646. if (parsedParticleSystem.id) {
  50647. particleSystem.id = parsedParticleSystem.id;
  50648. }
  50649. // Auto start
  50650. if (parsedParticleSystem.preventAutoStart) {
  50651. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  50652. }
  50653. // Texture
  50654. if (parsedParticleSystem.textureName) {
  50655. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  50656. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  50657. }
  50658. // Emitter
  50659. if (parsedParticleSystem.emitterId) {
  50660. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  50661. }
  50662. else {
  50663. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  50664. }
  50665. // Animations
  50666. if (parsedParticleSystem.animations) {
  50667. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  50668. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  50669. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  50670. }
  50671. }
  50672. if (parsedParticleSystem.autoAnimate) {
  50673. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  50674. }
  50675. // Particle system
  50676. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  50677. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  50678. particleSystem.minSize = parsedParticleSystem.minSize;
  50679. particleSystem.maxSize = parsedParticleSystem.maxSize;
  50680. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  50681. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  50682. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  50683. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  50684. particleSystem.emitRate = parsedParticleSystem.emitRate;
  50685. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  50686. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  50687. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  50688. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  50689. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  50690. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  50691. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  50692. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  50693. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  50694. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  50695. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  50696. particleSystem.blendMode = parsedParticleSystem.blendMode;
  50697. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  50698. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  50699. particleSystem.spriteCellLoop = parsedParticleSystem.spriteCellLoop;
  50700. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  50701. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  50702. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  50703. if (!particleSystem.preventAutoStart) {
  50704. particleSystem.start();
  50705. }
  50706. return particleSystem;
  50707. };
  50708. /**
  50709. * Source color is added to the destination color without alpha affecting the result.
  50710. */
  50711. ParticleSystem.BLENDMODE_ONEONE = 0;
  50712. /**
  50713. * Blend current color and particle color using particle’s alpha.
  50714. */
  50715. ParticleSystem.BLENDMODE_STANDARD = 1;
  50716. return ParticleSystem;
  50717. }());
  50718. BABYLON.ParticleSystem = ParticleSystem;
  50719. })(BABYLON || (BABYLON = {}));
  50720. //# sourceMappingURL=babylon.particleSystem.js.map
  50721. var BABYLON;
  50722. (function (BABYLON) {
  50723. /**
  50724. * Particle emitter emitting particles from the inside of a box.
  50725. * It emits the particles randomly between 2 given directions.
  50726. */
  50727. var BoxParticleEmitter = /** @class */ (function () {
  50728. // to be updated like the rest of emitters when breaking changes.
  50729. // all property should be come public variables and passed through constructor.
  50730. /**
  50731. * Creates a new instance of @see BoxParticleEmitter
  50732. * @param _particleSystem the particle system associated with the emitter
  50733. */
  50734. function BoxParticleEmitter(_particleSystem) {
  50735. this._particleSystem = _particleSystem;
  50736. }
  50737. Object.defineProperty(BoxParticleEmitter.prototype, "direction1", {
  50738. /**
  50739. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  50740. */
  50741. get: function () {
  50742. return this._particleSystem.direction1;
  50743. },
  50744. /**
  50745. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  50746. */
  50747. set: function (value) {
  50748. this._particleSystem.direction1 = value;
  50749. },
  50750. enumerable: true,
  50751. configurable: true
  50752. });
  50753. Object.defineProperty(BoxParticleEmitter.prototype, "direction2", {
  50754. /**
  50755. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  50756. */
  50757. get: function () {
  50758. return this._particleSystem.direction2;
  50759. },
  50760. /**
  50761. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  50762. */
  50763. set: function (value) {
  50764. this._particleSystem.direction2 = value;
  50765. },
  50766. enumerable: true,
  50767. configurable: true
  50768. });
  50769. Object.defineProperty(BoxParticleEmitter.prototype, "minEmitBox", {
  50770. /**
  50771. * 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.
  50772. */
  50773. get: function () {
  50774. return this._particleSystem.minEmitBox;
  50775. },
  50776. /**
  50777. * 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.
  50778. */
  50779. set: function (value) {
  50780. this._particleSystem.minEmitBox = value;
  50781. },
  50782. enumerable: true,
  50783. configurable: true
  50784. });
  50785. Object.defineProperty(BoxParticleEmitter.prototype, "maxEmitBox", {
  50786. /**
  50787. * 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.
  50788. */
  50789. get: function () {
  50790. return this._particleSystem.maxEmitBox;
  50791. },
  50792. /**
  50793. * 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.
  50794. */
  50795. set: function (value) {
  50796. this._particleSystem.maxEmitBox = value;
  50797. },
  50798. enumerable: true,
  50799. configurable: true
  50800. });
  50801. /**
  50802. * Called by the particle System when the direction is computed for the created particle.
  50803. * @param emitPower is the power of the particle (speed)
  50804. * @param worldMatrix is the world matrix of the particle system
  50805. * @param directionToUpdate is the direction vector to update with the result
  50806. * @param particle is the particle we are computed the direction for
  50807. */
  50808. BoxParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  50809. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  50810. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  50811. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  50812. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  50813. };
  50814. /**
  50815. * Called by the particle System when the position is computed for the created particle.
  50816. * @param worldMatrix is the world matrix of the particle system
  50817. * @param positionToUpdate is the position vector to update with the result
  50818. * @param particle is the particle we are computed the position for
  50819. */
  50820. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  50821. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  50822. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  50823. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  50824. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  50825. };
  50826. /**
  50827. * Clones the current emitter and returns a copy of it
  50828. * @returns the new emitter
  50829. */
  50830. BoxParticleEmitter.prototype.clone = function () {
  50831. var newOne = new BoxParticleEmitter(this._particleSystem);
  50832. BABYLON.Tools.DeepCopy(this, newOne);
  50833. return newOne;
  50834. };
  50835. return BoxParticleEmitter;
  50836. }());
  50837. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  50838. })(BABYLON || (BABYLON = {}));
  50839. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  50840. var BABYLON;
  50841. (function (BABYLON) {
  50842. /**
  50843. * Particle emitter emitting particles from the inside of a cone.
  50844. * It emits the particles alongside the cone volume from the base to the particle.
  50845. * The emission direction might be randomized.
  50846. */
  50847. var ConeParticleEmitter = /** @class */ (function () {
  50848. /**
  50849. * Creates a new instance of @see ConeParticleEmitter
  50850. * @param radius the radius of the emission cone
  50851. * @param angles the cone base angle
  50852. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  50853. */
  50854. function ConeParticleEmitter(radius,
  50855. /**
  50856. * The radius of the emission cone.
  50857. */
  50858. angle,
  50859. /**
  50860. * The cone base angle.
  50861. */
  50862. directionRandomizer) {
  50863. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  50864. this.angle = angle;
  50865. this.directionRandomizer = directionRandomizer;
  50866. this.radius = radius;
  50867. }
  50868. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  50869. /**
  50870. * Gets the radius of the emission cone.
  50871. */
  50872. get: function () {
  50873. return this._radius;
  50874. },
  50875. /**
  50876. * Sets the radius of the emission cone.
  50877. */
  50878. set: function (value) {
  50879. this._radius = value;
  50880. if (this.angle !== 0) {
  50881. this._height = value / Math.tan(this.angle / 2);
  50882. }
  50883. else {
  50884. this._height = 1;
  50885. }
  50886. },
  50887. enumerable: true,
  50888. configurable: true
  50889. });
  50890. /**
  50891. * Called by the particle System when the direction is computed for the created particle.
  50892. * @param emitPower is the power of the particle (speed)
  50893. * @param worldMatrix is the world matrix of the particle system
  50894. * @param directionToUpdate is the direction vector to update with the result
  50895. * @param particle is the particle we are computed the direction for
  50896. */
  50897. ConeParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  50898. if (this.angle === 0) {
  50899. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, emitPower, 0, worldMatrix, directionToUpdate);
  50900. }
  50901. else {
  50902. // measure the direction Vector from the emitter to the particle.
  50903. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  50904. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  50905. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  50906. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  50907. direction.x += randX;
  50908. direction.y += randY;
  50909. direction.z += randZ;
  50910. direction.normalize();
  50911. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  50912. }
  50913. };
  50914. /**
  50915. * Called by the particle System when the position is computed for the created particle.
  50916. * @param worldMatrix is the world matrix of the particle system
  50917. * @param positionToUpdate is the position vector to update with the result
  50918. * @param particle is the particle we are computed the position for
  50919. */
  50920. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  50921. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  50922. var h = BABYLON.Scalar.RandomRange(0, 1);
  50923. // Better distribution in a cone at normal angles.
  50924. h = 1 - h * h;
  50925. var radius = BABYLON.Scalar.RandomRange(0, this._radius);
  50926. radius = radius * h / this._height;
  50927. var randX = radius * Math.sin(s);
  50928. var randZ = radius * Math.cos(s);
  50929. var randY = h;
  50930. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  50931. };
  50932. /**
  50933. * Clones the current emitter and returns a copy of it
  50934. * @returns the new emitter
  50935. */
  50936. ConeParticleEmitter.prototype.clone = function () {
  50937. var newOne = new ConeParticleEmitter(this.radius, this.angle, this.directionRandomizer);
  50938. BABYLON.Tools.DeepCopy(this, newOne);
  50939. return newOne;
  50940. };
  50941. return ConeParticleEmitter;
  50942. }());
  50943. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  50944. })(BABYLON || (BABYLON = {}));
  50945. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  50946. var BABYLON;
  50947. (function (BABYLON) {
  50948. /**
  50949. * Particle emitter emitting particles from the inside of a sphere.
  50950. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  50951. */
  50952. var SphereParticleEmitter = /** @class */ (function () {
  50953. /**
  50954. * Creates a new instance of @see SphereParticleEmitter
  50955. * @param radius the radius of the emission sphere
  50956. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  50957. */
  50958. function SphereParticleEmitter(
  50959. /**
  50960. * The radius of the emission sphere.
  50961. */
  50962. radius,
  50963. /**
  50964. * How much to randomize the particle direction [0-1].
  50965. */
  50966. directionRandomizer) {
  50967. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  50968. this.radius = radius;
  50969. this.directionRandomizer = directionRandomizer;
  50970. }
  50971. /**
  50972. * Called by the particle System when the direction is computed for the created particle.
  50973. * @param emitPower is the power of the particle (speed)
  50974. * @param worldMatrix is the world matrix of the particle system
  50975. * @param directionToUpdate is the direction vector to update with the result
  50976. * @param particle is the particle we are computed the direction for
  50977. */
  50978. SphereParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  50979. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  50980. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  50981. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  50982. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  50983. direction.x += randX;
  50984. direction.y += randY;
  50985. direction.z += randZ;
  50986. direction.normalize();
  50987. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  50988. };
  50989. /**
  50990. * Called by the particle System when the position is computed for the created particle.
  50991. * @param worldMatrix is the world matrix of the particle system
  50992. * @param positionToUpdate is the position vector to update with the result
  50993. * @param particle is the particle we are computed the position for
  50994. */
  50995. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  50996. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  50997. var theta = BABYLON.Scalar.RandomRange(0, Math.PI);
  50998. var randX = this.radius * Math.cos(phi) * Math.sin(theta);
  50999. var randY = this.radius * Math.cos(theta);
  51000. var randZ = this.radius * Math.sin(phi) * Math.sin(theta);
  51001. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  51002. };
  51003. /**
  51004. * Clones the current emitter and returns a copy of it
  51005. * @returns the new emitter
  51006. */
  51007. SphereParticleEmitter.prototype.clone = function () {
  51008. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  51009. BABYLON.Tools.DeepCopy(this, newOne);
  51010. return newOne;
  51011. };
  51012. return SphereParticleEmitter;
  51013. }());
  51014. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  51015. /**
  51016. * Particle emitter emitting particles from the inside of a sphere.
  51017. * It emits the particles randomly between two vectors.
  51018. */
  51019. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  51020. __extends(SphereDirectedParticleEmitter, _super);
  51021. /**
  51022. * Creates a new instance of @see SphereDirectedParticleEmitter
  51023. * @param radius the radius of the emission sphere
  51024. * @param direction1 the min limit of the emission direction
  51025. * @param direction2 the max limit of the emission direction
  51026. */
  51027. function SphereDirectedParticleEmitter(radius,
  51028. /**
  51029. * The min limit of the emission direction.
  51030. */
  51031. direction1,
  51032. /**
  51033. * The max limit of the emission direction.
  51034. */
  51035. direction2) {
  51036. var _this = _super.call(this, radius) || this;
  51037. _this.direction1 = direction1;
  51038. _this.direction2 = direction2;
  51039. return _this;
  51040. }
  51041. /**
  51042. * Called by the particle System when the direction is computed for the created particle.
  51043. * @param emitPower is the power of the particle (speed)
  51044. * @param worldMatrix is the world matrix of the particle system
  51045. * @param directionToUpdate is the direction vector to update with the result
  51046. * @param particle is the particle we are computed the direction for
  51047. */
  51048. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  51049. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  51050. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  51051. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  51052. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  51053. };
  51054. /**
  51055. * Clones the current emitter and returns a copy of it
  51056. * @returns the new emitter
  51057. */
  51058. SphereDirectedParticleEmitter.prototype.clone = function () {
  51059. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  51060. BABYLON.Tools.DeepCopy(this, newOne);
  51061. return newOne;
  51062. };
  51063. return SphereDirectedParticleEmitter;
  51064. }(SphereParticleEmitter));
  51065. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  51066. })(BABYLON || (BABYLON = {}));
  51067. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  51068. //# sourceMappingURL=babylon.iParticleEmitterType.js.map
  51069. var BABYLON;
  51070. (function (BABYLON) {
  51071. /**
  51072. * Represents one particle of a solid particle system.
  51073. * @see SolidParticleSystem
  51074. */
  51075. var SolidParticle = /** @class */ (function () {
  51076. /**
  51077. * Creates a Solid Particle object.
  51078. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  51079. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  51080. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  51081. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  51082. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  51083. * @param shapeId (integer) is the model shape identifier in the SPS.
  51084. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  51085. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  51086. */
  51087. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  51088. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  51089. /**
  51090. * particle global index
  51091. */
  51092. this.idx = 0;
  51093. /**
  51094. * The color of the particle
  51095. */
  51096. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  51097. /**
  51098. * The world space position of the particle.
  51099. */
  51100. this.position = BABYLON.Vector3.Zero();
  51101. /**
  51102. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  51103. */
  51104. this.rotation = BABYLON.Vector3.Zero();
  51105. /**
  51106. * The scaling of the particle.
  51107. */
  51108. this.scaling = BABYLON.Vector3.One();
  51109. /**
  51110. * The uvs of the particle.
  51111. */
  51112. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  51113. /**
  51114. * The current speed of the particle.
  51115. */
  51116. this.velocity = BABYLON.Vector3.Zero();
  51117. /**
  51118. * The pivot point in the particle local space.
  51119. */
  51120. this.pivot = BABYLON.Vector3.Zero();
  51121. /**
  51122. * Must the particle be translated from its pivot point in its local space ?
  51123. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  51124. * Default : false
  51125. */
  51126. this.translateFromPivot = false;
  51127. /**
  51128. * Is the particle active or not ?
  51129. */
  51130. this.alive = true;
  51131. /**
  51132. * Is the particle visible or not ?
  51133. */
  51134. this.isVisible = true;
  51135. /**
  51136. * Index of this particle in the global "positions" array (Internal use)
  51137. */
  51138. this._pos = 0;
  51139. /**
  51140. * Index of this particle in the global "indices" array (Internal use)
  51141. */
  51142. this._ind = 0;
  51143. /**
  51144. * ModelShape id of this particle
  51145. */
  51146. this.shapeId = 0;
  51147. /**
  51148. * Index of the particle in its shape id (Internal use)
  51149. */
  51150. this.idxInShape = 0;
  51151. /**
  51152. * Still set as invisible in order to skip useless computations (Internal use)
  51153. */
  51154. this._stillInvisible = false;
  51155. /**
  51156. * Last computed particle rotation matrix
  51157. */
  51158. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  51159. this.idx = particleIndex;
  51160. this._pos = positionIndex;
  51161. this._ind = indiceIndex;
  51162. this._model = model;
  51163. this.shapeId = shapeId;
  51164. this.idxInShape = idxInShape;
  51165. this._sps = sps;
  51166. if (modelBoundingInfo) {
  51167. this._modelBoundingInfo = modelBoundingInfo;
  51168. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  51169. }
  51170. }
  51171. Object.defineProperty(SolidParticle.prototype, "scale", {
  51172. /**
  51173. * Legacy support, changed scale to scaling
  51174. */
  51175. get: function () {
  51176. return this.scaling;
  51177. },
  51178. /**
  51179. * Legacy support, changed scale to scaling
  51180. */
  51181. set: function (scale) {
  51182. this.scaling = scale;
  51183. },
  51184. enumerable: true,
  51185. configurable: true
  51186. });
  51187. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  51188. /**
  51189. * Legacy support, changed quaternion to rotationQuaternion
  51190. */
  51191. get: function () {
  51192. return this.rotationQuaternion;
  51193. },
  51194. /**
  51195. * Legacy support, changed quaternion to rotationQuaternion
  51196. */
  51197. set: function (q) {
  51198. this.rotationQuaternion = q;
  51199. },
  51200. enumerable: true,
  51201. configurable: true
  51202. });
  51203. /**
  51204. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  51205. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  51206. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  51207. * @returns true if it intersects
  51208. */
  51209. SolidParticle.prototype.intersectsMesh = function (target) {
  51210. if (!this._boundingInfo || !target._boundingInfo) {
  51211. return false;
  51212. }
  51213. if (this._sps._bSphereOnly) {
  51214. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  51215. }
  51216. return this._boundingInfo.intersects(target._boundingInfo, false);
  51217. };
  51218. return SolidParticle;
  51219. }());
  51220. BABYLON.SolidParticle = SolidParticle;
  51221. /**
  51222. * Represents the shape of the model used by one particle of a solid particle system.
  51223. * SPS internal tool, don't use it manually.
  51224. * @see SolidParticleSystem
  51225. */
  51226. var ModelShape = /** @class */ (function () {
  51227. /**
  51228. * 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.
  51229. * SPS internal tool, don't use it manually.
  51230. * @ignore
  51231. */
  51232. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  51233. /**
  51234. * length of the shape in the model indices array (internal use)
  51235. */
  51236. this._indicesLength = 0;
  51237. this.shapeID = id;
  51238. this._shape = shape;
  51239. this._indicesLength = indicesLength;
  51240. this._shapeUV = shapeUV;
  51241. this._positionFunction = posFunction;
  51242. this._vertexFunction = vtxFunction;
  51243. }
  51244. return ModelShape;
  51245. }());
  51246. BABYLON.ModelShape = ModelShape;
  51247. /**
  51248. * Represents a Depth Sorted Particle in the solid particle system.
  51249. * @see SolidParticleSystem
  51250. */
  51251. var DepthSortedParticle = /** @class */ (function () {
  51252. function DepthSortedParticle() {
  51253. /**
  51254. * Index of the particle in the "indices" array
  51255. */
  51256. this.ind = 0;
  51257. /**
  51258. * Length of the particle shape in the "indices" array
  51259. */
  51260. this.indicesLength = 0;
  51261. /**
  51262. * Squared distance from the particle to the camera
  51263. */
  51264. this.sqDistance = 0.0;
  51265. }
  51266. return DepthSortedParticle;
  51267. }());
  51268. BABYLON.DepthSortedParticle = DepthSortedParticle;
  51269. })(BABYLON || (BABYLON = {}));
  51270. //# sourceMappingURL=babylon.solidParticle.js.map
  51271. var BABYLON;
  51272. (function (BABYLON) {
  51273. /**
  51274. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  51275. *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.
  51276. * The SPS is also a particle system. It provides some methods to manage the particles.
  51277. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  51278. *
  51279. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  51280. */
  51281. var SolidParticleSystem = /** @class */ (function () {
  51282. /**
  51283. * Creates a SPS (Solid Particle System) object.
  51284. * @param name (String) is the SPS name, this will be the underlying mesh name.
  51285. * @param scene (Scene) is the scene in which the SPS is added.
  51286. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  51287. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  51288. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  51289. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  51290. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  51291. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  51292. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  51293. */
  51294. function SolidParticleSystem(name, scene, options) {
  51295. /**
  51296. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  51297. * Example : var p = SPS.particles[i];
  51298. */
  51299. this.particles = new Array();
  51300. /**
  51301. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  51302. */
  51303. this.nbParticles = 0;
  51304. /**
  51305. * If the particles must ever face the camera (default false). Useful for planar particles.
  51306. */
  51307. this.billboard = false;
  51308. /**
  51309. * Recompute normals when adding a shape
  51310. */
  51311. this.recomputeNormals = true;
  51312. /**
  51313. * This a counter ofr your own usage. It's not set by any SPS functions.
  51314. */
  51315. this.counter = 0;
  51316. /**
  51317. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  51318. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  51319. */
  51320. this.vars = {};
  51321. /**
  51322. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  51323. */
  51324. this._bSphereOnly = false;
  51325. /**
  51326. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  51327. */
  51328. this._bSphereRadiusFactor = 1.0;
  51329. this._positions = new Array();
  51330. this._indices = new Array();
  51331. this._normals = new Array();
  51332. this._colors = new Array();
  51333. this._uvs = new Array();
  51334. this._index = 0; // indices index
  51335. this._updatable = true;
  51336. this._pickable = false;
  51337. this._isVisibilityBoxLocked = false;
  51338. this._alwaysVisible = false;
  51339. this._depthSort = false;
  51340. this._shapeCounter = 0;
  51341. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  51342. this._color = new BABYLON.Color4(0, 0, 0, 0);
  51343. this._computeParticleColor = true;
  51344. this._computeParticleTexture = true;
  51345. this._computeParticleRotation = true;
  51346. this._computeParticleVertex = false;
  51347. this._computeBoundingBox = false;
  51348. this._depthSortParticles = true;
  51349. this._cam_axisZ = BABYLON.Vector3.Zero();
  51350. this._cam_axisY = BABYLON.Vector3.Zero();
  51351. this._cam_axisX = BABYLON.Vector3.Zero();
  51352. this._axisZ = BABYLON.Axis.Z;
  51353. this._camDir = BABYLON.Vector3.Zero();
  51354. this._camInvertedPosition = BABYLON.Vector3.Zero();
  51355. this._rotMatrix = new BABYLON.Matrix();
  51356. this._invertMatrix = new BABYLON.Matrix();
  51357. this._rotated = BABYLON.Vector3.Zero();
  51358. this._quaternion = new BABYLON.Quaternion();
  51359. this._vertex = BABYLON.Vector3.Zero();
  51360. this._normal = BABYLON.Vector3.Zero();
  51361. this._yaw = 0.0;
  51362. this._pitch = 0.0;
  51363. this._roll = 0.0;
  51364. this._halfroll = 0.0;
  51365. this._halfpitch = 0.0;
  51366. this._halfyaw = 0.0;
  51367. this._sinRoll = 0.0;
  51368. this._cosRoll = 0.0;
  51369. this._sinPitch = 0.0;
  51370. this._cosPitch = 0.0;
  51371. this._sinYaw = 0.0;
  51372. this._cosYaw = 0.0;
  51373. this._mustUnrotateFixedNormals = false;
  51374. this._minimum = BABYLON.Vector3.Zero();
  51375. this._maximum = BABYLON.Vector3.Zero();
  51376. this._minBbox = BABYLON.Vector3.Zero();
  51377. this._maxBbox = BABYLON.Vector3.Zero();
  51378. this._particlesIntersect = false;
  51379. this._depthSortFunction = function (p1, p2) {
  51380. return (p2.sqDistance - p1.sqDistance);
  51381. };
  51382. this._needs32Bits = false;
  51383. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  51384. this.name = name;
  51385. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  51386. this._camera = scene.activeCamera;
  51387. this._pickable = options ? options.isPickable : false;
  51388. this._depthSort = options ? options.enableDepthSort : false;
  51389. this._particlesIntersect = options ? options.particleIntersection : false;
  51390. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  51391. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  51392. if (options && options.updatable) {
  51393. this._updatable = options.updatable;
  51394. }
  51395. else {
  51396. this._updatable = true;
  51397. }
  51398. if (this._pickable) {
  51399. this.pickedParticles = [];
  51400. }
  51401. if (this._depthSort) {
  51402. this.depthSortedParticles = [];
  51403. }
  51404. }
  51405. /**
  51406. * Builds the SPS underlying mesh. Returns a standard Mesh.
  51407. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  51408. * @returns the created mesh
  51409. */
  51410. SolidParticleSystem.prototype.buildMesh = function () {
  51411. if (this.nbParticles === 0) {
  51412. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  51413. this.addShape(triangle, 1);
  51414. triangle.dispose();
  51415. }
  51416. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  51417. this._positions32 = new Float32Array(this._positions);
  51418. this._uvs32 = new Float32Array(this._uvs);
  51419. this._colors32 = new Float32Array(this._colors);
  51420. if (this.recomputeNormals) {
  51421. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  51422. }
  51423. this._normals32 = new Float32Array(this._normals);
  51424. this._fixedNormal32 = new Float32Array(this._normals);
  51425. if (this._mustUnrotateFixedNormals) {
  51426. this._unrotateFixedNormals();
  51427. }
  51428. var vertexData = new BABYLON.VertexData();
  51429. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  51430. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  51431. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  51432. if (this._uvs32) {
  51433. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  51434. ;
  51435. }
  51436. if (this._colors32) {
  51437. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  51438. }
  51439. var mesh = new BABYLON.Mesh(this.name, this._scene);
  51440. vertexData.applyToMesh(mesh, this._updatable);
  51441. this.mesh = mesh;
  51442. this.mesh.isPickable = this._pickable;
  51443. // free memory
  51444. if (!this._depthSort) {
  51445. this._indices = null;
  51446. }
  51447. this._positions = null;
  51448. this._normals = null;
  51449. this._uvs = null;
  51450. this._colors = null;
  51451. if (!this._updatable) {
  51452. this.particles.length = 0;
  51453. }
  51454. return mesh;
  51455. };
  51456. /**
  51457. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  51458. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  51459. * Thus the particles generated from `digest()` have their property `position` set yet.
  51460. * @param mesh ( Mesh ) is the mesh to be digested
  51461. * @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
  51462. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  51463. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  51464. * @returns the current SPS
  51465. */
  51466. SolidParticleSystem.prototype.digest = function (mesh, options) {
  51467. var size = (options && options.facetNb) || 1;
  51468. var number = (options && options.number) || 0;
  51469. var delta = (options && options.delta) || 0;
  51470. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  51471. var meshInd = mesh.getIndices();
  51472. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  51473. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  51474. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  51475. var f = 0; // facet counter
  51476. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  51477. // compute size from number
  51478. if (number) {
  51479. number = (number > totalFacets) ? totalFacets : number;
  51480. size = Math.round(totalFacets / number);
  51481. delta = 0;
  51482. }
  51483. else {
  51484. size = (size > totalFacets) ? totalFacets : size;
  51485. }
  51486. var facetPos = []; // submesh positions
  51487. var facetInd = []; // submesh indices
  51488. var facetUV = []; // submesh UV
  51489. var facetCol = []; // submesh colors
  51490. var barycenter = BABYLON.Vector3.Zero();
  51491. var sizeO = size;
  51492. while (f < totalFacets) {
  51493. size = sizeO + Math.floor((1 + delta) * Math.random());
  51494. if (f > totalFacets - size) {
  51495. size = totalFacets - f;
  51496. }
  51497. // reset temp arrays
  51498. facetPos.length = 0;
  51499. facetInd.length = 0;
  51500. facetUV.length = 0;
  51501. facetCol.length = 0;
  51502. // iterate over "size" facets
  51503. var fi = 0;
  51504. for (var j = f * 3; j < (f + size) * 3; j++) {
  51505. facetInd.push(fi);
  51506. var i = meshInd[j];
  51507. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  51508. if (meshUV) {
  51509. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  51510. }
  51511. if (meshCol) {
  51512. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  51513. }
  51514. fi++;
  51515. }
  51516. // create a model shape for each single particle
  51517. var idx = this.nbParticles;
  51518. var shape = this._posToShape(facetPos);
  51519. var shapeUV = this._uvsToShapeUV(facetUV);
  51520. // compute the barycenter of the shape
  51521. var v;
  51522. for (v = 0; v < shape.length; v++) {
  51523. barycenter.addInPlace(shape[v]);
  51524. }
  51525. barycenter.scaleInPlace(1 / shape.length);
  51526. // shift the shape from its barycenter to the origin
  51527. for (v = 0; v < shape.length; v++) {
  51528. shape[v].subtractInPlace(barycenter);
  51529. }
  51530. var bInfo;
  51531. if (this._particlesIntersect) {
  51532. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  51533. }
  51534. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  51535. // add the particle in the SPS
  51536. var currentPos = this._positions.length;
  51537. var currentInd = this._indices.length;
  51538. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  51539. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  51540. // initialize the particle position
  51541. this.particles[this.nbParticles].position.addInPlace(barycenter);
  51542. this._index += shape.length;
  51543. idx++;
  51544. this.nbParticles++;
  51545. this._shapeCounter++;
  51546. f += size;
  51547. }
  51548. return this;
  51549. };
  51550. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  51551. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  51552. var index = 0;
  51553. var idx = 0;
  51554. for (var p = 0; p < this.particles.length; p++) {
  51555. this._particle = this.particles[p];
  51556. this._shape = this._particle._model._shape;
  51557. if (this._particle.rotationQuaternion) {
  51558. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  51559. }
  51560. else {
  51561. this._yaw = this._particle.rotation.y;
  51562. this._pitch = this._particle.rotation.x;
  51563. this._roll = this._particle.rotation.z;
  51564. this._quaternionRotationYPR();
  51565. }
  51566. this._quaternionToRotationMatrix();
  51567. this._rotMatrix.invertToRef(this._invertMatrix);
  51568. for (var pt = 0; pt < this._shape.length; pt++) {
  51569. idx = index + pt * 3;
  51570. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  51571. this._fixedNormal32[idx] = this._normal.x;
  51572. this._fixedNormal32[idx + 1] = this._normal.y;
  51573. this._fixedNormal32[idx + 2] = this._normal.z;
  51574. }
  51575. index = idx + 3;
  51576. }
  51577. };
  51578. //reset copy
  51579. SolidParticleSystem.prototype._resetCopy = function () {
  51580. this._copy.position.x = 0;
  51581. this._copy.position.y = 0;
  51582. this._copy.position.z = 0;
  51583. this._copy.rotation.x = 0;
  51584. this._copy.rotation.y = 0;
  51585. this._copy.rotation.z = 0;
  51586. this._copy.rotationQuaternion = null;
  51587. this._copy.scaling.x = 1.0;
  51588. this._copy.scaling.y = 1.0;
  51589. this._copy.scaling.z = 1.0;
  51590. this._copy.uvs.x = 0;
  51591. this._copy.uvs.y = 0;
  51592. this._copy.uvs.z = 1.0;
  51593. this._copy.uvs.w = 1.0;
  51594. this._copy.color = null;
  51595. this._copy.translateFromPivot = false;
  51596. };
  51597. // _meshBuilder : inserts the shape model in the global SPS mesh
  51598. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  51599. var i;
  51600. var u = 0;
  51601. var c = 0;
  51602. var n = 0;
  51603. this._resetCopy();
  51604. if (options && options.positionFunction) {
  51605. options.positionFunction(this._copy, idx, idxInShape);
  51606. this._mustUnrotateFixedNormals = true;
  51607. }
  51608. if (this._copy.rotationQuaternion) {
  51609. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  51610. }
  51611. else {
  51612. this._yaw = this._copy.rotation.y;
  51613. this._pitch = this._copy.rotation.x;
  51614. this._roll = this._copy.rotation.z;
  51615. this._quaternionRotationYPR();
  51616. }
  51617. this._quaternionToRotationMatrix();
  51618. if (this._copy.translateFromPivot) {
  51619. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  51620. }
  51621. else {
  51622. this._pivotBackTranslation.copyFrom(this._copy.pivot);
  51623. }
  51624. for (i = 0; i < shape.length; i++) {
  51625. this._vertex.x = shape[i].x;
  51626. this._vertex.y = shape[i].y;
  51627. this._vertex.z = shape[i].z;
  51628. if (options && options.vertexFunction) {
  51629. options.vertexFunction(this._copy, this._vertex, i);
  51630. }
  51631. this._vertex.x *= this._copy.scaling.x;
  51632. this._vertex.y *= this._copy.scaling.y;
  51633. this._vertex.z *= this._copy.scaling.z;
  51634. this._vertex.x -= this._copy.pivot.x;
  51635. this._vertex.y -= this._copy.pivot.y;
  51636. this._vertex.z -= this._copy.pivot.z;
  51637. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  51638. this._rotated.addInPlace(this._pivotBackTranslation);
  51639. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  51640. if (meshUV) {
  51641. 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);
  51642. u += 2;
  51643. }
  51644. if (this._copy.color) {
  51645. this._color = this._copy.color;
  51646. }
  51647. else if (meshCol && meshCol[c] !== undefined) {
  51648. this._color.r = meshCol[c];
  51649. this._color.g = meshCol[c + 1];
  51650. this._color.b = meshCol[c + 2];
  51651. this._color.a = meshCol[c + 3];
  51652. }
  51653. else {
  51654. this._color.r = 1.0;
  51655. this._color.g = 1.0;
  51656. this._color.b = 1.0;
  51657. this._color.a = 1.0;
  51658. }
  51659. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  51660. c += 4;
  51661. if (!this.recomputeNormals && meshNor) {
  51662. this._normal.x = meshNor[n];
  51663. this._normal.y = meshNor[n + 1];
  51664. this._normal.z = meshNor[n + 2];
  51665. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  51666. normals.push(this._normal.x, this._normal.y, this._normal.z);
  51667. n += 3;
  51668. }
  51669. }
  51670. for (i = 0; i < meshInd.length; i++) {
  51671. var current_ind = p + meshInd[i];
  51672. indices.push(current_ind);
  51673. if (current_ind > 65535) {
  51674. this._needs32Bits = true;
  51675. }
  51676. }
  51677. if (this._pickable) {
  51678. var nbfaces = meshInd.length / 3;
  51679. for (i = 0; i < nbfaces; i++) {
  51680. this.pickedParticles.push({ idx: idx, faceId: i });
  51681. }
  51682. }
  51683. if (this._depthSort) {
  51684. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  51685. }
  51686. return this._copy;
  51687. };
  51688. // returns a shape array from positions array
  51689. SolidParticleSystem.prototype._posToShape = function (positions) {
  51690. var shape = [];
  51691. for (var i = 0; i < positions.length; i += 3) {
  51692. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  51693. }
  51694. return shape;
  51695. };
  51696. // returns a shapeUV array from a Vector4 uvs
  51697. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  51698. var shapeUV = [];
  51699. if (uvs) {
  51700. for (var i = 0; i < uvs.length; i++)
  51701. shapeUV.push(uvs[i]);
  51702. }
  51703. return shapeUV;
  51704. };
  51705. // adds a new particle object in the particles array
  51706. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  51707. if (bInfo === void 0) { bInfo = null; }
  51708. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  51709. this.particles.push(sp);
  51710. return sp;
  51711. };
  51712. /**
  51713. * Adds some particles to the SPS from the model shape. Returns the shape id.
  51714. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  51715. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  51716. * @param nb (positive integer) the number of particles to be created from this model
  51717. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  51718. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  51719. * @returns the number of shapes in the system
  51720. */
  51721. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  51722. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  51723. var meshInd = mesh.getIndices();
  51724. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  51725. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  51726. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  51727. var bbInfo;
  51728. if (this._particlesIntersect) {
  51729. bbInfo = mesh.getBoundingInfo();
  51730. }
  51731. var shape = this._posToShape(meshPos);
  51732. var shapeUV = this._uvsToShapeUV(meshUV);
  51733. var posfunc = options ? options.positionFunction : null;
  51734. var vtxfunc = options ? options.vertexFunction : null;
  51735. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  51736. // particles
  51737. var sp;
  51738. var currentCopy;
  51739. var idx = this.nbParticles;
  51740. for (var i = 0; i < nb; i++) {
  51741. var currentPos = this._positions.length;
  51742. var currentInd = this._indices.length;
  51743. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  51744. if (this._updatable) {
  51745. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  51746. sp.position.copyFrom(currentCopy.position);
  51747. sp.rotation.copyFrom(currentCopy.rotation);
  51748. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  51749. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  51750. }
  51751. if (currentCopy.color && sp.color) {
  51752. sp.color.copyFrom(currentCopy.color);
  51753. }
  51754. sp.scaling.copyFrom(currentCopy.scaling);
  51755. sp.uvs.copyFrom(currentCopy.uvs);
  51756. }
  51757. this._index += shape.length;
  51758. idx++;
  51759. }
  51760. this.nbParticles += nb;
  51761. this._shapeCounter++;
  51762. return this._shapeCounter - 1;
  51763. };
  51764. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  51765. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  51766. this._resetCopy();
  51767. if (particle._model._positionFunction) {
  51768. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  51769. }
  51770. if (this._copy.rotationQuaternion) {
  51771. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  51772. }
  51773. else {
  51774. this._yaw = this._copy.rotation.y;
  51775. this._pitch = this._copy.rotation.x;
  51776. this._roll = this._copy.rotation.z;
  51777. this._quaternionRotationYPR();
  51778. }
  51779. this._quaternionToRotationMatrix();
  51780. if (this._copy.translateFromPivot) {
  51781. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  51782. }
  51783. else {
  51784. this._pivotBackTranslation.copyFrom(this._copy.pivot);
  51785. }
  51786. this._shape = particle._model._shape;
  51787. for (var pt = 0; pt < this._shape.length; pt++) {
  51788. this._vertex.x = this._shape[pt].x;
  51789. this._vertex.y = this._shape[pt].y;
  51790. this._vertex.z = this._shape[pt].z;
  51791. if (particle._model._vertexFunction) {
  51792. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  51793. }
  51794. this._vertex.x *= this._copy.scaling.x;
  51795. this._vertex.y *= this._copy.scaling.y;
  51796. this._vertex.z *= this._copy.scaling.z;
  51797. this._vertex.x -= this._copy.pivot.x;
  51798. this._vertex.y -= this._copy.pivot.y;
  51799. this._vertex.z -= this._copy.pivot.z;
  51800. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  51801. this._rotated.addInPlace(this._pivotBackTranslation);
  51802. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  51803. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  51804. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  51805. }
  51806. particle.position.x = 0.0;
  51807. particle.position.y = 0.0;
  51808. particle.position.z = 0.0;
  51809. particle.rotation.x = 0.0;
  51810. particle.rotation.y = 0.0;
  51811. particle.rotation.z = 0.0;
  51812. particle.rotationQuaternion = null;
  51813. particle.scaling.x = 1.0;
  51814. particle.scaling.y = 1.0;
  51815. particle.scaling.z = 1.0;
  51816. };
  51817. /**
  51818. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  51819. * @returns the SPS.
  51820. */
  51821. SolidParticleSystem.prototype.rebuildMesh = function () {
  51822. for (var p = 0; p < this.particles.length; p++) {
  51823. this._rebuildParticle(this.particles[p]);
  51824. }
  51825. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  51826. return this;
  51827. };
  51828. /**
  51829. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  51830. * This method calls `updateParticle()` for each particle of the SPS.
  51831. * For an animated SPS, it is usually called within the render loop.
  51832. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  51833. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  51834. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  51835. * @returns the SPS.
  51836. */
  51837. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  51838. if (start === void 0) { start = 0; }
  51839. if (end === void 0) { end = this.nbParticles - 1; }
  51840. if (update === void 0) { update = true; }
  51841. if (!this._updatable) {
  51842. return this;
  51843. }
  51844. // custom beforeUpdate
  51845. this.beforeUpdateParticles(start, end, update);
  51846. this._cam_axisX.x = 1.0;
  51847. this._cam_axisX.y = 0.0;
  51848. this._cam_axisX.z = 0.0;
  51849. this._cam_axisY.x = 0.0;
  51850. this._cam_axisY.y = 1.0;
  51851. this._cam_axisY.z = 0.0;
  51852. this._cam_axisZ.x = 0.0;
  51853. this._cam_axisZ.y = 0.0;
  51854. this._cam_axisZ.z = 1.0;
  51855. // cases when the World Matrix is to be computed first
  51856. if (this.billboard || this._depthSort) {
  51857. this.mesh.computeWorldMatrix(true);
  51858. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  51859. }
  51860. // if the particles will always face the camera
  51861. if (this.billboard) {
  51862. // compute the camera position and un-rotate it by the current mesh rotation
  51863. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  51864. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  51865. this._cam_axisZ.normalize();
  51866. // same for camera up vector extracted from the cam view matrix
  51867. var view = this._camera.getViewMatrix(true);
  51868. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  51869. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  51870. this._cam_axisY.normalize();
  51871. this._cam_axisX.normalize();
  51872. }
  51873. // if depthSort, compute the camera global position in the mesh local system
  51874. if (this._depthSort) {
  51875. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  51876. }
  51877. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  51878. var idx = 0; // current position index in the global array positions32
  51879. var index = 0; // position start index in the global array positions32 of the current particle
  51880. var colidx = 0; // current color index in the global array colors32
  51881. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  51882. var uvidx = 0; // current uv index in the global array uvs32
  51883. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  51884. var pt = 0; // current index in the particle model shape
  51885. if (this.mesh.isFacetDataEnabled) {
  51886. this._computeBoundingBox = true;
  51887. }
  51888. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  51889. if (this._computeBoundingBox) {
  51890. if (start == 0 && end == this.nbParticles - 1) {
  51891. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  51892. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  51893. }
  51894. else {
  51895. if (this.mesh._boundingInfo) {
  51896. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  51897. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  51898. }
  51899. }
  51900. }
  51901. // particle loop
  51902. index = this.particles[start]._pos;
  51903. var vpos = (index / 3) | 0;
  51904. colorIndex = vpos * 4;
  51905. uvIndex = vpos * 2;
  51906. for (var p = start; p <= end; p++) {
  51907. this._particle = this.particles[p];
  51908. this._shape = this._particle._model._shape;
  51909. this._shapeUV = this._particle._model._shapeUV;
  51910. // call to custom user function to update the particle properties
  51911. this.updateParticle(this._particle);
  51912. // camera-particle distance for depth sorting
  51913. if (this._depthSort && this._depthSortParticles) {
  51914. var dsp = this.depthSortedParticles[p];
  51915. dsp.ind = this._particle._ind;
  51916. dsp.indicesLength = this._particle._model._indicesLength;
  51917. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  51918. }
  51919. // skip the computations for inactive or already invisible particles
  51920. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  51921. // increment indexes for the next particle
  51922. pt = this._shape.length;
  51923. index += pt * 3;
  51924. colorIndex += pt * 4;
  51925. uvIndex += pt * 2;
  51926. continue;
  51927. }
  51928. if (this._particle.isVisible) {
  51929. this._particle._stillInvisible = false; // un-mark permanent invisibility
  51930. // particle rotation matrix
  51931. if (this.billboard) {
  51932. this._particle.rotation.x = 0.0;
  51933. this._particle.rotation.y = 0.0;
  51934. }
  51935. if (this._computeParticleRotation || this.billboard) {
  51936. if (this._particle.rotationQuaternion) {
  51937. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  51938. }
  51939. else {
  51940. this._yaw = this._particle.rotation.y;
  51941. this._pitch = this._particle.rotation.x;
  51942. this._roll = this._particle.rotation.z;
  51943. this._quaternionRotationYPR();
  51944. }
  51945. this._quaternionToRotationMatrix();
  51946. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  51947. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  51948. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  51949. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  51950. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  51951. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  51952. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  51953. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  51954. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  51955. }
  51956. if (this._particle.translateFromPivot) {
  51957. this._pivotBackTranslation.x = 0.0;
  51958. this._pivotBackTranslation.y = 0.0;
  51959. this._pivotBackTranslation.z = 0.0;
  51960. }
  51961. else {
  51962. this._pivotBackTranslation.x = this._particle.pivot.x;
  51963. this._pivotBackTranslation.y = this._particle.pivot.y;
  51964. this._pivotBackTranslation.z = this._particle.pivot.z;
  51965. }
  51966. // particle vertex loop
  51967. for (pt = 0; pt < this._shape.length; pt++) {
  51968. idx = index + pt * 3;
  51969. colidx = colorIndex + pt * 4;
  51970. uvidx = uvIndex + pt * 2;
  51971. this._vertex.x = this._shape[pt].x;
  51972. this._vertex.y = this._shape[pt].y;
  51973. this._vertex.z = this._shape[pt].z;
  51974. if (this._computeParticleVertex) {
  51975. this.updateParticleVertex(this._particle, this._vertex, pt);
  51976. }
  51977. // positions
  51978. this._vertex.x *= this._particle.scaling.x;
  51979. this._vertex.y *= this._particle.scaling.y;
  51980. this._vertex.z *= this._particle.scaling.z;
  51981. this._vertex.x -= this._particle.pivot.x;
  51982. this._vertex.y -= this._particle.pivot.y;
  51983. this._vertex.z -= this._particle.pivot.z;
  51984. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  51985. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  51986. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  51987. this._rotated.x += this._pivotBackTranslation.x;
  51988. this._rotated.y += this._pivotBackTranslation.y;
  51989. this._rotated.z += this._pivotBackTranslation.z;
  51990. this._positions32[idx] = this._particle.position.x + this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  51991. this._positions32[idx + 1] = this._particle.position.y + this._cam_axisX.y * this._rotated.x + this._cam_axisY.y * this._rotated.y + this._cam_axisZ.y * this._rotated.z;
  51992. this._positions32[idx + 2] = this._particle.position.z + this._cam_axisX.z * this._rotated.x + this._cam_axisY.z * this._rotated.y + this._cam_axisZ.z * this._rotated.z;
  51993. if (this._computeBoundingBox) {
  51994. if (this._positions32[idx] < this._minimum.x) {
  51995. this._minimum.x = this._positions32[idx];
  51996. }
  51997. if (this._positions32[idx] > this._maximum.x) {
  51998. this._maximum.x = this._positions32[idx];
  51999. }
  52000. if (this._positions32[idx + 1] < this._minimum.y) {
  52001. this._minimum.y = this._positions32[idx + 1];
  52002. }
  52003. if (this._positions32[idx + 1] > this._maximum.y) {
  52004. this._maximum.y = this._positions32[idx + 1];
  52005. }
  52006. if (this._positions32[idx + 2] < this._minimum.z) {
  52007. this._minimum.z = this._positions32[idx + 2];
  52008. }
  52009. if (this._positions32[idx + 2] > this._maximum.z) {
  52010. this._maximum.z = this._positions32[idx + 2];
  52011. }
  52012. }
  52013. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  52014. if (!this._computeParticleVertex) {
  52015. this._normal.x = this._fixedNormal32[idx];
  52016. this._normal.y = this._fixedNormal32[idx + 1];
  52017. this._normal.z = this._fixedNormal32[idx + 2];
  52018. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  52019. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  52020. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  52021. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  52022. 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;
  52023. 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;
  52024. }
  52025. if (this._computeParticleColor && this._particle.color) {
  52026. this._colors32[colidx] = this._particle.color.r;
  52027. this._colors32[colidx + 1] = this._particle.color.g;
  52028. this._colors32[colidx + 2] = this._particle.color.b;
  52029. this._colors32[colidx + 3] = this._particle.color.a;
  52030. }
  52031. if (this._computeParticleTexture) {
  52032. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  52033. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  52034. }
  52035. }
  52036. }
  52037. else {
  52038. this._particle._stillInvisible = true; // mark the particle as invisible
  52039. for (pt = 0; pt < this._shape.length; pt++) {
  52040. idx = index + pt * 3;
  52041. colidx = colorIndex + pt * 4;
  52042. uvidx = uvIndex + pt * 2;
  52043. this._positions32[idx] = 0.0;
  52044. this._positions32[idx + 1] = 0.0;
  52045. this._positions32[idx + 2] = 0.0;
  52046. this._normals32[idx] = 0.0;
  52047. this._normals32[idx + 1] = 0.0;
  52048. this._normals32[idx + 2] = 0.0;
  52049. if (this._computeParticleColor && this._particle.color) {
  52050. this._colors32[colidx] = this._particle.color.r;
  52051. this._colors32[colidx + 1] = this._particle.color.g;
  52052. this._colors32[colidx + 2] = this._particle.color.b;
  52053. this._colors32[colidx + 3] = this._particle.color.a;
  52054. }
  52055. if (this._computeParticleTexture) {
  52056. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  52057. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  52058. }
  52059. }
  52060. }
  52061. // if the particle intersections must be computed : update the bbInfo
  52062. if (this._particlesIntersect) {
  52063. var bInfo = this._particle._boundingInfo;
  52064. var bBox = bInfo.boundingBox;
  52065. var bSphere = bInfo.boundingSphere;
  52066. if (!this._bSphereOnly) {
  52067. // place, scale and rotate the particle bbox within the SPS local system, then update it
  52068. for (var b = 0; b < bBox.vectors.length; b++) {
  52069. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  52070. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  52071. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  52072. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  52073. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  52074. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  52075. 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;
  52076. 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;
  52077. 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;
  52078. }
  52079. bBox._update(this.mesh._worldMatrix);
  52080. }
  52081. // place and scale the particle bouding sphere in the SPS local system, then update it
  52082. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  52083. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  52084. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  52085. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  52086. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  52087. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  52088. bSphere.center.x = this._particle.position.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  52089. bSphere.center.y = this._particle.position.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  52090. bSphere.center.z = this._particle.position.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  52091. 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));
  52092. bSphere._update(this.mesh._worldMatrix);
  52093. }
  52094. // increment indexes for the next particle
  52095. index = idx + 3;
  52096. colorIndex = colidx + 4;
  52097. uvIndex = uvidx + 2;
  52098. }
  52099. // if the VBO must be updated
  52100. if (update) {
  52101. if (this._computeParticleColor) {
  52102. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  52103. }
  52104. if (this._computeParticleTexture) {
  52105. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  52106. }
  52107. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  52108. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  52109. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  52110. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  52111. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  52112. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  52113. for (var i = 0; i < this._normals32.length; i++) {
  52114. this._fixedNormal32[i] = this._normals32[i];
  52115. }
  52116. }
  52117. if (!this.mesh.areNormalsFrozen) {
  52118. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  52119. }
  52120. }
  52121. if (this._depthSort && this._depthSortParticles) {
  52122. this.depthSortedParticles.sort(this._depthSortFunction);
  52123. var dspl = this.depthSortedParticles.length;
  52124. var sorted = 0;
  52125. var lind = 0;
  52126. var sind = 0;
  52127. var sid = 0;
  52128. for (sorted = 0; sorted < dspl; sorted++) {
  52129. lind = this.depthSortedParticles[sorted].indicesLength;
  52130. sind = this.depthSortedParticles[sorted].ind;
  52131. for (var i = 0; i < lind; i++) {
  52132. this._indices32[sid] = this._indices[sind + i];
  52133. sid++;
  52134. }
  52135. }
  52136. this.mesh.updateIndices(this._indices32);
  52137. }
  52138. }
  52139. if (this._computeBoundingBox) {
  52140. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  52141. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  52142. }
  52143. this.afterUpdateParticles(start, end, update);
  52144. return this;
  52145. };
  52146. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  52147. this._halfroll = this._roll * 0.5;
  52148. this._halfpitch = this._pitch * 0.5;
  52149. this._halfyaw = this._yaw * 0.5;
  52150. this._sinRoll = Math.sin(this._halfroll);
  52151. this._cosRoll = Math.cos(this._halfroll);
  52152. this._sinPitch = Math.sin(this._halfpitch);
  52153. this._cosPitch = Math.cos(this._halfpitch);
  52154. this._sinYaw = Math.sin(this._halfyaw);
  52155. this._cosYaw = Math.cos(this._halfyaw);
  52156. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  52157. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  52158. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  52159. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  52160. };
  52161. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  52162. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  52163. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  52164. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  52165. this._rotMatrix.m[3] = 0;
  52166. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  52167. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  52168. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  52169. this._rotMatrix.m[7] = 0;
  52170. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  52171. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  52172. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  52173. this._rotMatrix.m[11] = 0;
  52174. this._rotMatrix.m[12] = 0;
  52175. this._rotMatrix.m[13] = 0;
  52176. this._rotMatrix.m[14] = 0;
  52177. this._rotMatrix.m[15] = 1.0;
  52178. };
  52179. /**
  52180. * Disposes the SPS.
  52181. */
  52182. SolidParticleSystem.prototype.dispose = function () {
  52183. this.mesh.dispose();
  52184. this.vars = null;
  52185. // drop references to internal big arrays for the GC
  52186. this._positions = null;
  52187. this._indices = null;
  52188. this._normals = null;
  52189. this._uvs = null;
  52190. this._colors = null;
  52191. this._indices32 = null;
  52192. this._positions32 = null;
  52193. this._normals32 = null;
  52194. this._fixedNormal32 = null;
  52195. this._uvs32 = null;
  52196. this._colors32 = null;
  52197. this.pickedParticles = null;
  52198. };
  52199. /**
  52200. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  52201. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  52202. * @returns the SPS.
  52203. */
  52204. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  52205. if (!this._isVisibilityBoxLocked) {
  52206. this.mesh.refreshBoundingInfo();
  52207. }
  52208. return this;
  52209. };
  52210. /**
  52211. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  52212. * @param size the size (float) of the visibility box
  52213. * note : this doesn't lock the SPS mesh bounding box.
  52214. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  52215. */
  52216. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  52217. var vis = size / 2;
  52218. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  52219. };
  52220. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  52221. /**
  52222. * Gets whether the SPS as always visible or not
  52223. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  52224. */
  52225. get: function () {
  52226. return this._alwaysVisible;
  52227. },
  52228. /**
  52229. * Sets the SPS as always visible or not
  52230. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  52231. */
  52232. set: function (val) {
  52233. this._alwaysVisible = val;
  52234. this.mesh.alwaysSelectAsActiveMesh = val;
  52235. },
  52236. enumerable: true,
  52237. configurable: true
  52238. });
  52239. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  52240. /**
  52241. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  52242. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  52243. */
  52244. get: function () {
  52245. return this._isVisibilityBoxLocked;
  52246. },
  52247. /**
  52248. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  52249. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  52250. */
  52251. set: function (val) {
  52252. this._isVisibilityBoxLocked = val;
  52253. var boundingInfo = this.mesh.getBoundingInfo();
  52254. boundingInfo.isLocked = val;
  52255. },
  52256. enumerable: true,
  52257. configurable: true
  52258. });
  52259. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  52260. /**
  52261. * Gets if `setParticles()` computes the particle rotations or not.
  52262. * Default value : true. The SPS is faster when it's set to false.
  52263. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  52264. */
  52265. get: function () {
  52266. return this._computeParticleRotation;
  52267. },
  52268. /**
  52269. * Tells to `setParticles()` to compute the particle rotations or not.
  52270. * Default value : true. The SPS is faster when it's set to false.
  52271. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  52272. */
  52273. set: function (val) {
  52274. this._computeParticleRotation = val;
  52275. },
  52276. enumerable: true,
  52277. configurable: true
  52278. });
  52279. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  52280. /**
  52281. * Gets if `setParticles()` computes the particle colors or not.
  52282. * Default value : true. The SPS is faster when it's set to false.
  52283. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  52284. */
  52285. get: function () {
  52286. return this._computeParticleColor;
  52287. },
  52288. /**
  52289. * Tells to `setParticles()` to compute the particle colors or not.
  52290. * Default value : true. The SPS is faster when it's set to false.
  52291. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  52292. */
  52293. set: function (val) {
  52294. this._computeParticleColor = val;
  52295. },
  52296. enumerable: true,
  52297. configurable: true
  52298. });
  52299. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  52300. /**
  52301. * Gets if `setParticles()` computes the particle textures or not.
  52302. * Default value : true. The SPS is faster when it's set to false.
  52303. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  52304. */
  52305. get: function () {
  52306. return this._computeParticleTexture;
  52307. },
  52308. set: function (val) {
  52309. this._computeParticleTexture = val;
  52310. },
  52311. enumerable: true,
  52312. configurable: true
  52313. });
  52314. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  52315. /**
  52316. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  52317. * Default value : false. The SPS is faster when it's set to false.
  52318. * Note : the particle custom vertex positions aren't stored values.
  52319. */
  52320. get: function () {
  52321. return this._computeParticleVertex;
  52322. },
  52323. /**
  52324. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  52325. * Default value : false. The SPS is faster when it's set to false.
  52326. * Note : the particle custom vertex positions aren't stored values.
  52327. */
  52328. set: function (val) {
  52329. this._computeParticleVertex = val;
  52330. },
  52331. enumerable: true,
  52332. configurable: true
  52333. });
  52334. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  52335. /**
  52336. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  52337. */
  52338. get: function () {
  52339. return this._computeBoundingBox;
  52340. },
  52341. /**
  52342. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  52343. */
  52344. set: function (val) {
  52345. this._computeBoundingBox = val;
  52346. },
  52347. enumerable: true,
  52348. configurable: true
  52349. });
  52350. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  52351. /**
  52352. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  52353. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  52354. * Default : `true`
  52355. */
  52356. get: function () {
  52357. return this._depthSortParticles;
  52358. },
  52359. /**
  52360. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  52361. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  52362. * Default : `true`
  52363. */
  52364. set: function (val) {
  52365. this._depthSortParticles = val;
  52366. },
  52367. enumerable: true,
  52368. configurable: true
  52369. });
  52370. // =======================================================================
  52371. // Particle behavior logic
  52372. // these following methods may be overwritten by the user to fit his needs
  52373. /**
  52374. * This function does nothing. It may be overwritten to set all the particle first values.
  52375. * The SPS doesn't call this function, you may have to call it by your own.
  52376. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  52377. */
  52378. SolidParticleSystem.prototype.initParticles = function () {
  52379. };
  52380. /**
  52381. * This function does nothing. It may be overwritten to recycle a particle.
  52382. * The SPS doesn't call this function, you may have to call it by your own.
  52383. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  52384. * @param particle The particle to recycle
  52385. * @returns the recycled particle
  52386. */
  52387. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  52388. return particle;
  52389. };
  52390. /**
  52391. * Updates a particle : this function should be overwritten by the user.
  52392. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  52393. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  52394. * @example : just set a particle position or velocity and recycle conditions
  52395. * @param particle The particle to update
  52396. * @returns the updated particle
  52397. */
  52398. SolidParticleSystem.prototype.updateParticle = function (particle) {
  52399. return particle;
  52400. };
  52401. /**
  52402. * Updates a vertex of a particle : it can be overwritten by the user.
  52403. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  52404. * @param particle the current particle
  52405. * @param vertex the current index of the current particle
  52406. * @param pt the index of the current vertex in the particle shape
  52407. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  52408. * @example : just set a vertex particle position
  52409. * @returns the updated vertex
  52410. */
  52411. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  52412. return vertex;
  52413. };
  52414. /**
  52415. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  52416. * This does nothing and may be overwritten by the user.
  52417. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  52418. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  52419. * @param update the boolean update value actually passed to setParticles()
  52420. */
  52421. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  52422. };
  52423. /**
  52424. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  52425. * This will be passed three parameters.
  52426. * This does nothing and may be overwritten by the user.
  52427. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  52428. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  52429. * @param update the boolean update value actually passed to setParticles()
  52430. */
  52431. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  52432. };
  52433. return SolidParticleSystem;
  52434. }());
  52435. BABYLON.SolidParticleSystem = SolidParticleSystem;
  52436. })(BABYLON || (BABYLON = {}));
  52437. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  52438. var BABYLON;
  52439. (function (BABYLON) {
  52440. var ShaderMaterial = /** @class */ (function (_super) {
  52441. __extends(ShaderMaterial, _super);
  52442. function ShaderMaterial(name, scene, shaderPath, options) {
  52443. var _this = _super.call(this, name, scene) || this;
  52444. _this._textures = {};
  52445. _this._textureArrays = {};
  52446. _this._floats = {};
  52447. _this._ints = {};
  52448. _this._floatsArrays = {};
  52449. _this._colors3 = {};
  52450. _this._colors3Arrays = {};
  52451. _this._colors4 = {};
  52452. _this._vectors2 = {};
  52453. _this._vectors3 = {};
  52454. _this._vectors4 = {};
  52455. _this._matrices = {};
  52456. _this._matrices3x3 = {};
  52457. _this._matrices2x2 = {};
  52458. _this._vectors2Arrays = {};
  52459. _this._vectors3Arrays = {};
  52460. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  52461. _this._shaderPath = shaderPath;
  52462. options.needAlphaBlending = options.needAlphaBlending || false;
  52463. options.needAlphaTesting = options.needAlphaTesting || false;
  52464. options.attributes = options.attributes || ["position", "normal", "uv"];
  52465. options.uniforms = options.uniforms || ["worldViewProjection"];
  52466. options.uniformBuffers = options.uniformBuffers || [];
  52467. options.samplers = options.samplers || [];
  52468. options.defines = options.defines || [];
  52469. _this._options = options;
  52470. return _this;
  52471. }
  52472. ShaderMaterial.prototype.getClassName = function () {
  52473. return "ShaderMaterial";
  52474. };
  52475. ShaderMaterial.prototype.needAlphaBlending = function () {
  52476. return this._options.needAlphaBlending;
  52477. };
  52478. ShaderMaterial.prototype.needAlphaTesting = function () {
  52479. return this._options.needAlphaTesting;
  52480. };
  52481. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  52482. if (this._options.uniforms.indexOf(uniformName) === -1) {
  52483. this._options.uniforms.push(uniformName);
  52484. }
  52485. };
  52486. ShaderMaterial.prototype.setTexture = function (name, texture) {
  52487. if (this._options.samplers.indexOf(name) === -1) {
  52488. this._options.samplers.push(name);
  52489. }
  52490. this._textures[name] = texture;
  52491. return this;
  52492. };
  52493. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  52494. if (this._options.samplers.indexOf(name) === -1) {
  52495. this._options.samplers.push(name);
  52496. }
  52497. this._checkUniform(name);
  52498. this._textureArrays[name] = textures;
  52499. return this;
  52500. };
  52501. ShaderMaterial.prototype.setFloat = function (name, value) {
  52502. this._checkUniform(name);
  52503. this._floats[name] = value;
  52504. return this;
  52505. };
  52506. ShaderMaterial.prototype.setInt = function (name, value) {
  52507. this._checkUniform(name);
  52508. this._ints[name] = value;
  52509. return this;
  52510. };
  52511. ShaderMaterial.prototype.setFloats = function (name, value) {
  52512. this._checkUniform(name);
  52513. this._floatsArrays[name] = value;
  52514. return this;
  52515. };
  52516. ShaderMaterial.prototype.setColor3 = function (name, value) {
  52517. this._checkUniform(name);
  52518. this._colors3[name] = value;
  52519. return this;
  52520. };
  52521. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  52522. this._checkUniform(name);
  52523. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  52524. color.toArray(arr, arr.length);
  52525. return arr;
  52526. }, []);
  52527. return this;
  52528. };
  52529. ShaderMaterial.prototype.setColor4 = function (name, value) {
  52530. this._checkUniform(name);
  52531. this._colors4[name] = value;
  52532. return this;
  52533. };
  52534. ShaderMaterial.prototype.setVector2 = function (name, value) {
  52535. this._checkUniform(name);
  52536. this._vectors2[name] = value;
  52537. return this;
  52538. };
  52539. ShaderMaterial.prototype.setVector3 = function (name, value) {
  52540. this._checkUniform(name);
  52541. this._vectors3[name] = value;
  52542. return this;
  52543. };
  52544. ShaderMaterial.prototype.setVector4 = function (name, value) {
  52545. this._checkUniform(name);
  52546. this._vectors4[name] = value;
  52547. return this;
  52548. };
  52549. ShaderMaterial.prototype.setMatrix = function (name, value) {
  52550. this._checkUniform(name);
  52551. this._matrices[name] = value;
  52552. return this;
  52553. };
  52554. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  52555. this._checkUniform(name);
  52556. this._matrices3x3[name] = value;
  52557. return this;
  52558. };
  52559. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  52560. this._checkUniform(name);
  52561. this._matrices2x2[name] = value;
  52562. return this;
  52563. };
  52564. ShaderMaterial.prototype.setArray2 = function (name, value) {
  52565. this._checkUniform(name);
  52566. this._vectors2Arrays[name] = value;
  52567. return this;
  52568. };
  52569. ShaderMaterial.prototype.setArray3 = function (name, value) {
  52570. this._checkUniform(name);
  52571. this._vectors3Arrays[name] = value;
  52572. return this;
  52573. };
  52574. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  52575. if (!mesh) {
  52576. return true;
  52577. }
  52578. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  52579. return false;
  52580. }
  52581. return false;
  52582. };
  52583. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  52584. var scene = this.getScene();
  52585. var engine = scene.getEngine();
  52586. if (!this.checkReadyOnEveryCall) {
  52587. if (this._renderId === scene.getRenderId()) {
  52588. if (this._checkCache(scene, mesh, useInstances)) {
  52589. return true;
  52590. }
  52591. }
  52592. }
  52593. // Instances
  52594. var defines = [];
  52595. var attribs = [];
  52596. var fallbacks = new BABYLON.EffectFallbacks();
  52597. if (useInstances) {
  52598. defines.push("#define INSTANCES");
  52599. }
  52600. for (var index = 0; index < this._options.defines.length; index++) {
  52601. defines.push(this._options.defines[index]);
  52602. }
  52603. for (var index = 0; index < this._options.attributes.length; index++) {
  52604. attribs.push(this._options.attributes[index]);
  52605. }
  52606. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  52607. attribs.push(BABYLON.VertexBuffer.ColorKind);
  52608. defines.push("#define VERTEXCOLOR");
  52609. }
  52610. // Bones
  52611. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  52612. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  52613. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  52614. if (mesh.numBoneInfluencers > 4) {
  52615. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  52616. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  52617. }
  52618. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  52619. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  52620. fallbacks.addCPUSkinningFallback(0, mesh);
  52621. if (this._options.uniforms.indexOf("mBones") === -1) {
  52622. this._options.uniforms.push("mBones");
  52623. }
  52624. }
  52625. else {
  52626. defines.push("#define NUM_BONE_INFLUENCERS 0");
  52627. }
  52628. // Textures
  52629. for (var name in this._textures) {
  52630. if (!this._textures[name].isReady()) {
  52631. return false;
  52632. }
  52633. }
  52634. // Alpha test
  52635. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  52636. defines.push("#define ALPHATEST");
  52637. }
  52638. var previousEffect = this._effect;
  52639. var join = defines.join("\n");
  52640. this._effect = engine.createEffect(this._shaderPath, {
  52641. attributes: attribs,
  52642. uniformsNames: this._options.uniforms,
  52643. uniformBuffersNames: this._options.uniformBuffers,
  52644. samplers: this._options.samplers,
  52645. defines: join,
  52646. fallbacks: fallbacks,
  52647. onCompiled: this.onCompiled,
  52648. onError: this.onError
  52649. }, engine);
  52650. if (!this._effect.isReady()) {
  52651. return false;
  52652. }
  52653. if (previousEffect !== this._effect) {
  52654. scene.resetCachedMaterial();
  52655. }
  52656. this._renderId = scene.getRenderId();
  52657. return true;
  52658. };
  52659. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  52660. var scene = this.getScene();
  52661. if (!this._effect) {
  52662. return;
  52663. }
  52664. if (this._options.uniforms.indexOf("world") !== -1) {
  52665. this._effect.setMatrix("world", world);
  52666. }
  52667. if (this._options.uniforms.indexOf("worldView") !== -1) {
  52668. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  52669. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  52670. }
  52671. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  52672. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  52673. }
  52674. };
  52675. ShaderMaterial.prototype.bind = function (world, mesh) {
  52676. // Std values
  52677. this.bindOnlyWorldMatrix(world);
  52678. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  52679. if (this._options.uniforms.indexOf("view") !== -1) {
  52680. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  52681. }
  52682. if (this._options.uniforms.indexOf("projection") !== -1) {
  52683. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  52684. }
  52685. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  52686. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  52687. }
  52688. // Bones
  52689. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  52690. var name;
  52691. // Texture
  52692. for (name in this._textures) {
  52693. this._effect.setTexture(name, this._textures[name]);
  52694. }
  52695. // Texture arrays
  52696. for (name in this._textureArrays) {
  52697. this._effect.setTextureArray(name, this._textureArrays[name]);
  52698. }
  52699. // Int
  52700. for (name in this._ints) {
  52701. this._effect.setInt(name, this._ints[name]);
  52702. }
  52703. // Float
  52704. for (name in this._floats) {
  52705. this._effect.setFloat(name, this._floats[name]);
  52706. }
  52707. // Floats
  52708. for (name in this._floatsArrays) {
  52709. this._effect.setArray(name, this._floatsArrays[name]);
  52710. }
  52711. // Color3
  52712. for (name in this._colors3) {
  52713. this._effect.setColor3(name, this._colors3[name]);
  52714. }
  52715. for (name in this._colors3Arrays) {
  52716. this._effect.setArray3(name, this._colors3Arrays[name]);
  52717. }
  52718. // Color4
  52719. for (name in this._colors4) {
  52720. var color = this._colors4[name];
  52721. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  52722. }
  52723. // Vector2
  52724. for (name in this._vectors2) {
  52725. this._effect.setVector2(name, this._vectors2[name]);
  52726. }
  52727. // Vector3
  52728. for (name in this._vectors3) {
  52729. this._effect.setVector3(name, this._vectors3[name]);
  52730. }
  52731. // Vector4
  52732. for (name in this._vectors4) {
  52733. this._effect.setVector4(name, this._vectors4[name]);
  52734. }
  52735. // Matrix
  52736. for (name in this._matrices) {
  52737. this._effect.setMatrix(name, this._matrices[name]);
  52738. }
  52739. // Matrix 3x3
  52740. for (name in this._matrices3x3) {
  52741. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  52742. }
  52743. // Matrix 2x2
  52744. for (name in this._matrices2x2) {
  52745. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  52746. }
  52747. // Vector2Array
  52748. for (name in this._vectors2Arrays) {
  52749. this._effect.setArray2(name, this._vectors2Arrays[name]);
  52750. }
  52751. // Vector3Array
  52752. for (name in this._vectors3Arrays) {
  52753. this._effect.setArray3(name, this._vectors3Arrays[name]);
  52754. }
  52755. }
  52756. this._afterBind(mesh);
  52757. };
  52758. ShaderMaterial.prototype.getActiveTextures = function () {
  52759. var activeTextures = _super.prototype.getActiveTextures.call(this);
  52760. for (var name in this._textures) {
  52761. activeTextures.push(this._textures[name]);
  52762. }
  52763. for (var name in this._textureArrays) {
  52764. var array = this._textureArrays[name];
  52765. for (var index = 0; index < array.length; index++) {
  52766. activeTextures.push(array[index]);
  52767. }
  52768. }
  52769. return activeTextures;
  52770. };
  52771. ShaderMaterial.prototype.hasTexture = function (texture) {
  52772. if (_super.prototype.hasTexture.call(this, texture)) {
  52773. return true;
  52774. }
  52775. for (var name in this._textures) {
  52776. if (this._textures[name] === texture) {
  52777. return true;
  52778. }
  52779. }
  52780. for (var name in this._textureArrays) {
  52781. var array = this._textureArrays[name];
  52782. for (var index = 0; index < array.length; index++) {
  52783. if (array[index] === texture) {
  52784. return true;
  52785. }
  52786. }
  52787. }
  52788. return false;
  52789. };
  52790. ShaderMaterial.prototype.clone = function (name) {
  52791. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  52792. return newShaderMaterial;
  52793. };
  52794. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  52795. if (forceDisposeTextures) {
  52796. var name;
  52797. for (name in this._textures) {
  52798. this._textures[name].dispose();
  52799. }
  52800. for (name in this._textureArrays) {
  52801. var array = this._textureArrays[name];
  52802. for (var index = 0; index < array.length; index++) {
  52803. array[index].dispose();
  52804. }
  52805. }
  52806. }
  52807. this._textures = {};
  52808. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  52809. };
  52810. ShaderMaterial.prototype.serialize = function () {
  52811. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  52812. serializationObject.customType = "BABYLON.ShaderMaterial";
  52813. serializationObject.options = this._options;
  52814. serializationObject.shaderPath = this._shaderPath;
  52815. var name;
  52816. // Texture
  52817. serializationObject.textures = {};
  52818. for (name in this._textures) {
  52819. serializationObject.textures[name] = this._textures[name].serialize();
  52820. }
  52821. // Texture arrays
  52822. serializationObject.textureArrays = {};
  52823. for (name in this._textureArrays) {
  52824. serializationObject.textureArrays[name] = [];
  52825. var array = this._textureArrays[name];
  52826. for (var index = 0; index < array.length; index++) {
  52827. serializationObject.textureArrays[name].push(array[index].serialize());
  52828. }
  52829. }
  52830. // Float
  52831. serializationObject.floats = {};
  52832. for (name in this._floats) {
  52833. serializationObject.floats[name] = this._floats[name];
  52834. }
  52835. // Float s
  52836. serializationObject.FloatArrays = {};
  52837. for (name in this._floatsArrays) {
  52838. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  52839. }
  52840. // Color3
  52841. serializationObject.colors3 = {};
  52842. for (name in this._colors3) {
  52843. serializationObject.colors3[name] = this._colors3[name].asArray();
  52844. }
  52845. // Color3 array
  52846. serializationObject.colors3Arrays = {};
  52847. for (name in this._colors3Arrays) {
  52848. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  52849. }
  52850. // Color4
  52851. serializationObject.colors4 = {};
  52852. for (name in this._colors4) {
  52853. serializationObject.colors4[name] = this._colors4[name].asArray();
  52854. }
  52855. // Vector2
  52856. serializationObject.vectors2 = {};
  52857. for (name in this._vectors2) {
  52858. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  52859. }
  52860. // Vector3
  52861. serializationObject.vectors3 = {};
  52862. for (name in this._vectors3) {
  52863. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  52864. }
  52865. // Vector4
  52866. serializationObject.vectors4 = {};
  52867. for (name in this._vectors4) {
  52868. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  52869. }
  52870. // Matrix
  52871. serializationObject.matrices = {};
  52872. for (name in this._matrices) {
  52873. serializationObject.matrices[name] = this._matrices[name].asArray();
  52874. }
  52875. // Matrix 3x3
  52876. serializationObject.matrices3x3 = {};
  52877. for (name in this._matrices3x3) {
  52878. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  52879. }
  52880. // Matrix 2x2
  52881. serializationObject.matrices2x2 = {};
  52882. for (name in this._matrices2x2) {
  52883. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  52884. }
  52885. // Vector2Array
  52886. serializationObject.vectors2Arrays = {};
  52887. for (name in this._vectors2Arrays) {
  52888. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  52889. }
  52890. // Vector3Array
  52891. serializationObject.vectors3Arrays = {};
  52892. for (name in this._vectors3Arrays) {
  52893. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  52894. }
  52895. return serializationObject;
  52896. };
  52897. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  52898. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  52899. var name;
  52900. // Texture
  52901. for (name in source.textures) {
  52902. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  52903. }
  52904. // Texture arrays
  52905. for (name in source.textureArrays) {
  52906. var array = source.textureArrays[name];
  52907. var textureArray = new Array();
  52908. for (var index = 0; index < array.length; index++) {
  52909. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  52910. }
  52911. material.setTextureArray(name, textureArray);
  52912. }
  52913. // Float
  52914. for (name in source.floats) {
  52915. material.setFloat(name, source.floats[name]);
  52916. }
  52917. // Float s
  52918. for (name in source.floatsArrays) {
  52919. material.setFloats(name, source.floatsArrays[name]);
  52920. }
  52921. // Color3
  52922. for (name in source.colors3) {
  52923. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  52924. }
  52925. // Color3 arrays
  52926. for (name in source.colors3Arrays) {
  52927. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  52928. if (i % 3 === 0) {
  52929. arr.push([num]);
  52930. }
  52931. else {
  52932. arr[arr.length - 1].push(num);
  52933. }
  52934. return arr;
  52935. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  52936. material.setColor3Array(name, colors);
  52937. }
  52938. // Color4
  52939. for (name in source.colors4) {
  52940. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  52941. }
  52942. // Vector2
  52943. for (name in source.vectors2) {
  52944. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  52945. }
  52946. // Vector3
  52947. for (name in source.vectors3) {
  52948. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  52949. }
  52950. // Vector4
  52951. for (name in source.vectors4) {
  52952. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  52953. }
  52954. // Matrix
  52955. for (name in source.matrices) {
  52956. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  52957. }
  52958. // Matrix 3x3
  52959. for (name in source.matrices3x3) {
  52960. material.setMatrix3x3(name, source.matrices3x3[name]);
  52961. }
  52962. // Matrix 2x2
  52963. for (name in source.matrices2x2) {
  52964. material.setMatrix2x2(name, source.matrices2x2[name]);
  52965. }
  52966. // Vector2Array
  52967. for (name in source.vectors2Arrays) {
  52968. material.setArray2(name, source.vectors2Arrays[name]);
  52969. }
  52970. // Vector3Array
  52971. for (name in source.vectors3Arrays) {
  52972. material.setArray3(name, source.vectors3Arrays[name]);
  52973. }
  52974. return material;
  52975. };
  52976. return ShaderMaterial;
  52977. }(BABYLON.Material));
  52978. BABYLON.ShaderMaterial = ShaderMaterial;
  52979. })(BABYLON || (BABYLON = {}));
  52980. //# sourceMappingURL=babylon.shaderMaterial.js.map
  52981. var BABYLON;
  52982. (function (BABYLON) {
  52983. var GroundMesh = /** @class */ (function (_super) {
  52984. __extends(GroundMesh, _super);
  52985. function GroundMesh(name, scene) {
  52986. var _this = _super.call(this, name, scene) || this;
  52987. _this.generateOctree = false;
  52988. return _this;
  52989. }
  52990. GroundMesh.prototype.getClassName = function () {
  52991. return "GroundMesh";
  52992. };
  52993. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  52994. get: function () {
  52995. return Math.min(this._subdivisionsX, this._subdivisionsY);
  52996. },
  52997. enumerable: true,
  52998. configurable: true
  52999. });
  53000. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  53001. get: function () {
  53002. return this._subdivisionsX;
  53003. },
  53004. enumerable: true,
  53005. configurable: true
  53006. });
  53007. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  53008. get: function () {
  53009. return this._subdivisionsY;
  53010. },
  53011. enumerable: true,
  53012. configurable: true
  53013. });
  53014. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  53015. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  53016. this._subdivisionsX = chunksCount;
  53017. this._subdivisionsY = chunksCount;
  53018. this.subdivide(chunksCount);
  53019. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  53020. };
  53021. /**
  53022. * Returns a height (y) value in the Worl system :
  53023. * the ground altitude at the coordinates (x, z) expressed in the World system.
  53024. * Returns the ground y position if (x, z) are outside the ground surface.
  53025. */
  53026. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  53027. var world = this.getWorldMatrix();
  53028. var invMat = BABYLON.Tmp.Matrix[5];
  53029. world.invertToRef(invMat);
  53030. var tmpVect = BABYLON.Tmp.Vector3[8];
  53031. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  53032. x = tmpVect.x;
  53033. z = tmpVect.z;
  53034. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  53035. return this.position.y;
  53036. }
  53037. if (!this._heightQuads || this._heightQuads.length == 0) {
  53038. this._initHeightQuads();
  53039. this._computeHeightQuads();
  53040. }
  53041. var facet = this._getFacetAt(x, z);
  53042. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  53043. // return y in the World system
  53044. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  53045. return tmpVect.y;
  53046. };
  53047. /**
  53048. * Returns a normalized vector (Vector3) orthogonal to the ground
  53049. * at the ground coordinates (x, z) expressed in the World system.
  53050. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  53051. */
  53052. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  53053. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  53054. this.getNormalAtCoordinatesToRef(x, z, normal);
  53055. return normal;
  53056. };
  53057. /**
  53058. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  53059. * at the ground coordinates (x, z) expressed in the World system.
  53060. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  53061. * Returns the GroundMesh.
  53062. */
  53063. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  53064. var world = this.getWorldMatrix();
  53065. var tmpMat = BABYLON.Tmp.Matrix[5];
  53066. world.invertToRef(tmpMat);
  53067. var tmpVect = BABYLON.Tmp.Vector3[8];
  53068. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  53069. x = tmpVect.x;
  53070. z = tmpVect.z;
  53071. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  53072. return this;
  53073. }
  53074. if (!this._heightQuads || this._heightQuads.length == 0) {
  53075. this._initHeightQuads();
  53076. this._computeHeightQuads();
  53077. }
  53078. var facet = this._getFacetAt(x, z);
  53079. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  53080. return this;
  53081. };
  53082. /**
  53083. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  53084. * if the ground has been updated.
  53085. * This can be used in the render loop.
  53086. * Returns the GroundMesh.
  53087. */
  53088. GroundMesh.prototype.updateCoordinateHeights = function () {
  53089. if (!this._heightQuads || this._heightQuads.length == 0) {
  53090. this._initHeightQuads();
  53091. }
  53092. this._computeHeightQuads();
  53093. return this;
  53094. };
  53095. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  53096. GroundMesh.prototype._getFacetAt = function (x, z) {
  53097. // retrieve col and row from x, z coordinates in the ground local system
  53098. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  53099. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  53100. var quad = this._heightQuads[row * this._subdivisionsX + col];
  53101. var facet;
  53102. if (z < quad.slope.x * x + quad.slope.y) {
  53103. facet = quad.facet1;
  53104. }
  53105. else {
  53106. facet = quad.facet2;
  53107. }
  53108. return facet;
  53109. };
  53110. // Creates and populates the heightMap array with "facet" elements :
  53111. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  53112. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  53113. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  53114. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  53115. // Returns the GroundMesh.
  53116. GroundMesh.prototype._initHeightQuads = function () {
  53117. var subdivisionsX = this._subdivisionsX;
  53118. var subdivisionsY = this._subdivisionsY;
  53119. this._heightQuads = new Array();
  53120. for (var row = 0; row < subdivisionsY; row++) {
  53121. for (var col = 0; col < subdivisionsX; col++) {
  53122. 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) };
  53123. this._heightQuads[row * subdivisionsX + col] = quad;
  53124. }
  53125. }
  53126. return this;
  53127. };
  53128. // Compute each quad element values and update the the heightMap array :
  53129. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  53130. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  53131. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  53132. // Returns the GroundMesh.
  53133. GroundMesh.prototype._computeHeightQuads = function () {
  53134. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  53135. if (!positions) {
  53136. return this;
  53137. }
  53138. var v1 = BABYLON.Tmp.Vector3[3];
  53139. var v2 = BABYLON.Tmp.Vector3[2];
  53140. var v3 = BABYLON.Tmp.Vector3[1];
  53141. var v4 = BABYLON.Tmp.Vector3[0];
  53142. var v1v2 = BABYLON.Tmp.Vector3[4];
  53143. var v1v3 = BABYLON.Tmp.Vector3[5];
  53144. var v1v4 = BABYLON.Tmp.Vector3[6];
  53145. var norm1 = BABYLON.Tmp.Vector3[7];
  53146. var norm2 = BABYLON.Tmp.Vector3[8];
  53147. var i = 0;
  53148. var j = 0;
  53149. var k = 0;
  53150. var cd = 0; // 2D slope coefficient : z = cd * x + h
  53151. var h = 0;
  53152. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  53153. var d2 = 0;
  53154. var subdivisionsX = this._subdivisionsX;
  53155. var subdivisionsY = this._subdivisionsY;
  53156. for (var row = 0; row < subdivisionsY; row++) {
  53157. for (var col = 0; col < subdivisionsX; col++) {
  53158. i = col * 3;
  53159. j = row * (subdivisionsX + 1) * 3;
  53160. k = (row + 1) * (subdivisionsX + 1) * 3;
  53161. v1.x = positions[j + i];
  53162. v1.y = positions[j + i + 1];
  53163. v1.z = positions[j + i + 2];
  53164. v2.x = positions[j + i + 3];
  53165. v2.y = positions[j + i + 4];
  53166. v2.z = positions[j + i + 5];
  53167. v3.x = positions[k + i];
  53168. v3.y = positions[k + i + 1];
  53169. v3.z = positions[k + i + 2];
  53170. v4.x = positions[k + i + 3];
  53171. v4.y = positions[k + i + 4];
  53172. v4.z = positions[k + i + 5];
  53173. // 2D slope V1V4
  53174. cd = (v4.z - v1.z) / (v4.x - v1.x);
  53175. h = v1.z - cd * v1.x; // v1 belongs to the slope
  53176. // facet equations :
  53177. // we compute each facet normal vector
  53178. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  53179. // we compute the value d by applying the equation to v1 which belongs to the plane
  53180. // then we store the facet equation in a Vector4
  53181. v2.subtractToRef(v1, v1v2);
  53182. v3.subtractToRef(v1, v1v3);
  53183. v4.subtractToRef(v1, v1v4);
  53184. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  53185. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  53186. norm1.normalize();
  53187. norm2.normalize();
  53188. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  53189. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  53190. var quad = this._heightQuads[row * subdivisionsX + col];
  53191. quad.slope.copyFromFloats(cd, h);
  53192. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  53193. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  53194. }
  53195. }
  53196. return this;
  53197. };
  53198. GroundMesh.prototype.serialize = function (serializationObject) {
  53199. _super.prototype.serialize.call(this, serializationObject);
  53200. serializationObject.subdivisionsX = this._subdivisionsX;
  53201. serializationObject.subdivisionsY = this._subdivisionsY;
  53202. serializationObject.minX = this._minX;
  53203. serializationObject.maxX = this._maxX;
  53204. serializationObject.minZ = this._minZ;
  53205. serializationObject.maxZ = this._maxZ;
  53206. serializationObject.width = this._width;
  53207. serializationObject.height = this._height;
  53208. };
  53209. GroundMesh.Parse = function (parsedMesh, scene) {
  53210. var result = new GroundMesh(parsedMesh.name, scene);
  53211. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  53212. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  53213. result._minX = parsedMesh.minX;
  53214. result._maxX = parsedMesh.maxX;
  53215. result._minZ = parsedMesh.minZ;
  53216. result._maxZ = parsedMesh.maxZ;
  53217. result._width = parsedMesh.width;
  53218. result._height = parsedMesh.height;
  53219. return result;
  53220. };
  53221. return GroundMesh;
  53222. }(BABYLON.Mesh));
  53223. BABYLON.GroundMesh = GroundMesh;
  53224. })(BABYLON || (BABYLON = {}));
  53225. //# sourceMappingURL=babylon.groundMesh.js.map
  53226. var BABYLON;
  53227. (function (BABYLON) {
  53228. /**
  53229. * Creates an instance based on a source mesh.
  53230. */
  53231. var InstancedMesh = /** @class */ (function (_super) {
  53232. __extends(InstancedMesh, _super);
  53233. function InstancedMesh(name, source) {
  53234. var _this = _super.call(this, name, source.getScene()) || this;
  53235. source.instances.push(_this);
  53236. _this._sourceMesh = source;
  53237. _this.position.copyFrom(source.position);
  53238. _this.rotation.copyFrom(source.rotation);
  53239. _this.scaling.copyFrom(source.scaling);
  53240. if (source.rotationQuaternion) {
  53241. _this.rotationQuaternion = source.rotationQuaternion.clone();
  53242. }
  53243. _this.infiniteDistance = source.infiniteDistance;
  53244. _this.setPivotMatrix(source.getPivotMatrix());
  53245. _this.refreshBoundingInfo();
  53246. _this._syncSubMeshes();
  53247. return _this;
  53248. }
  53249. /**
  53250. * Returns the string "InstancedMesh".
  53251. */
  53252. InstancedMesh.prototype.getClassName = function () {
  53253. return "InstancedMesh";
  53254. };
  53255. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  53256. // Methods
  53257. get: function () {
  53258. return this._sourceMesh.receiveShadows;
  53259. },
  53260. enumerable: true,
  53261. configurable: true
  53262. });
  53263. Object.defineProperty(InstancedMesh.prototype, "material", {
  53264. get: function () {
  53265. return this._sourceMesh.material;
  53266. },
  53267. enumerable: true,
  53268. configurable: true
  53269. });
  53270. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  53271. get: function () {
  53272. return this._sourceMesh.visibility;
  53273. },
  53274. enumerable: true,
  53275. configurable: true
  53276. });
  53277. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  53278. get: function () {
  53279. return this._sourceMesh.skeleton;
  53280. },
  53281. enumerable: true,
  53282. configurable: true
  53283. });
  53284. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  53285. get: function () {
  53286. return this._sourceMesh.renderingGroupId;
  53287. },
  53288. enumerable: true,
  53289. configurable: true
  53290. });
  53291. /**
  53292. * Returns the total number of vertices (integer).
  53293. */
  53294. InstancedMesh.prototype.getTotalVertices = function () {
  53295. return this._sourceMesh.getTotalVertices();
  53296. };
  53297. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  53298. get: function () {
  53299. return this._sourceMesh;
  53300. },
  53301. enumerable: true,
  53302. configurable: true
  53303. });
  53304. /**
  53305. * Is this node ready to be used/rendered
  53306. * @return {boolean} is it ready
  53307. */
  53308. InstancedMesh.prototype.isReady = function () {
  53309. return this._sourceMesh.isReady(true);
  53310. };
  53311. /**
  53312. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  53313. */
  53314. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  53315. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  53316. };
  53317. /**
  53318. * Sets the vertex data of the mesh geometry for the requested `kind`.
  53319. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  53320. * The `data` are either a numeric array either a Float32Array.
  53321. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  53322. * 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).
  53323. * Note that a new underlying VertexBuffer object is created each call.
  53324. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  53325. *
  53326. * Possible `kind` values :
  53327. * - BABYLON.VertexBuffer.PositionKind
  53328. * - BABYLON.VertexBuffer.UVKind
  53329. * - BABYLON.VertexBuffer.UV2Kind
  53330. * - BABYLON.VertexBuffer.UV3Kind
  53331. * - BABYLON.VertexBuffer.UV4Kind
  53332. * - BABYLON.VertexBuffer.UV5Kind
  53333. * - BABYLON.VertexBuffer.UV6Kind
  53334. * - BABYLON.VertexBuffer.ColorKind
  53335. * - BABYLON.VertexBuffer.MatricesIndicesKind
  53336. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  53337. * - BABYLON.VertexBuffer.MatricesWeightsKind
  53338. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  53339. *
  53340. * Returns the Mesh.
  53341. */
  53342. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  53343. if (this.sourceMesh) {
  53344. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  53345. }
  53346. return this.sourceMesh;
  53347. };
  53348. /**
  53349. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  53350. * If the mesh has no geometry, it is simply returned as it is.
  53351. * The `data` are either a numeric array either a Float32Array.
  53352. * No new underlying VertexBuffer object is created.
  53353. * 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.
  53354. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  53355. *
  53356. * Possible `kind` values :
  53357. * - BABYLON.VertexBuffer.PositionKind
  53358. * - BABYLON.VertexBuffer.UVKind
  53359. * - BABYLON.VertexBuffer.UV2Kind
  53360. * - BABYLON.VertexBuffer.UV3Kind
  53361. * - BABYLON.VertexBuffer.UV4Kind
  53362. * - BABYLON.VertexBuffer.UV5Kind
  53363. * - BABYLON.VertexBuffer.UV6Kind
  53364. * - BABYLON.VertexBuffer.ColorKind
  53365. * - BABYLON.VertexBuffer.MatricesIndicesKind
  53366. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  53367. * - BABYLON.VertexBuffer.MatricesWeightsKind
  53368. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  53369. *
  53370. * Returns the Mesh.
  53371. */
  53372. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  53373. if (this.sourceMesh) {
  53374. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  53375. }
  53376. return this.sourceMesh;
  53377. };
  53378. /**
  53379. * Sets the mesh indices.
  53380. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  53381. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  53382. * This method creates a new index buffer each call.
  53383. * Returns the Mesh.
  53384. */
  53385. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  53386. if (totalVertices === void 0) { totalVertices = null; }
  53387. if (this.sourceMesh) {
  53388. this.sourceMesh.setIndices(indices, totalVertices);
  53389. }
  53390. return this.sourceMesh;
  53391. };
  53392. /**
  53393. * Boolean : True if the mesh owns the requested kind of data.
  53394. */
  53395. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  53396. return this._sourceMesh.isVerticesDataPresent(kind);
  53397. };
  53398. /**
  53399. * Returns an array of indices (IndicesArray).
  53400. */
  53401. InstancedMesh.prototype.getIndices = function () {
  53402. return this._sourceMesh.getIndices();
  53403. };
  53404. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  53405. get: function () {
  53406. return this._sourceMesh._positions;
  53407. },
  53408. enumerable: true,
  53409. configurable: true
  53410. });
  53411. /**
  53412. * Sets a new updated BoundingInfo to the mesh.
  53413. * Returns the mesh.
  53414. */
  53415. InstancedMesh.prototype.refreshBoundingInfo = function () {
  53416. var meshBB = this._sourceMesh.getBoundingInfo();
  53417. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  53418. this._updateBoundingInfo();
  53419. return this;
  53420. };
  53421. InstancedMesh.prototype._preActivate = function () {
  53422. if (this._currentLOD) {
  53423. this._currentLOD._preActivate();
  53424. }
  53425. return this;
  53426. };
  53427. InstancedMesh.prototype._activate = function (renderId) {
  53428. if (this._currentLOD) {
  53429. this._currentLOD._registerInstanceForRenderId(this, renderId);
  53430. }
  53431. return this;
  53432. };
  53433. /**
  53434. * Returns the current associated LOD AbstractMesh.
  53435. */
  53436. InstancedMesh.prototype.getLOD = function (camera) {
  53437. if (!camera) {
  53438. return this;
  53439. }
  53440. var boundingInfo = this.getBoundingInfo();
  53441. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  53442. if (this._currentLOD === this.sourceMesh) {
  53443. return this;
  53444. }
  53445. return this._currentLOD;
  53446. };
  53447. InstancedMesh.prototype._syncSubMeshes = function () {
  53448. this.releaseSubMeshes();
  53449. if (this._sourceMesh.subMeshes) {
  53450. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  53451. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  53452. }
  53453. }
  53454. return this;
  53455. };
  53456. InstancedMesh.prototype._generatePointsArray = function () {
  53457. return this._sourceMesh._generatePointsArray();
  53458. };
  53459. /**
  53460. * Creates a new InstancedMesh from the current mesh.
  53461. * - name (string) : the cloned mesh name
  53462. * - newParent (optional Node) : the optional Node to parent the clone to.
  53463. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  53464. *
  53465. * Returns the clone.
  53466. */
  53467. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  53468. var result = this._sourceMesh.createInstance(name);
  53469. // Deep copy
  53470. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  53471. // Bounding info
  53472. this.refreshBoundingInfo();
  53473. // Parent
  53474. if (newParent) {
  53475. result.parent = newParent;
  53476. }
  53477. if (!doNotCloneChildren) {
  53478. // Children
  53479. for (var index = 0; index < this.getScene().meshes.length; index++) {
  53480. var mesh = this.getScene().meshes[index];
  53481. if (mesh.parent === this) {
  53482. mesh.clone(mesh.name, result);
  53483. }
  53484. }
  53485. }
  53486. result.computeWorldMatrix(true);
  53487. return result;
  53488. };
  53489. /**
  53490. * Disposes the InstancedMesh.
  53491. * Returns nothing.
  53492. */
  53493. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  53494. // Remove from mesh
  53495. var index = this._sourceMesh.instances.indexOf(this);
  53496. this._sourceMesh.instances.splice(index, 1);
  53497. _super.prototype.dispose.call(this, doNotRecurse);
  53498. };
  53499. return InstancedMesh;
  53500. }(BABYLON.AbstractMesh));
  53501. BABYLON.InstancedMesh = InstancedMesh;
  53502. })(BABYLON || (BABYLON = {}));
  53503. //# sourceMappingURL=babylon.instancedMesh.js.map
  53504. var BABYLON;
  53505. (function (BABYLON) {
  53506. var LinesMesh = /** @class */ (function (_super) {
  53507. __extends(LinesMesh, _super);
  53508. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  53509. if (scene === void 0) { scene = null; }
  53510. if (parent === void 0) { parent = null; }
  53511. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  53512. _this.useVertexColor = useVertexColor;
  53513. _this.useVertexAlpha = useVertexAlpha;
  53514. _this.color = new BABYLON.Color3(1, 1, 1);
  53515. _this.alpha = 1;
  53516. if (source) {
  53517. _this.color = source.color.clone();
  53518. _this.alpha = source.alpha;
  53519. _this.useVertexColor = source.useVertexColor;
  53520. _this.useVertexAlpha = source.useVertexAlpha;
  53521. }
  53522. _this._intersectionThreshold = 0.1;
  53523. var defines = [];
  53524. var options = {
  53525. attributes: [BABYLON.VertexBuffer.PositionKind],
  53526. uniforms: ["world", "viewProjection"],
  53527. needAlphaBlending: true,
  53528. defines: defines
  53529. };
  53530. if (useVertexAlpha === false) {
  53531. options.needAlphaBlending = false;
  53532. }
  53533. if (!useVertexColor) {
  53534. options.uniforms.push("color");
  53535. }
  53536. else {
  53537. options.defines.push("#define VERTEXCOLOR");
  53538. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  53539. }
  53540. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  53541. return _this;
  53542. }
  53543. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  53544. /**
  53545. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  53546. * This margin is expressed in world space coordinates, so its value may vary.
  53547. * Default value is 0.1
  53548. * @returns the intersection Threshold value.
  53549. */
  53550. get: function () {
  53551. return this._intersectionThreshold;
  53552. },
  53553. /**
  53554. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  53555. * This margin is expressed in world space coordinates, so its value may vary.
  53556. * @param value the new threshold to apply
  53557. */
  53558. set: function (value) {
  53559. if (this._intersectionThreshold === value) {
  53560. return;
  53561. }
  53562. this._intersectionThreshold = value;
  53563. if (this.geometry) {
  53564. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  53565. }
  53566. },
  53567. enumerable: true,
  53568. configurable: true
  53569. });
  53570. /**
  53571. * Returns the string "LineMesh"
  53572. */
  53573. LinesMesh.prototype.getClassName = function () {
  53574. return "LinesMesh";
  53575. };
  53576. Object.defineProperty(LinesMesh.prototype, "material", {
  53577. get: function () {
  53578. return this._colorShader;
  53579. },
  53580. set: function (value) {
  53581. // Do nothing
  53582. },
  53583. enumerable: true,
  53584. configurable: true
  53585. });
  53586. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  53587. get: function () {
  53588. return false;
  53589. },
  53590. enumerable: true,
  53591. configurable: true
  53592. });
  53593. LinesMesh.prototype.createInstance = function (name) {
  53594. throw new Error("LinesMeshes do not support createInstance.");
  53595. };
  53596. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  53597. if (!this._geometry) {
  53598. return this;
  53599. }
  53600. // VBOs
  53601. this._geometry._bind(this._colorShader.getEffect());
  53602. // Color
  53603. if (!this.useVertexColor) {
  53604. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  53605. }
  53606. return this;
  53607. };
  53608. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  53609. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  53610. return this;
  53611. }
  53612. var engine = this.getScene().getEngine();
  53613. // Draw order
  53614. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  53615. return this;
  53616. };
  53617. LinesMesh.prototype.dispose = function (doNotRecurse) {
  53618. this._colorShader.dispose();
  53619. _super.prototype.dispose.call(this, doNotRecurse);
  53620. };
  53621. /**
  53622. * Returns a new LineMesh object cloned from the current one.
  53623. */
  53624. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  53625. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  53626. };
  53627. return LinesMesh;
  53628. }(BABYLON.Mesh));
  53629. BABYLON.LinesMesh = LinesMesh;
  53630. })(BABYLON || (BABYLON = {}));
  53631. //# sourceMappingURL=babylon.linesMesh.js.map
  53632. var BABYLON;
  53633. (function (BABYLON) {
  53634. var MeshBuilder = /** @class */ (function () {
  53635. function MeshBuilder() {
  53636. }
  53637. MeshBuilder.updateSideOrientation = function (orientation) {
  53638. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  53639. return BABYLON.Mesh.DOUBLESIDE;
  53640. }
  53641. if (orientation === undefined || orientation === null) {
  53642. return BABYLON.Mesh.FRONTSIDE;
  53643. }
  53644. return orientation;
  53645. };
  53646. /**
  53647. * Creates a box mesh.
  53648. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  53649. * The parameter `size` sets the size (float) of each box side (default 1).
  53650. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  53651. * 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).
  53652. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  53653. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  53654. * 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).
  53655. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  53656. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  53657. */
  53658. MeshBuilder.CreateBox = function (name, options, scene) {
  53659. if (scene === void 0) { scene = null; }
  53660. var box = new BABYLON.Mesh(name, scene);
  53661. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  53662. box._originalBuilderSideOrientation = options.sideOrientation;
  53663. var vertexData = BABYLON.VertexData.CreateBox(options);
  53664. vertexData.applyToMesh(box, options.updatable);
  53665. return box;
  53666. };
  53667. /**
  53668. * Creates a sphere mesh.
  53669. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  53670. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  53671. * 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`).
  53672. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  53673. * 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
  53674. * 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).
  53675. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  53676. * 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).
  53677. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  53678. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  53679. */
  53680. MeshBuilder.CreateSphere = function (name, options, scene) {
  53681. var sphere = new BABYLON.Mesh(name, scene);
  53682. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  53683. sphere._originalBuilderSideOrientation = options.sideOrientation;
  53684. var vertexData = BABYLON.VertexData.CreateSphere(options);
  53685. vertexData.applyToMesh(sphere, options.updatable);
  53686. return sphere;
  53687. };
  53688. /**
  53689. * Creates a plane polygonal mesh. By default, this is a disc.
  53690. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  53691. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  53692. * 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.
  53693. * 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
  53694. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  53695. * 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).
  53696. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  53697. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  53698. */
  53699. MeshBuilder.CreateDisc = function (name, options, scene) {
  53700. if (scene === void 0) { scene = null; }
  53701. var disc = new BABYLON.Mesh(name, scene);
  53702. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  53703. disc._originalBuilderSideOrientation = options.sideOrientation;
  53704. var vertexData = BABYLON.VertexData.CreateDisc(options);
  53705. vertexData.applyToMesh(disc, options.updatable);
  53706. return disc;
  53707. };
  53708. /**
  53709. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  53710. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  53711. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  53712. * 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`).
  53713. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  53714. * 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.
  53715. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  53716. * 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).
  53717. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  53718. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  53719. */
  53720. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  53721. var sphere = new BABYLON.Mesh(name, scene);
  53722. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  53723. sphere._originalBuilderSideOrientation = options.sideOrientation;
  53724. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  53725. vertexData.applyToMesh(sphere, options.updatable);
  53726. return sphere;
  53727. };
  53728. ;
  53729. /**
  53730. * Creates a ribbon mesh.
  53731. * 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.
  53732. *
  53733. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  53734. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  53735. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  53736. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  53737. * 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.
  53738. * 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.
  53739. * 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
  53740. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  53741. * 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).
  53742. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  53743. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  53744. * 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.
  53745. * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values.
  53746. * 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
  53747. * if you set `closePath` to `true`, there's one extra vertex per path in the geometry.
  53748. * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time.
  53749. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  53750. */
  53751. MeshBuilder.CreateRibbon = function (name, options, scene) {
  53752. if (scene === void 0) { scene = null; }
  53753. var pathArray = options.pathArray;
  53754. var closeArray = options.closeArray;
  53755. var closePath = options.closePath;
  53756. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  53757. var instance = options.instance;
  53758. var updatable = options.updatable;
  53759. if (instance) {
  53760. // positionFunction : ribbon case
  53761. // only pathArray and sideOrientation parameters are taken into account for positions update
  53762. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  53763. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  53764. var positionFunction = function (positions) {
  53765. var minlg = pathArray[0].length;
  53766. var i = 0;
  53767. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  53768. for (var si = 1; si <= ns; si++) {
  53769. for (var p = 0; p < pathArray.length; p++) {
  53770. var path = pathArray[p];
  53771. var l = path.length;
  53772. minlg = (minlg < l) ? minlg : l;
  53773. var j = 0;
  53774. while (j < minlg) {
  53775. positions[i] = path[j].x;
  53776. positions[i + 1] = path[j].y;
  53777. positions[i + 2] = path[j].z;
  53778. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  53779. BABYLON.Tmp.Vector3[0].x = path[j].x;
  53780. }
  53781. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  53782. BABYLON.Tmp.Vector3[1].x = path[j].x;
  53783. }
  53784. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  53785. BABYLON.Tmp.Vector3[0].y = path[j].y;
  53786. }
  53787. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  53788. BABYLON.Tmp.Vector3[1].y = path[j].y;
  53789. }
  53790. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  53791. BABYLON.Tmp.Vector3[0].z = path[j].z;
  53792. }
  53793. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  53794. BABYLON.Tmp.Vector3[1].z = path[j].z;
  53795. }
  53796. j++;
  53797. i += 3;
  53798. }
  53799. if (instance._closePath) {
  53800. positions[i] = path[0].x;
  53801. positions[i + 1] = path[0].y;
  53802. positions[i + 2] = path[0].z;
  53803. i += 3;
  53804. }
  53805. }
  53806. }
  53807. };
  53808. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  53809. positionFunction(positions);
  53810. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  53811. instance._boundingInfo.update(instance._worldMatrix);
  53812. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  53813. if (options.colors) {
  53814. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  53815. for (var c = 0; c < options.colors.length; c++) {
  53816. colors[c * 4] = options.colors[c].r;
  53817. colors[c * 4 + 1] = options.colors[c].g;
  53818. colors[c * 4 + 2] = options.colors[c].b;
  53819. colors[c * 4 + 3] = options.colors[c].a;
  53820. }
  53821. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  53822. }
  53823. if (options.uvs) {
  53824. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  53825. for (var i = 0; i < options.uvs.length; i++) {
  53826. uvs[i * 2] = options.uvs[i].x;
  53827. uvs[i * 2 + 1] = options.uvs[i].y;
  53828. }
  53829. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  53830. }
  53831. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  53832. var indices = instance.getIndices();
  53833. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  53834. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  53835. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  53836. if (instance._closePath) {
  53837. var indexFirst = 0;
  53838. var indexLast = 0;
  53839. for (var p = 0; p < pathArray.length; p++) {
  53840. indexFirst = instance._idx[p] * 3;
  53841. if (p + 1 < pathArray.length) {
  53842. indexLast = (instance._idx[p + 1] - 1) * 3;
  53843. }
  53844. else {
  53845. indexLast = normals.length - 3;
  53846. }
  53847. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  53848. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  53849. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  53850. normals[indexLast] = normals[indexFirst];
  53851. normals[indexLast + 1] = normals[indexFirst + 1];
  53852. normals[indexLast + 2] = normals[indexFirst + 2];
  53853. }
  53854. }
  53855. if (!(instance.areNormalsFrozen)) {
  53856. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  53857. }
  53858. }
  53859. return instance;
  53860. }
  53861. else {
  53862. var ribbon = new BABYLON.Mesh(name, scene);
  53863. ribbon._originalBuilderSideOrientation = sideOrientation;
  53864. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  53865. if (closePath) {
  53866. ribbon._idx = vertexData._idx;
  53867. }
  53868. ribbon._closePath = closePath;
  53869. ribbon._closeArray = closeArray;
  53870. vertexData.applyToMesh(ribbon, updatable);
  53871. return ribbon;
  53872. }
  53873. };
  53874. /**
  53875. * Creates a cylinder or a cone mesh.
  53876. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  53877. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  53878. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  53879. * 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.
  53880. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  53881. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  53882. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  53883. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  53884. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  53885. * 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).
  53886. * 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
  53887. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  53888. * 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
  53889. * 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.
  53890. * If `enclose` is false, a ring surface is one element.
  53891. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  53892. * 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
  53893. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  53894. * 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).
  53895. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  53896. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  53897. */
  53898. MeshBuilder.CreateCylinder = function (name, options, scene) {
  53899. var cylinder = new BABYLON.Mesh(name, scene);
  53900. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  53901. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  53902. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  53903. vertexData.applyToMesh(cylinder, options.updatable);
  53904. return cylinder;
  53905. };
  53906. /**
  53907. * Creates a torus mesh.
  53908. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  53909. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  53910. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  53911. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  53912. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  53913. * 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).
  53914. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  53915. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  53916. */
  53917. MeshBuilder.CreateTorus = function (name, options, scene) {
  53918. var torus = new BABYLON.Mesh(name, scene);
  53919. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  53920. torus._originalBuilderSideOrientation = options.sideOrientation;
  53921. var vertexData = BABYLON.VertexData.CreateTorus(options);
  53922. vertexData.applyToMesh(torus, options.updatable);
  53923. return torus;
  53924. };
  53925. /**
  53926. * Creates a torus knot mesh.
  53927. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  53928. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  53929. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  53930. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  53931. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  53932. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  53933. * 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).
  53934. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  53935. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  53936. */
  53937. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  53938. var torusKnot = new BABYLON.Mesh(name, scene);
  53939. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  53940. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  53941. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  53942. vertexData.applyToMesh(torusKnot, options.updatable);
  53943. return torusKnot;
  53944. };
  53945. /**
  53946. * Creates a line system mesh.
  53947. * A line system is a pool of many lines gathered in a single mesh.
  53948. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  53949. * 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.
  53950. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  53951. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  53952. * 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
  53953. * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point.
  53954. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need the alpha blending (faster).
  53955. * 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
  53956. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  53957. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  53958. */
  53959. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  53960. var instance = options.instance;
  53961. var lines = options.lines;
  53962. var colors = options.colors;
  53963. if (instance) {
  53964. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  53965. var vertexColor;
  53966. var lineColors;
  53967. if (colors) {
  53968. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  53969. }
  53970. var i = 0;
  53971. var c = 0;
  53972. for (var l = 0; l < lines.length; l++) {
  53973. var points = lines[l];
  53974. for (var p = 0; p < points.length; p++) {
  53975. positions[i] = points[p].x;
  53976. positions[i + 1] = points[p].y;
  53977. positions[i + 2] = points[p].z;
  53978. if (colors && vertexColor) {
  53979. lineColors = colors[l];
  53980. vertexColor[c] = lineColors[p].r;
  53981. vertexColor[c + 1] = lineColors[p].g;
  53982. vertexColor[c + 2] = lineColors[p].b;
  53983. vertexColor[c + 3] = lineColors[p].a;
  53984. c += 4;
  53985. }
  53986. i += 3;
  53987. }
  53988. }
  53989. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  53990. if (colors && vertexColor) {
  53991. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  53992. }
  53993. return instance;
  53994. }
  53995. // line system creation
  53996. var useVertexColor = (colors) ? true : false;
  53997. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  53998. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  53999. vertexData.applyToMesh(lineSystem, options.updatable);
  54000. return lineSystem;
  54001. };
  54002. /**
  54003. * Creates a line mesh.
  54004. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  54005. * 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.
  54006. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  54007. * The parameter `points` is an array successive Vector3.
  54008. * 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
  54009. * The optional parameter `colors` is an array of successive Color4, one per line point.
  54010. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need alpha blending (faster).
  54011. * When updating an instance, remember that only point positions can change, not the number of points.
  54012. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54013. */
  54014. MeshBuilder.CreateLines = function (name, options, scene) {
  54015. if (scene === void 0) { scene = null; }
  54016. var colors = (options.colors) ? [options.colors] : null;
  54017. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  54018. return lines;
  54019. };
  54020. /**
  54021. * Creates a dashed line mesh.
  54022. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  54023. * 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.
  54024. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  54025. * The parameter `points` is an array successive Vector3.
  54026. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  54027. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  54028. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  54029. * 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
  54030. * When updating an instance, remember that only point positions can change, not the number of points.
  54031. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54032. */
  54033. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  54034. if (scene === void 0) { scene = null; }
  54035. var points = options.points;
  54036. var instance = options.instance;
  54037. var gapSize = options.gapSize || 1;
  54038. var dashSize = options.dashSize || 3;
  54039. if (instance) {
  54040. var positionFunction = function (positions) {
  54041. var curvect = BABYLON.Vector3.Zero();
  54042. var nbSeg = positions.length / 6;
  54043. var lg = 0;
  54044. var nb = 0;
  54045. var shft = 0;
  54046. var dashshft = 0;
  54047. var curshft = 0;
  54048. var p = 0;
  54049. var i = 0;
  54050. var j = 0;
  54051. for (i = 0; i < points.length - 1; i++) {
  54052. points[i + 1].subtractToRef(points[i], curvect);
  54053. lg += curvect.length();
  54054. }
  54055. shft = lg / nbSeg;
  54056. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  54057. for (i = 0; i < points.length - 1; i++) {
  54058. points[i + 1].subtractToRef(points[i], curvect);
  54059. nb = Math.floor(curvect.length() / shft);
  54060. curvect.normalize();
  54061. j = 0;
  54062. while (j < nb && p < positions.length) {
  54063. curshft = shft * j;
  54064. positions[p] = points[i].x + curshft * curvect.x;
  54065. positions[p + 1] = points[i].y + curshft * curvect.y;
  54066. positions[p + 2] = points[i].z + curshft * curvect.z;
  54067. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  54068. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  54069. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  54070. p += 6;
  54071. j++;
  54072. }
  54073. }
  54074. while (p < positions.length) {
  54075. positions[p] = points[i].x;
  54076. positions[p + 1] = points[i].y;
  54077. positions[p + 2] = points[i].z;
  54078. p += 3;
  54079. }
  54080. };
  54081. instance.updateMeshPositions(positionFunction, false);
  54082. return instance;
  54083. }
  54084. // dashed lines creation
  54085. var dashedLines = new BABYLON.LinesMesh(name, scene);
  54086. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  54087. vertexData.applyToMesh(dashedLines, options.updatable);
  54088. dashedLines.dashSize = dashSize;
  54089. dashedLines.gapSize = gapSize;
  54090. return dashedLines;
  54091. };
  54092. /**
  54093. * Creates an extruded shape mesh.
  54094. * 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.
  54095. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  54096. *
  54097. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  54098. * 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
  54099. * extruded along the Z axis.
  54100. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  54101. * 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.
  54102. * The parameter `scale` (float, default 1) is the value to scale the shape.
  54103. * 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
  54104. * 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
  54105. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  54106. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54107. * 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).
  54108. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54109. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  54110. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54111. */
  54112. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  54113. if (scene === void 0) { scene = null; }
  54114. var path = options.path;
  54115. var shape = options.shape;
  54116. var scale = options.scale || 1;
  54117. var rotation = options.rotation || 0;
  54118. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  54119. var updatable = options.updatable;
  54120. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54121. var instance = options.instance || null;
  54122. var invertUV = options.invertUV || false;
  54123. 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);
  54124. };
  54125. /**
  54126. * Creates an custom extruded shape mesh.
  54127. * 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.
  54128. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  54129. *
  54130. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  54131. * 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
  54132. * extruded along the Z axis.
  54133. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  54134. * 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
  54135. * and the distance of this point from the begining of the path :
  54136. * ```javascript
  54137. * var rotationFunction = function(i, distance) {
  54138. * // do things
  54139. * return rotationValue; }
  54140. * ```
  54141. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  54142. * 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
  54143. * and the distance of this point from the begining of the path :
  54144. * ```javascript
  54145. * var scaleFunction = function(i, distance) {
  54146. * // do things
  54147. * return scaleValue;}
  54148. * ```
  54149. * It must returns a float value that will be the scale value applied to the shape on each path point.
  54150. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  54151. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  54152. * 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
  54153. * 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
  54154. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  54155. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54156. * 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).
  54157. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54158. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  54159. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54160. */
  54161. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  54162. var path = options.path;
  54163. var shape = options.shape;
  54164. var scaleFunction = options.scaleFunction || (function () { return 1; });
  54165. var rotationFunction = options.rotationFunction || (function () { return 0; });
  54166. var ribbonCloseArray = options.ribbonCloseArray || false;
  54167. var ribbonClosePath = options.ribbonClosePath || false;
  54168. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  54169. var updatable = options.updatable;
  54170. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54171. var instance = options.instance;
  54172. var invertUV = options.invertUV || false;
  54173. 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);
  54174. };
  54175. /**
  54176. * Creates lathe mesh.
  54177. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  54178. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  54179. *
  54180. * 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
  54181. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  54182. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  54183. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  54184. * 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.
  54185. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  54186. * 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
  54187. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54188. * 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).
  54189. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54190. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  54191. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54192. */
  54193. MeshBuilder.CreateLathe = function (name, options, scene) {
  54194. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  54195. var closed = (options.closed === undefined) ? true : options.closed;
  54196. var shape = options.shape;
  54197. var radius = options.radius || 1;
  54198. var tessellation = options.tessellation || 64;
  54199. var updatable = options.updatable;
  54200. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54201. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  54202. var pi2 = Math.PI * 2;
  54203. var paths = new Array();
  54204. var invertUV = options.invertUV || false;
  54205. var i = 0;
  54206. var p = 0;
  54207. var step = pi2 / tessellation * arc;
  54208. var rotated;
  54209. var path = new Array();
  54210. ;
  54211. for (i = 0; i <= tessellation; i++) {
  54212. var path = [];
  54213. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  54214. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  54215. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  54216. }
  54217. for (p = 0; p < shape.length; p++) {
  54218. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  54219. path.push(rotated);
  54220. }
  54221. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  54222. 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));
  54223. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  54224. }
  54225. paths.push(path);
  54226. }
  54227. // lathe ribbon
  54228. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  54229. return lathe;
  54230. };
  54231. /**
  54232. * Creates a plane mesh.
  54233. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  54234. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  54235. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  54236. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  54237. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54238. * 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).
  54239. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54240. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54241. */
  54242. MeshBuilder.CreatePlane = function (name, options, scene) {
  54243. var plane = new BABYLON.Mesh(name, scene);
  54244. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54245. plane._originalBuilderSideOrientation = options.sideOrientation;
  54246. var vertexData = BABYLON.VertexData.CreatePlane(options);
  54247. vertexData.applyToMesh(plane, options.updatable);
  54248. if (options.sourcePlane) {
  54249. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  54250. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  54251. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  54252. plane.rotate(vectorProduct, product);
  54253. }
  54254. return plane;
  54255. };
  54256. /**
  54257. * Creates a ground mesh.
  54258. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  54259. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  54260. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  54261. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54262. */
  54263. MeshBuilder.CreateGround = function (name, options, scene) {
  54264. var ground = new BABYLON.GroundMesh(name, scene);
  54265. ground._setReady(false);
  54266. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  54267. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  54268. ground._width = options.width || 1;
  54269. ground._height = options.height || 1;
  54270. ground._maxX = ground._width / 2;
  54271. ground._maxZ = ground._height / 2;
  54272. ground._minX = -ground._maxX;
  54273. ground._minZ = -ground._maxZ;
  54274. var vertexData = BABYLON.VertexData.CreateGround(options);
  54275. vertexData.applyToMesh(ground, options.updatable);
  54276. ground._setReady(true);
  54277. return ground;
  54278. };
  54279. /**
  54280. * Creates a tiled ground mesh.
  54281. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  54282. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  54283. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  54284. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  54285. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  54286. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  54287. * numbers of subdivisions on the ground width and height of each tile.
  54288. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54289. */
  54290. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  54291. var tiledGround = new BABYLON.Mesh(name, scene);
  54292. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  54293. vertexData.applyToMesh(tiledGround, options.updatable);
  54294. return tiledGround;
  54295. };
  54296. /**
  54297. * Creates a ground mesh from a height map.
  54298. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  54299. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  54300. * The parameter `url` sets the URL of the height map image resource.
  54301. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  54302. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  54303. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  54304. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  54305. * 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.
  54306. * 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).
  54307. * This function is passed the newly built mesh :
  54308. * ```javascript
  54309. * function(mesh) { // do things
  54310. * return; }
  54311. * ```
  54312. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54313. */
  54314. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  54315. var width = options.width || 10.0;
  54316. var height = options.height || 10.0;
  54317. var subdivisions = options.subdivisions || 1 | 0;
  54318. var minHeight = options.minHeight || 0.0;
  54319. var maxHeight = options.maxHeight || 1.0;
  54320. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  54321. var updatable = options.updatable;
  54322. var onReady = options.onReady;
  54323. var ground = new BABYLON.GroundMesh(name, scene);
  54324. ground._subdivisionsX = subdivisions;
  54325. ground._subdivisionsY = subdivisions;
  54326. ground._width = width;
  54327. ground._height = height;
  54328. ground._maxX = ground._width / 2.0;
  54329. ground._maxZ = ground._height / 2.0;
  54330. ground._minX = -ground._maxX;
  54331. ground._minZ = -ground._maxZ;
  54332. ground._setReady(false);
  54333. var onload = function (img) {
  54334. // Getting height map data
  54335. var canvas = document.createElement("canvas");
  54336. var context = canvas.getContext("2d");
  54337. if (!context) {
  54338. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  54339. }
  54340. if (scene.isDisposed) {
  54341. return;
  54342. }
  54343. var bufferWidth = img.width;
  54344. var bufferHeight = img.height;
  54345. canvas.width = bufferWidth;
  54346. canvas.height = bufferHeight;
  54347. context.drawImage(img, 0, 0);
  54348. // Create VertexData from map data
  54349. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  54350. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  54351. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  54352. width: width, height: height,
  54353. subdivisions: subdivisions,
  54354. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  54355. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  54356. });
  54357. vertexData.applyToMesh(ground, updatable);
  54358. ground._setReady(true);
  54359. //execute ready callback, if set
  54360. if (onReady) {
  54361. onReady(ground);
  54362. }
  54363. };
  54364. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  54365. return ground;
  54366. };
  54367. /**
  54368. * Creates a polygon mesh.
  54369. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  54370. * 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.
  54371. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54372. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54373. * 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).
  54374. * Remember you can only change the shape positions, not their number when updating a polygon.
  54375. */
  54376. MeshBuilder.CreatePolygon = function (name, options, scene) {
  54377. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54378. var shape = options.shape;
  54379. var holes = options.holes || [];
  54380. var depth = options.depth || 0;
  54381. var contours = [];
  54382. var hole = [];
  54383. for (var i = 0; i < shape.length; i++) {
  54384. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  54385. }
  54386. var epsilon = 0.00000001;
  54387. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  54388. contours.pop();
  54389. }
  54390. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  54391. for (var hNb = 0; hNb < holes.length; hNb++) {
  54392. hole = [];
  54393. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  54394. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  54395. }
  54396. polygonTriangulation.addHole(hole);
  54397. }
  54398. var polygon = polygonTriangulation.build(options.updatable, depth);
  54399. polygon._originalBuilderSideOrientation = options.sideOrientation;
  54400. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  54401. vertexData.applyToMesh(polygon, options.updatable);
  54402. return polygon;
  54403. };
  54404. ;
  54405. /**
  54406. * Creates an extruded polygon mesh, with depth in the Y direction.
  54407. * 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).
  54408. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  54409. */
  54410. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  54411. return MeshBuilder.CreatePolygon(name, options, scene);
  54412. };
  54413. ;
  54414. /**
  54415. * Creates a tube mesh.
  54416. * 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.
  54417. *
  54418. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  54419. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  54420. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  54421. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  54422. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  54423. * 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.
  54424. * It must return a radius value (positive float) :
  54425. * ```javascript
  54426. * var radiusFunction = function(i, distance) {
  54427. * // do things
  54428. * return radius; }
  54429. * ```
  54430. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  54431. * 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
  54432. * 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
  54433. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54434. * 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).
  54435. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54436. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  54437. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54438. */
  54439. MeshBuilder.CreateTube = function (name, options, scene) {
  54440. var path = options.path;
  54441. var instance = options.instance;
  54442. var radius = 1.0;
  54443. if (instance) {
  54444. radius = instance.radius;
  54445. }
  54446. if (options.radius !== undefined) {
  54447. radius = options.radius;
  54448. }
  54449. ;
  54450. var tessellation = options.tessellation || 64 | 0;
  54451. var radiusFunction = options.radiusFunction || null;
  54452. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  54453. var invertUV = options.invertUV || false;
  54454. var updatable = options.updatable;
  54455. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54456. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  54457. // tube geometry
  54458. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  54459. var tangents = path3D.getTangents();
  54460. var normals = path3D.getNormals();
  54461. var distances = path3D.getDistances();
  54462. var pi2 = Math.PI * 2;
  54463. var step = pi2 / tessellation * arc;
  54464. var returnRadius = function () { return radius; };
  54465. var radiusFunctionFinal = radiusFunction || returnRadius;
  54466. var circlePath;
  54467. var rad;
  54468. var normal;
  54469. var rotated;
  54470. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  54471. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  54472. for (var i = 0; i < path.length; i++) {
  54473. rad = radiusFunctionFinal(i, distances[i]); // current radius
  54474. circlePath = Array(); // current circle array
  54475. normal = normals[i]; // current normal
  54476. for (var t = 0; t < tessellation; t++) {
  54477. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  54478. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  54479. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  54480. rotated.scaleInPlace(rad).addInPlace(path[i]);
  54481. circlePath[t] = rotated;
  54482. }
  54483. circlePaths[index] = circlePath;
  54484. index++;
  54485. }
  54486. // cap
  54487. var capPath = function (nbPoints, pathIndex) {
  54488. var pointCap = Array();
  54489. for (var i = 0; i < nbPoints; i++) {
  54490. pointCap.push(path[pathIndex]);
  54491. }
  54492. return pointCap;
  54493. };
  54494. switch (cap) {
  54495. case BABYLON.Mesh.NO_CAP:
  54496. break;
  54497. case BABYLON.Mesh.CAP_START:
  54498. circlePaths[0] = capPath(tessellation, 0);
  54499. circlePaths[1] = circlePaths[2].slice(0);
  54500. break;
  54501. case BABYLON.Mesh.CAP_END:
  54502. circlePaths[index] = circlePaths[index - 1].slice(0);
  54503. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  54504. break;
  54505. case BABYLON.Mesh.CAP_ALL:
  54506. circlePaths[0] = capPath(tessellation, 0);
  54507. circlePaths[1] = circlePaths[2].slice(0);
  54508. circlePaths[index] = circlePaths[index - 1].slice(0);
  54509. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  54510. break;
  54511. default:
  54512. break;
  54513. }
  54514. return circlePaths;
  54515. };
  54516. var path3D;
  54517. var pathArray;
  54518. if (instance) {
  54519. var arc = options.arc || instance.arc;
  54520. path3D = (instance.path3D).update(path);
  54521. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  54522. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  54523. instance.path3D = path3D;
  54524. instance.pathArray = pathArray;
  54525. instance.arc = arc;
  54526. instance.radius = radius;
  54527. return instance;
  54528. }
  54529. // tube creation
  54530. path3D = new BABYLON.Path3D(path);
  54531. var newPathArray = new Array();
  54532. cap = (cap < 0 || cap > 3) ? 0 : cap;
  54533. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  54534. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  54535. tube.pathArray = pathArray;
  54536. tube.path3D = path3D;
  54537. tube.tessellation = tessellation;
  54538. tube.cap = cap;
  54539. tube.arc = options.arc;
  54540. tube.radius = radius;
  54541. return tube;
  54542. };
  54543. /**
  54544. * Creates a polyhedron mesh.
  54545. *
  54546. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  54547. * 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
  54548. * to choose the wanted type.
  54549. * The parameter `size` (positive float, default 1) sets the polygon size.
  54550. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  54551. * 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`.
  54552. * 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
  54553. * 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)`).
  54554. * 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
  54555. * 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.
  54556. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54557. * 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).
  54558. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54559. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54560. */
  54561. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  54562. var polyhedron = new BABYLON.Mesh(name, scene);
  54563. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54564. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  54565. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  54566. vertexData.applyToMesh(polyhedron, options.updatable);
  54567. return polyhedron;
  54568. };
  54569. /**
  54570. * Creates a decal mesh.
  54571. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  54572. * 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.
  54573. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  54574. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  54575. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  54576. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  54577. */
  54578. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  54579. var indices = sourceMesh.getIndices();
  54580. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  54581. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  54582. var position = options.position || BABYLON.Vector3.Zero();
  54583. var normal = options.normal || BABYLON.Vector3.Up();
  54584. var size = options.size || BABYLON.Vector3.One();
  54585. var angle = options.angle || 0;
  54586. // Getting correct rotation
  54587. if (!normal) {
  54588. var target = new BABYLON.Vector3(0, 0, 1);
  54589. var camera = sourceMesh.getScene().activeCamera;
  54590. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  54591. normal = camera.globalPosition.subtract(cameraWorldTarget);
  54592. }
  54593. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  54594. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  54595. var pitch = Math.atan2(normal.y, len);
  54596. // Matrix
  54597. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  54598. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  54599. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  54600. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  54601. var vertexData = new BABYLON.VertexData();
  54602. vertexData.indices = [];
  54603. vertexData.positions = [];
  54604. vertexData.normals = [];
  54605. vertexData.uvs = [];
  54606. var currentVertexDataIndex = 0;
  54607. var extractDecalVector3 = function (indexId) {
  54608. var result = new BABYLON.PositionNormalVertex();
  54609. if (!indices || !positions || !normals) {
  54610. return result;
  54611. }
  54612. var vertexId = indices[indexId];
  54613. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  54614. // Send vector to decal local world
  54615. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  54616. // Get normal
  54617. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  54618. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  54619. return result;
  54620. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  54621. var clip = function (vertices, axis) {
  54622. if (vertices.length === 0) {
  54623. return vertices;
  54624. }
  54625. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  54626. var clipVertices = function (v0, v1) {
  54627. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  54628. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  54629. };
  54630. var result = new Array();
  54631. for (var index = 0; index < vertices.length; index += 3) {
  54632. var v1Out;
  54633. var v2Out;
  54634. var v3Out;
  54635. var total = 0;
  54636. var nV1 = null;
  54637. var nV2 = null;
  54638. var nV3 = null;
  54639. var nV4 = null;
  54640. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  54641. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  54642. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  54643. v1Out = d1 > 0;
  54644. v2Out = d2 > 0;
  54645. v3Out = d3 > 0;
  54646. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  54647. switch (total) {
  54648. case 0:
  54649. result.push(vertices[index]);
  54650. result.push(vertices[index + 1]);
  54651. result.push(vertices[index + 2]);
  54652. break;
  54653. case 1:
  54654. if (v1Out) {
  54655. nV1 = vertices[index + 1];
  54656. nV2 = vertices[index + 2];
  54657. nV3 = clipVertices(vertices[index], nV1);
  54658. nV4 = clipVertices(vertices[index], nV2);
  54659. }
  54660. if (v2Out) {
  54661. nV1 = vertices[index];
  54662. nV2 = vertices[index + 2];
  54663. nV3 = clipVertices(vertices[index + 1], nV1);
  54664. nV4 = clipVertices(vertices[index + 1], nV2);
  54665. result.push(nV3);
  54666. result.push(nV2.clone());
  54667. result.push(nV1.clone());
  54668. result.push(nV2.clone());
  54669. result.push(nV3.clone());
  54670. result.push(nV4);
  54671. break;
  54672. }
  54673. if (v3Out) {
  54674. nV1 = vertices[index];
  54675. nV2 = vertices[index + 1];
  54676. nV3 = clipVertices(vertices[index + 2], nV1);
  54677. nV4 = clipVertices(vertices[index + 2], nV2);
  54678. }
  54679. if (nV1 && nV2 && nV3 && nV4) {
  54680. result.push(nV1.clone());
  54681. result.push(nV2.clone());
  54682. result.push(nV3);
  54683. result.push(nV4);
  54684. result.push(nV3.clone());
  54685. result.push(nV2.clone());
  54686. }
  54687. break;
  54688. case 2:
  54689. if (!v1Out) {
  54690. nV1 = vertices[index].clone();
  54691. nV2 = clipVertices(nV1, vertices[index + 1]);
  54692. nV3 = clipVertices(nV1, vertices[index + 2]);
  54693. result.push(nV1);
  54694. result.push(nV2);
  54695. result.push(nV3);
  54696. }
  54697. if (!v2Out) {
  54698. nV1 = vertices[index + 1].clone();
  54699. nV2 = clipVertices(nV1, vertices[index + 2]);
  54700. nV3 = clipVertices(nV1, vertices[index]);
  54701. result.push(nV1);
  54702. result.push(nV2);
  54703. result.push(nV3);
  54704. }
  54705. if (!v3Out) {
  54706. nV1 = vertices[index + 2].clone();
  54707. nV2 = clipVertices(nV1, vertices[index]);
  54708. nV3 = clipVertices(nV1, vertices[index + 1]);
  54709. result.push(nV1);
  54710. result.push(nV2);
  54711. result.push(nV3);
  54712. }
  54713. break;
  54714. case 3:
  54715. break;
  54716. }
  54717. }
  54718. return result;
  54719. };
  54720. for (var index = 0; index < indices.length; index += 3) {
  54721. var faceVertices = new Array();
  54722. faceVertices.push(extractDecalVector3(index));
  54723. faceVertices.push(extractDecalVector3(index + 1));
  54724. faceVertices.push(extractDecalVector3(index + 2));
  54725. // Clip
  54726. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  54727. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  54728. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  54729. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  54730. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  54731. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  54732. if (faceVertices.length === 0) {
  54733. continue;
  54734. }
  54735. // Add UVs and get back to world
  54736. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  54737. var vertex = faceVertices[vIndex];
  54738. //TODO check for Int32Array | Uint32Array | Uint16Array
  54739. vertexData.indices.push(currentVertexDataIndex);
  54740. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  54741. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  54742. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  54743. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  54744. currentVertexDataIndex++;
  54745. }
  54746. }
  54747. // Return mesh
  54748. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  54749. vertexData.applyToMesh(decal);
  54750. decal.position = position.clone();
  54751. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  54752. return decal;
  54753. };
  54754. // Privates
  54755. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  54756. // extrusion geometry
  54757. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  54758. var tangents = path3D.getTangents();
  54759. var normals = path3D.getNormals();
  54760. var binormals = path3D.getBinormals();
  54761. var distances = path3D.getDistances();
  54762. var angle = 0;
  54763. var returnScale = function () { return scale !== null ? scale : 1; };
  54764. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  54765. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  54766. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  54767. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  54768. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  54769. for (var i = 0; i < curve.length; i++) {
  54770. var shapePath = new Array();
  54771. var angleStep = rotate(i, distances[i]);
  54772. var scaleRatio = scl(i, distances[i]);
  54773. for (var p = 0; p < shape.length; p++) {
  54774. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  54775. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  54776. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  54777. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  54778. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  54779. shapePath[p] = rotated;
  54780. }
  54781. shapePaths[index] = shapePath;
  54782. angle += angleStep;
  54783. index++;
  54784. }
  54785. // cap
  54786. var capPath = function (shapePath) {
  54787. var pointCap = Array();
  54788. var barycenter = BABYLON.Vector3.Zero();
  54789. var i;
  54790. for (i = 0; i < shapePath.length; i++) {
  54791. barycenter.addInPlace(shapePath[i]);
  54792. }
  54793. barycenter.scaleInPlace(1.0 / shapePath.length);
  54794. for (i = 0; i < shapePath.length; i++) {
  54795. pointCap.push(barycenter);
  54796. }
  54797. return pointCap;
  54798. };
  54799. switch (cap) {
  54800. case BABYLON.Mesh.NO_CAP:
  54801. break;
  54802. case BABYLON.Mesh.CAP_START:
  54803. shapePaths[0] = capPath(shapePaths[2]);
  54804. shapePaths[1] = shapePaths[2];
  54805. break;
  54806. case BABYLON.Mesh.CAP_END:
  54807. shapePaths[index] = shapePaths[index - 1];
  54808. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  54809. break;
  54810. case BABYLON.Mesh.CAP_ALL:
  54811. shapePaths[0] = capPath(shapePaths[2]);
  54812. shapePaths[1] = shapePaths[2];
  54813. shapePaths[index] = shapePaths[index - 1];
  54814. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  54815. break;
  54816. default:
  54817. break;
  54818. }
  54819. return shapePaths;
  54820. };
  54821. var path3D;
  54822. var pathArray;
  54823. if (instance) {
  54824. path3D = (instance.path3D).update(curve);
  54825. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  54826. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  54827. return instance;
  54828. }
  54829. // extruded shape creation
  54830. path3D = new BABYLON.Path3D(curve);
  54831. var newShapePaths = new Array();
  54832. cap = (cap < 0 || cap > 3) ? 0 : cap;
  54833. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  54834. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  54835. extrudedGeneric.pathArray = pathArray;
  54836. extrudedGeneric.path3D = path3D;
  54837. extrudedGeneric.cap = cap;
  54838. return extrudedGeneric;
  54839. };
  54840. return MeshBuilder;
  54841. }());
  54842. BABYLON.MeshBuilder = MeshBuilder;
  54843. })(BABYLON || (BABYLON = {}));
  54844. //# sourceMappingURL=babylon.meshBuilder.js.map
  54845. var BABYLON;
  54846. (function (BABYLON) {
  54847. var AudioEngine = /** @class */ (function () {
  54848. function AudioEngine() {
  54849. this._audioContext = null;
  54850. this._audioContextInitialized = false;
  54851. this.canUseWebAudio = false;
  54852. this.WarnedWebAudioUnsupported = false;
  54853. this.unlocked = false;
  54854. this.isMP3supported = false;
  54855. this.isOGGsupported = false;
  54856. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  54857. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  54858. this.canUseWebAudio = true;
  54859. }
  54860. var audioElem = document.createElement('audio');
  54861. try {
  54862. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  54863. this.isMP3supported = true;
  54864. }
  54865. }
  54866. catch (e) {
  54867. // protect error during capability check.
  54868. }
  54869. try {
  54870. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  54871. this.isOGGsupported = true;
  54872. }
  54873. }
  54874. catch (e) {
  54875. // protect error during capability check.
  54876. }
  54877. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  54878. this._unlockiOSaudio();
  54879. }
  54880. else {
  54881. this.unlocked = true;
  54882. }
  54883. }
  54884. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  54885. get: function () {
  54886. if (!this._audioContextInitialized) {
  54887. this._initializeAudioContext();
  54888. }
  54889. return this._audioContext;
  54890. },
  54891. enumerable: true,
  54892. configurable: true
  54893. });
  54894. AudioEngine.prototype._unlockiOSaudio = function () {
  54895. var _this = this;
  54896. var unlockaudio = function () {
  54897. if (!_this.audioContext) {
  54898. return;
  54899. }
  54900. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  54901. var source = _this.audioContext.createBufferSource();
  54902. source.buffer = buffer;
  54903. source.connect(_this.audioContext.destination);
  54904. source.start(0);
  54905. setTimeout(function () {
  54906. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  54907. _this.unlocked = true;
  54908. window.removeEventListener('touchend', unlockaudio, false);
  54909. if (_this.onAudioUnlocked) {
  54910. _this.onAudioUnlocked();
  54911. }
  54912. }
  54913. }, 0);
  54914. };
  54915. window.addEventListener('touchend', unlockaudio, false);
  54916. };
  54917. AudioEngine.prototype._initializeAudioContext = function () {
  54918. try {
  54919. if (this.canUseWebAudio) {
  54920. this._audioContext = new AudioContext();
  54921. // create a global volume gain node
  54922. this.masterGain = this._audioContext.createGain();
  54923. this.masterGain.gain.value = 1;
  54924. this.masterGain.connect(this._audioContext.destination);
  54925. this._audioContextInitialized = true;
  54926. }
  54927. }
  54928. catch (e) {
  54929. this.canUseWebAudio = false;
  54930. BABYLON.Tools.Error("Web Audio: " + e.message);
  54931. }
  54932. };
  54933. AudioEngine.prototype.dispose = function () {
  54934. if (this.canUseWebAudio && this._audioContextInitialized) {
  54935. if (this._connectedAnalyser && this._audioContext) {
  54936. this._connectedAnalyser.stopDebugCanvas();
  54937. this._connectedAnalyser.dispose();
  54938. this.masterGain.disconnect();
  54939. this.masterGain.connect(this._audioContext.destination);
  54940. this._connectedAnalyser = null;
  54941. }
  54942. this.masterGain.gain.value = 1;
  54943. }
  54944. this.WarnedWebAudioUnsupported = false;
  54945. };
  54946. AudioEngine.prototype.getGlobalVolume = function () {
  54947. if (this.canUseWebAudio && this._audioContextInitialized) {
  54948. return this.masterGain.gain.value;
  54949. }
  54950. else {
  54951. return -1;
  54952. }
  54953. };
  54954. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  54955. if (this.canUseWebAudio && this._audioContextInitialized) {
  54956. this.masterGain.gain.value = newVolume;
  54957. }
  54958. };
  54959. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  54960. if (this._connectedAnalyser) {
  54961. this._connectedAnalyser.stopDebugCanvas();
  54962. }
  54963. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  54964. this._connectedAnalyser = analyser;
  54965. this.masterGain.disconnect();
  54966. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  54967. }
  54968. };
  54969. return AudioEngine;
  54970. }());
  54971. BABYLON.AudioEngine = AudioEngine;
  54972. })(BABYLON || (BABYLON = {}));
  54973. //# sourceMappingURL=babylon.audioEngine.js.map
  54974. var BABYLON;
  54975. (function (BABYLON) {
  54976. var Sound = /** @class */ (function () {
  54977. /**
  54978. * Create a sound and attach it to a scene
  54979. * @param name Name of your sound
  54980. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  54981. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  54982. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  54983. */
  54984. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  54985. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  54986. var _this = this;
  54987. this.autoplay = false;
  54988. this.loop = false;
  54989. this.useCustomAttenuation = false;
  54990. this.spatialSound = false;
  54991. this.refDistance = 1;
  54992. this.rolloffFactor = 1;
  54993. this.maxDistance = 100;
  54994. this.distanceModel = "linear";
  54995. this._panningModel = "equalpower";
  54996. this._playbackRate = 1;
  54997. this._streaming = false;
  54998. this._startTime = 0;
  54999. this._startOffset = 0;
  55000. this._position = BABYLON.Vector3.Zero();
  55001. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  55002. this._volume = 1;
  55003. this._isReadyToPlay = false;
  55004. this.isPlaying = false;
  55005. this.isPaused = false;
  55006. this._isDirectional = false;
  55007. // Used if you'd like to create a directional sound.
  55008. // If not set, the sound will be omnidirectional
  55009. this._coneInnerAngle = 360;
  55010. this._coneOuterAngle = 360;
  55011. this._coneOuterGain = 0;
  55012. this._isOutputConnected = false;
  55013. this._urlType = "Unknown";
  55014. this.name = name;
  55015. this._scene = scene;
  55016. this._readyToPlayCallback = readyToPlayCallback;
  55017. // Default custom attenuation function is a linear attenuation
  55018. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  55019. if (currentDistance < maxDistance) {
  55020. return currentVolume * (1 - currentDistance / maxDistance);
  55021. }
  55022. else {
  55023. return 0;
  55024. }
  55025. };
  55026. if (options) {
  55027. this.autoplay = options.autoplay || false;
  55028. this.loop = options.loop || false;
  55029. // if volume === 0, we need another way to check this option
  55030. if (options.volume !== undefined) {
  55031. this._volume = options.volume;
  55032. }
  55033. this.spatialSound = options.spatialSound || false;
  55034. this.maxDistance = options.maxDistance || 100;
  55035. this.useCustomAttenuation = options.useCustomAttenuation || false;
  55036. this.rolloffFactor = options.rolloffFactor || 1;
  55037. this.refDistance = options.refDistance || 1;
  55038. this.distanceModel = options.distanceModel || "linear";
  55039. this._playbackRate = options.playbackRate || 1;
  55040. this._streaming = options.streaming || false;
  55041. }
  55042. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  55043. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  55044. this._soundGain.gain.value = this._volume;
  55045. this._inputAudioNode = this._soundGain;
  55046. this._ouputAudioNode = this._soundGain;
  55047. if (this.spatialSound) {
  55048. this._createSpatialParameters();
  55049. }
  55050. this._scene.mainSoundTrack.AddSound(this);
  55051. var validParameter = true;
  55052. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  55053. if (urlOrArrayBuffer) {
  55054. if (typeof (urlOrArrayBuffer) === "string")
  55055. this._urlType = "String";
  55056. if (Array.isArray(urlOrArrayBuffer))
  55057. this._urlType = "Array";
  55058. if (urlOrArrayBuffer instanceof ArrayBuffer)
  55059. this._urlType = "ArrayBuffer";
  55060. var urls = [];
  55061. var codecSupportedFound = false;
  55062. switch (this._urlType) {
  55063. case "ArrayBuffer":
  55064. if (urlOrArrayBuffer.byteLength > 0) {
  55065. codecSupportedFound = true;
  55066. this._soundLoaded(urlOrArrayBuffer);
  55067. }
  55068. break;
  55069. case "String":
  55070. urls.push(urlOrArrayBuffer);
  55071. case "Array":
  55072. if (urls.length === 0)
  55073. urls = urlOrArrayBuffer;
  55074. // If we found a supported format, we load it immediately and stop the loop
  55075. for (var i = 0; i < urls.length; i++) {
  55076. var url = urls[i];
  55077. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  55078. codecSupportedFound = true;
  55079. }
  55080. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  55081. codecSupportedFound = true;
  55082. }
  55083. if (url.indexOf(".wav", url.length - 4) !== -1) {
  55084. codecSupportedFound = true;
  55085. }
  55086. if (url.indexOf("blob:") !== -1) {
  55087. codecSupportedFound = true;
  55088. }
  55089. if (codecSupportedFound) {
  55090. // Loading sound using XHR2
  55091. if (!this._streaming) {
  55092. this._scene._loadFile(url, function (data) { _this._soundLoaded(data); }, undefined, true, true);
  55093. }
  55094. else {
  55095. this._htmlAudioElement = new Audio(url);
  55096. this._htmlAudioElement.controls = false;
  55097. this._htmlAudioElement.loop = this.loop;
  55098. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  55099. this._htmlAudioElement.preload = "auto";
  55100. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  55101. _this._isReadyToPlay = true;
  55102. if (_this.autoplay) {
  55103. _this.play();
  55104. }
  55105. if (_this._readyToPlayCallback) {
  55106. _this._readyToPlayCallback();
  55107. }
  55108. });
  55109. document.body.appendChild(this._htmlAudioElement);
  55110. }
  55111. break;
  55112. }
  55113. }
  55114. break;
  55115. default:
  55116. validParameter = false;
  55117. break;
  55118. }
  55119. if (!validParameter) {
  55120. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  55121. }
  55122. else {
  55123. if (!codecSupportedFound) {
  55124. this._isReadyToPlay = true;
  55125. // Simulating a ready to play event to avoid breaking code path
  55126. if (this._readyToPlayCallback) {
  55127. window.setTimeout(function () {
  55128. if (_this._readyToPlayCallback) {
  55129. _this._readyToPlayCallback();
  55130. }
  55131. }, 1000);
  55132. }
  55133. }
  55134. }
  55135. }
  55136. }
  55137. else {
  55138. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  55139. this._scene.mainSoundTrack.AddSound(this);
  55140. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  55141. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  55142. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  55143. }
  55144. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  55145. if (this._readyToPlayCallback) {
  55146. window.setTimeout(function () {
  55147. if (_this._readyToPlayCallback) {
  55148. _this._readyToPlayCallback();
  55149. }
  55150. }, 1000);
  55151. }
  55152. }
  55153. }
  55154. Sound.prototype.dispose = function () {
  55155. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  55156. if (this.isPlaying) {
  55157. this.stop();
  55158. }
  55159. this._isReadyToPlay = false;
  55160. if (this.soundTrackId === -1) {
  55161. this._scene.mainSoundTrack.RemoveSound(this);
  55162. }
  55163. else {
  55164. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  55165. }
  55166. if (this._soundGain) {
  55167. this._soundGain.disconnect();
  55168. this._soundGain = null;
  55169. }
  55170. if (this._soundPanner) {
  55171. this._soundPanner.disconnect();
  55172. this._soundPanner = null;
  55173. }
  55174. if (this._soundSource) {
  55175. this._soundSource.disconnect();
  55176. this._soundSource = null;
  55177. }
  55178. this._audioBuffer = null;
  55179. if (this._htmlAudioElement) {
  55180. this._htmlAudioElement.pause();
  55181. this._htmlAudioElement.src = "";
  55182. document.body.removeChild(this._htmlAudioElement);
  55183. }
  55184. if (this._connectedMesh && this._registerFunc) {
  55185. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  55186. this._connectedMesh = null;
  55187. }
  55188. }
  55189. };
  55190. Sound.prototype.isReady = function () {
  55191. return this._isReadyToPlay;
  55192. };
  55193. Sound.prototype._soundLoaded = function (audioData) {
  55194. var _this = this;
  55195. if (!BABYLON.Engine.audioEngine.audioContext) {
  55196. return;
  55197. }
  55198. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  55199. _this._audioBuffer = buffer;
  55200. _this._isReadyToPlay = true;
  55201. if (_this.autoplay) {
  55202. _this.play();
  55203. }
  55204. if (_this._readyToPlayCallback) {
  55205. _this._readyToPlayCallback();
  55206. }
  55207. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  55208. };
  55209. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  55210. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  55211. this._audioBuffer = audioBuffer;
  55212. this._isReadyToPlay = true;
  55213. }
  55214. };
  55215. Sound.prototype.updateOptions = function (options) {
  55216. if (options) {
  55217. this.loop = options.loop || this.loop;
  55218. this.maxDistance = options.maxDistance || this.maxDistance;
  55219. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  55220. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  55221. this.refDistance = options.refDistance || this.refDistance;
  55222. this.distanceModel = options.distanceModel || this.distanceModel;
  55223. this._playbackRate = options.playbackRate || this._playbackRate;
  55224. this._updateSpatialParameters();
  55225. if (this.isPlaying) {
  55226. if (this._streaming) {
  55227. this._htmlAudioElement.playbackRate = this._playbackRate;
  55228. }
  55229. else {
  55230. if (this._soundSource) {
  55231. this._soundSource.playbackRate.value = this._playbackRate;
  55232. }
  55233. }
  55234. }
  55235. }
  55236. };
  55237. Sound.prototype._createSpatialParameters = function () {
  55238. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  55239. if (this._scene.headphone) {
  55240. this._panningModel = "HRTF";
  55241. }
  55242. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  55243. this._updateSpatialParameters();
  55244. this._soundPanner.connect(this._ouputAudioNode);
  55245. this._inputAudioNode = this._soundPanner;
  55246. }
  55247. };
  55248. Sound.prototype._updateSpatialParameters = function () {
  55249. if (this.spatialSound && this._soundPanner) {
  55250. if (this.useCustomAttenuation) {
  55251. // Tricks to disable in a way embedded Web Audio attenuation
  55252. this._soundPanner.distanceModel = "linear";
  55253. this._soundPanner.maxDistance = Number.MAX_VALUE;
  55254. this._soundPanner.refDistance = 1;
  55255. this._soundPanner.rolloffFactor = 1;
  55256. this._soundPanner.panningModel = this._panningModel;
  55257. }
  55258. else {
  55259. this._soundPanner.distanceModel = this.distanceModel;
  55260. this._soundPanner.maxDistance = this.maxDistance;
  55261. this._soundPanner.refDistance = this.refDistance;
  55262. this._soundPanner.rolloffFactor = this.rolloffFactor;
  55263. this._soundPanner.panningModel = this._panningModel;
  55264. }
  55265. }
  55266. };
  55267. Sound.prototype.switchPanningModelToHRTF = function () {
  55268. this._panningModel = "HRTF";
  55269. this._switchPanningModel();
  55270. };
  55271. Sound.prototype.switchPanningModelToEqualPower = function () {
  55272. this._panningModel = "equalpower";
  55273. this._switchPanningModel();
  55274. };
  55275. Sound.prototype._switchPanningModel = function () {
  55276. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  55277. this._soundPanner.panningModel = this._panningModel;
  55278. }
  55279. };
  55280. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  55281. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  55282. if (this._isOutputConnected) {
  55283. this._ouputAudioNode.disconnect();
  55284. }
  55285. this._ouputAudioNode.connect(soundTrackAudioNode);
  55286. this._isOutputConnected = true;
  55287. }
  55288. };
  55289. /**
  55290. * Transform this sound into a directional source
  55291. * @param coneInnerAngle Size of the inner cone in degree
  55292. * @param coneOuterAngle Size of the outer cone in degree
  55293. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  55294. */
  55295. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  55296. if (coneOuterAngle < coneInnerAngle) {
  55297. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  55298. return;
  55299. }
  55300. this._coneInnerAngle = coneInnerAngle;
  55301. this._coneOuterAngle = coneOuterAngle;
  55302. this._coneOuterGain = coneOuterGain;
  55303. this._isDirectional = true;
  55304. if (this.isPlaying && this.loop) {
  55305. this.stop();
  55306. this.play();
  55307. }
  55308. };
  55309. Sound.prototype.setPosition = function (newPosition) {
  55310. this._position = newPosition;
  55311. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  55312. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  55313. }
  55314. };
  55315. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  55316. this._localDirection = newLocalDirection;
  55317. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  55318. this._updateDirection();
  55319. }
  55320. };
  55321. Sound.prototype._updateDirection = function () {
  55322. if (!this._connectedMesh || !this._soundPanner) {
  55323. return;
  55324. }
  55325. var mat = this._connectedMesh.getWorldMatrix();
  55326. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  55327. direction.normalize();
  55328. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  55329. };
  55330. Sound.prototype.updateDistanceFromListener = function () {
  55331. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  55332. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  55333. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  55334. }
  55335. };
  55336. Sound.prototype.setAttenuationFunction = function (callback) {
  55337. this._customAttenuationFunction = callback;
  55338. };
  55339. /**
  55340. * Play the sound
  55341. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  55342. * @param offset (optional) Start the sound setting it at a specific time
  55343. */
  55344. Sound.prototype.play = function (time, offset) {
  55345. var _this = this;
  55346. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  55347. try {
  55348. if (this._startOffset < 0) {
  55349. time = -this._startOffset;
  55350. this._startOffset = 0;
  55351. }
  55352. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  55353. if (!this._soundSource || !this._streamingSource) {
  55354. if (this.spatialSound && this._soundPanner) {
  55355. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  55356. if (this._isDirectional) {
  55357. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  55358. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  55359. this._soundPanner.coneOuterGain = this._coneOuterGain;
  55360. if (this._connectedMesh) {
  55361. this._updateDirection();
  55362. }
  55363. else {
  55364. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  55365. }
  55366. }
  55367. }
  55368. }
  55369. if (this._streaming) {
  55370. if (!this._streamingSource) {
  55371. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  55372. this._htmlAudioElement.onended = function () { _this._onended(); };
  55373. this._htmlAudioElement.playbackRate = this._playbackRate;
  55374. }
  55375. this._streamingSource.disconnect();
  55376. this._streamingSource.connect(this._inputAudioNode);
  55377. this._htmlAudioElement.play();
  55378. }
  55379. else {
  55380. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  55381. this._soundSource.buffer = this._audioBuffer;
  55382. this._soundSource.connect(this._inputAudioNode);
  55383. this._soundSource.loop = this.loop;
  55384. this._soundSource.playbackRate.value = this._playbackRate;
  55385. this._soundSource.onended = function () { _this._onended(); };
  55386. if (this._soundSource.buffer) {
  55387. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  55388. }
  55389. }
  55390. this._startTime = startTime;
  55391. this.isPlaying = true;
  55392. this.isPaused = false;
  55393. }
  55394. catch (ex) {
  55395. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  55396. }
  55397. }
  55398. };
  55399. Sound.prototype._onended = function () {
  55400. this.isPlaying = false;
  55401. if (this.onended) {
  55402. this.onended();
  55403. }
  55404. };
  55405. /**
  55406. * Stop the sound
  55407. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  55408. */
  55409. Sound.prototype.stop = function (time) {
  55410. if (this.isPlaying) {
  55411. if (this._streaming) {
  55412. this._htmlAudioElement.pause();
  55413. // Test needed for Firefox or it will generate an Invalid State Error
  55414. if (this._htmlAudioElement.currentTime > 0) {
  55415. this._htmlAudioElement.currentTime = 0;
  55416. }
  55417. }
  55418. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  55419. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  55420. this._soundSource.stop(stopTime);
  55421. this._soundSource.onended = function () { };
  55422. if (!this.isPaused) {
  55423. this._startOffset = 0;
  55424. }
  55425. }
  55426. this.isPlaying = false;
  55427. }
  55428. };
  55429. Sound.prototype.pause = function () {
  55430. if (this.isPlaying) {
  55431. this.isPaused = true;
  55432. if (this._streaming) {
  55433. this._htmlAudioElement.pause();
  55434. }
  55435. else if (BABYLON.Engine.audioEngine.audioContext) {
  55436. this.stop(0);
  55437. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  55438. }
  55439. }
  55440. };
  55441. Sound.prototype.setVolume = function (newVolume, time) {
  55442. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  55443. if (time && BABYLON.Engine.audioEngine.audioContext) {
  55444. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  55445. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  55446. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  55447. }
  55448. else {
  55449. this._soundGain.gain.value = newVolume;
  55450. }
  55451. }
  55452. this._volume = newVolume;
  55453. };
  55454. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  55455. this._playbackRate = newPlaybackRate;
  55456. if (this.isPlaying) {
  55457. if (this._streaming) {
  55458. this._htmlAudioElement.playbackRate = this._playbackRate;
  55459. }
  55460. else if (this._soundSource) {
  55461. this._soundSource.playbackRate.value = this._playbackRate;
  55462. }
  55463. }
  55464. };
  55465. Sound.prototype.getVolume = function () {
  55466. return this._volume;
  55467. };
  55468. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  55469. var _this = this;
  55470. if (this._connectedMesh && this._registerFunc) {
  55471. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  55472. this._registerFunc = null;
  55473. }
  55474. this._connectedMesh = meshToConnectTo;
  55475. if (!this.spatialSound) {
  55476. this.spatialSound = true;
  55477. this._createSpatialParameters();
  55478. if (this.isPlaying && this.loop) {
  55479. this.stop();
  55480. this.play();
  55481. }
  55482. }
  55483. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  55484. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  55485. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  55486. };
  55487. Sound.prototype.detachFromMesh = function () {
  55488. if (this._connectedMesh && this._registerFunc) {
  55489. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  55490. this._registerFunc = null;
  55491. this._connectedMesh = null;
  55492. }
  55493. };
  55494. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  55495. if (!node.getBoundingInfo) {
  55496. return;
  55497. }
  55498. var mesh = node;
  55499. var boundingInfo = mesh.getBoundingInfo();
  55500. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  55501. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  55502. this._updateDirection();
  55503. }
  55504. };
  55505. Sound.prototype.clone = function () {
  55506. var _this = this;
  55507. if (!this._streaming) {
  55508. var setBufferAndRun = function () {
  55509. if (_this._isReadyToPlay) {
  55510. clonedSound._audioBuffer = _this.getAudioBuffer();
  55511. clonedSound._isReadyToPlay = true;
  55512. if (clonedSound.autoplay) {
  55513. clonedSound.play();
  55514. }
  55515. }
  55516. else {
  55517. window.setTimeout(setBufferAndRun, 300);
  55518. }
  55519. };
  55520. var currentOptions = {
  55521. autoplay: this.autoplay, loop: this.loop,
  55522. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  55523. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  55524. refDistance: this.refDistance, distanceModel: this.distanceModel
  55525. };
  55526. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  55527. if (this.useCustomAttenuation) {
  55528. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  55529. }
  55530. clonedSound.setPosition(this._position);
  55531. clonedSound.setPlaybackRate(this._playbackRate);
  55532. setBufferAndRun();
  55533. return clonedSound;
  55534. }
  55535. else {
  55536. return null;
  55537. }
  55538. };
  55539. Sound.prototype.getAudioBuffer = function () {
  55540. return this._audioBuffer;
  55541. };
  55542. Sound.prototype.serialize = function () {
  55543. var serializationObject = {
  55544. name: this.name,
  55545. url: this.name,
  55546. autoplay: this.autoplay,
  55547. loop: this.loop,
  55548. volume: this._volume,
  55549. spatialSound: this.spatialSound,
  55550. maxDistance: this.maxDistance,
  55551. rolloffFactor: this.rolloffFactor,
  55552. refDistance: this.refDistance,
  55553. distanceModel: this.distanceModel,
  55554. playbackRate: this._playbackRate,
  55555. panningModel: this._panningModel,
  55556. soundTrackId: this.soundTrackId
  55557. };
  55558. if (this.spatialSound) {
  55559. if (this._connectedMesh)
  55560. serializationObject.connectedMeshId = this._connectedMesh.id;
  55561. serializationObject.position = this._position.asArray();
  55562. serializationObject.refDistance = this.refDistance;
  55563. serializationObject.distanceModel = this.distanceModel;
  55564. serializationObject.isDirectional = this._isDirectional;
  55565. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  55566. serializationObject.coneInnerAngle = this._coneInnerAngle;
  55567. serializationObject.coneOuterAngle = this._coneOuterAngle;
  55568. serializationObject.coneOuterGain = this._coneOuterGain;
  55569. }
  55570. return serializationObject;
  55571. };
  55572. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  55573. var soundName = parsedSound.name;
  55574. var soundUrl;
  55575. if (parsedSound.url) {
  55576. soundUrl = rootUrl + parsedSound.url;
  55577. }
  55578. else {
  55579. soundUrl = rootUrl + soundName;
  55580. }
  55581. var options = {
  55582. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  55583. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  55584. rolloffFactor: parsedSound.rolloffFactor,
  55585. refDistance: parsedSound.refDistance,
  55586. distanceModel: parsedSound.distanceModel,
  55587. playbackRate: parsedSound.playbackRate
  55588. };
  55589. var newSound;
  55590. if (!sourceSound) {
  55591. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  55592. scene._addPendingData(newSound);
  55593. }
  55594. else {
  55595. var setBufferAndRun = function () {
  55596. if (sourceSound._isReadyToPlay) {
  55597. newSound._audioBuffer = sourceSound.getAudioBuffer();
  55598. newSound._isReadyToPlay = true;
  55599. if (newSound.autoplay) {
  55600. newSound.play();
  55601. }
  55602. }
  55603. else {
  55604. window.setTimeout(setBufferAndRun, 300);
  55605. }
  55606. };
  55607. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  55608. setBufferAndRun();
  55609. }
  55610. if (parsedSound.position) {
  55611. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  55612. newSound.setPosition(soundPosition);
  55613. }
  55614. if (parsedSound.isDirectional) {
  55615. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  55616. if (parsedSound.localDirectionToMesh) {
  55617. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  55618. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  55619. }
  55620. }
  55621. if (parsedSound.connectedMeshId) {
  55622. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  55623. if (connectedMesh) {
  55624. newSound.attachToMesh(connectedMesh);
  55625. }
  55626. }
  55627. return newSound;
  55628. };
  55629. return Sound;
  55630. }());
  55631. BABYLON.Sound = Sound;
  55632. })(BABYLON || (BABYLON = {}));
  55633. //# sourceMappingURL=babylon.sound.js.map
  55634. var BABYLON;
  55635. (function (BABYLON) {
  55636. var SoundTrack = /** @class */ (function () {
  55637. function SoundTrack(scene, options) {
  55638. this.id = -1;
  55639. this._isMainTrack = false;
  55640. this._isInitialized = false;
  55641. this._scene = scene;
  55642. this.soundCollection = new Array();
  55643. this._options = options;
  55644. if (!this._isMainTrack) {
  55645. this._scene.soundTracks.push(this);
  55646. this.id = this._scene.soundTracks.length - 1;
  55647. }
  55648. }
  55649. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  55650. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  55651. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  55652. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  55653. if (this._options) {
  55654. if (this._options.volume) {
  55655. this._outputAudioNode.gain.value = this._options.volume;
  55656. }
  55657. if (this._options.mainTrack) {
  55658. this._isMainTrack = this._options.mainTrack;
  55659. }
  55660. }
  55661. this._isInitialized = true;
  55662. }
  55663. };
  55664. SoundTrack.prototype.dispose = function () {
  55665. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  55666. if (this._connectedAnalyser) {
  55667. this._connectedAnalyser.stopDebugCanvas();
  55668. }
  55669. while (this.soundCollection.length) {
  55670. this.soundCollection[0].dispose();
  55671. }
  55672. if (this._outputAudioNode) {
  55673. this._outputAudioNode.disconnect();
  55674. }
  55675. this._outputAudioNode = null;
  55676. }
  55677. };
  55678. SoundTrack.prototype.AddSound = function (sound) {
  55679. if (!this._isInitialized) {
  55680. this._initializeSoundTrackAudioGraph();
  55681. }
  55682. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  55683. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  55684. }
  55685. if (sound.soundTrackId) {
  55686. if (sound.soundTrackId === -1) {
  55687. this._scene.mainSoundTrack.RemoveSound(sound);
  55688. }
  55689. else {
  55690. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  55691. }
  55692. }
  55693. this.soundCollection.push(sound);
  55694. sound.soundTrackId = this.id;
  55695. };
  55696. SoundTrack.prototype.RemoveSound = function (sound) {
  55697. var index = this.soundCollection.indexOf(sound);
  55698. if (index !== -1) {
  55699. this.soundCollection.splice(index, 1);
  55700. }
  55701. };
  55702. SoundTrack.prototype.setVolume = function (newVolume) {
  55703. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  55704. this._outputAudioNode.gain.value = newVolume;
  55705. }
  55706. };
  55707. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  55708. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  55709. for (var i = 0; i < this.soundCollection.length; i++) {
  55710. this.soundCollection[i].switchPanningModelToHRTF();
  55711. }
  55712. }
  55713. };
  55714. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  55715. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  55716. for (var i = 0; i < this.soundCollection.length; i++) {
  55717. this.soundCollection[i].switchPanningModelToEqualPower();
  55718. }
  55719. }
  55720. };
  55721. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  55722. if (this._connectedAnalyser) {
  55723. this._connectedAnalyser.stopDebugCanvas();
  55724. }
  55725. this._connectedAnalyser = analyser;
  55726. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  55727. this._outputAudioNode.disconnect();
  55728. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  55729. }
  55730. };
  55731. return SoundTrack;
  55732. }());
  55733. BABYLON.SoundTrack = SoundTrack;
  55734. })(BABYLON || (BABYLON = {}));
  55735. //# sourceMappingURL=babylon.soundtrack.js.map
  55736. var BABYLON;
  55737. (function (BABYLON) {
  55738. var Analyser = /** @class */ (function () {
  55739. function Analyser(scene) {
  55740. this.SMOOTHING = 0.75;
  55741. this.FFT_SIZE = 512;
  55742. this.BARGRAPHAMPLITUDE = 256;
  55743. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  55744. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  55745. this._scene = scene;
  55746. this._audioEngine = BABYLON.Engine.audioEngine;
  55747. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  55748. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  55749. this._webAudioAnalyser.minDecibels = -140;
  55750. this._webAudioAnalyser.maxDecibels = 0;
  55751. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  55752. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  55753. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  55754. }
  55755. }
  55756. Analyser.prototype.getFrequencyBinCount = function () {
  55757. if (this._audioEngine.canUseWebAudio) {
  55758. return this._webAudioAnalyser.frequencyBinCount;
  55759. }
  55760. else {
  55761. return 0;
  55762. }
  55763. };
  55764. Analyser.prototype.getByteFrequencyData = function () {
  55765. if (this._audioEngine.canUseWebAudio) {
  55766. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  55767. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  55768. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  55769. }
  55770. return this._byteFreqs;
  55771. };
  55772. Analyser.prototype.getByteTimeDomainData = function () {
  55773. if (this._audioEngine.canUseWebAudio) {
  55774. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  55775. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  55776. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  55777. }
  55778. return this._byteTime;
  55779. };
  55780. Analyser.prototype.getFloatFrequencyData = function () {
  55781. if (this._audioEngine.canUseWebAudio) {
  55782. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  55783. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  55784. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  55785. }
  55786. return this._floatFreqs;
  55787. };
  55788. Analyser.prototype.drawDebugCanvas = function () {
  55789. var _this = this;
  55790. if (this._audioEngine.canUseWebAudio) {
  55791. if (!this._debugCanvas) {
  55792. this._debugCanvas = document.createElement("canvas");
  55793. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  55794. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  55795. this._debugCanvas.style.position = "absolute";
  55796. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  55797. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  55798. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  55799. document.body.appendChild(this._debugCanvas);
  55800. this._registerFunc = function () {
  55801. _this.drawDebugCanvas();
  55802. };
  55803. this._scene.registerBeforeRender(this._registerFunc);
  55804. }
  55805. if (this._registerFunc && this._debugCanvasContext) {
  55806. var workingArray = this.getByteFrequencyData();
  55807. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  55808. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  55809. // Draw the frequency domain chart.
  55810. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  55811. var value = workingArray[i];
  55812. var percent = value / this.BARGRAPHAMPLITUDE;
  55813. var height = this.DEBUGCANVASSIZE.height * percent;
  55814. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  55815. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  55816. var hue = i / this.getFrequencyBinCount() * 360;
  55817. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  55818. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  55819. }
  55820. }
  55821. }
  55822. };
  55823. Analyser.prototype.stopDebugCanvas = function () {
  55824. if (this._debugCanvas) {
  55825. if (this._registerFunc) {
  55826. this._scene.unregisterBeforeRender(this._registerFunc);
  55827. this._registerFunc = null;
  55828. }
  55829. document.body.removeChild(this._debugCanvas);
  55830. this._debugCanvas = null;
  55831. this._debugCanvasContext = null;
  55832. }
  55833. };
  55834. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  55835. if (this._audioEngine.canUseWebAudio) {
  55836. inputAudioNode.connect(this._webAudioAnalyser);
  55837. this._webAudioAnalyser.connect(outputAudioNode);
  55838. }
  55839. };
  55840. Analyser.prototype.dispose = function () {
  55841. if (this._audioEngine.canUseWebAudio) {
  55842. this._webAudioAnalyser.disconnect();
  55843. }
  55844. };
  55845. return Analyser;
  55846. }());
  55847. BABYLON.Analyser = Analyser;
  55848. })(BABYLON || (BABYLON = {}));
  55849. //# sourceMappingURL=babylon.analyser.js.map
  55850. var BABYLON;
  55851. (function (BABYLON) {
  55852. var CubeTexture = /** @class */ (function (_super) {
  55853. __extends(CubeTexture, _super);
  55854. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension) {
  55855. if (extensions === void 0) { extensions = null; }
  55856. if (noMipmap === void 0) { noMipmap = false; }
  55857. if (files === void 0) { files = null; }
  55858. if (onLoad === void 0) { onLoad = null; }
  55859. if (onError === void 0) { onError = null; }
  55860. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  55861. if (prefiltered === void 0) { prefiltered = false; }
  55862. if (forcedExtension === void 0) { forcedExtension = null; }
  55863. var _this = _super.call(this, scene) || this;
  55864. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  55865. /**
  55866. * Gets or sets the center of the bounding box associated with the cube texture
  55867. * It must define where the camera used to render the texture was set
  55868. */
  55869. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  55870. _this.name = rootUrl;
  55871. _this.url = rootUrl;
  55872. _this._noMipmap = noMipmap;
  55873. _this.hasAlpha = false;
  55874. _this._format = format;
  55875. _this._prefiltered = prefiltered;
  55876. _this.isCube = true;
  55877. _this._textureMatrix = BABYLON.Matrix.Identity();
  55878. if (prefiltered) {
  55879. _this.gammaSpace = false;
  55880. }
  55881. if (!rootUrl && !files) {
  55882. return _this;
  55883. }
  55884. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  55885. var lastDot = rootUrl.lastIndexOf(".");
  55886. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  55887. var isDDS = (extension === ".dds");
  55888. if (!files) {
  55889. if (!isDDS && !extensions) {
  55890. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  55891. }
  55892. files = [];
  55893. if (extensions) {
  55894. for (var index = 0; index < extensions.length; index++) {
  55895. files.push(rootUrl + extensions[index]);
  55896. }
  55897. }
  55898. }
  55899. _this._files = files;
  55900. if (!_this._texture) {
  55901. if (!scene.useDelayedTextureLoading) {
  55902. if (prefiltered) {
  55903. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension);
  55904. }
  55905. else {
  55906. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  55907. }
  55908. }
  55909. else {
  55910. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  55911. }
  55912. }
  55913. else if (onLoad) {
  55914. if (_this._texture.isReady) {
  55915. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  55916. }
  55917. else {
  55918. _this._texture.onLoadedObservable.add(onLoad);
  55919. }
  55920. }
  55921. return _this;
  55922. }
  55923. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  55924. get: function () {
  55925. return this._boundingBoxSize;
  55926. },
  55927. /**
  55928. * Gets or sets the size of the bounding box associated with the cube texture
  55929. * When defined, the cubemap will switch to local mode
  55930. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  55931. * @example https://www.babylonjs-playground.com/#RNASML
  55932. */
  55933. set: function (value) {
  55934. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  55935. return;
  55936. }
  55937. this._boundingBoxSize = value;
  55938. var scene = this.getScene();
  55939. if (scene) {
  55940. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  55941. }
  55942. },
  55943. enumerable: true,
  55944. configurable: true
  55945. });
  55946. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  55947. return new CubeTexture("", scene, null, noMipmap, files);
  55948. };
  55949. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension) {
  55950. if (forcedExtension === void 0) { forcedExtension = null; }
  55951. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension);
  55952. };
  55953. // Methods
  55954. CubeTexture.prototype.delayLoad = function () {
  55955. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  55956. return;
  55957. }
  55958. var scene = this.getScene();
  55959. if (!scene) {
  55960. return;
  55961. }
  55962. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  55963. this._texture = this._getFromCache(this.url, this._noMipmap);
  55964. if (!this._texture) {
  55965. if (this._prefiltered) {
  55966. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format);
  55967. }
  55968. else {
  55969. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  55970. }
  55971. }
  55972. };
  55973. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  55974. return this._textureMatrix;
  55975. };
  55976. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  55977. this._textureMatrix = value;
  55978. };
  55979. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  55980. var texture = BABYLON.SerializationHelper.Parse(function () {
  55981. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  55982. }, parsedTexture, scene);
  55983. // Animations
  55984. if (parsedTexture.animations) {
  55985. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  55986. var parsedAnimation = parsedTexture.animations[animationIndex];
  55987. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  55988. }
  55989. }
  55990. return texture;
  55991. };
  55992. CubeTexture.prototype.clone = function () {
  55993. var _this = this;
  55994. return BABYLON.SerializationHelper.Clone(function () {
  55995. var scene = _this.getScene();
  55996. if (!scene) {
  55997. return _this;
  55998. }
  55999. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  56000. }, this);
  56001. };
  56002. return CubeTexture;
  56003. }(BABYLON.BaseTexture));
  56004. BABYLON.CubeTexture = CubeTexture;
  56005. })(BABYLON || (BABYLON = {}));
  56006. //# sourceMappingURL=babylon.cubeTexture.js.map
  56007. var BABYLON;
  56008. (function (BABYLON) {
  56009. var RenderTargetTexture = /** @class */ (function (_super) {
  56010. __extends(RenderTargetTexture, _super);
  56011. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  56012. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  56013. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  56014. if (isCube === void 0) { isCube = false; }
  56015. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  56016. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  56017. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  56018. if (isMulti === void 0) { isMulti = false; }
  56019. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  56020. _this.isCube = isCube;
  56021. /**
  56022. * Use this list to define the list of mesh you want to render.
  56023. */
  56024. _this.renderList = new Array();
  56025. _this.renderParticles = true;
  56026. _this.renderSprites = false;
  56027. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  56028. _this.ignoreCameraViewport = false;
  56029. // Events
  56030. /**
  56031. * An event triggered when the texture is unbind.
  56032. * @type {BABYLON.Observable}
  56033. */
  56034. _this.onBeforeBindObservable = new BABYLON.Observable();
  56035. /**
  56036. * An event triggered when the texture is unbind.
  56037. * @type {BABYLON.Observable}
  56038. */
  56039. _this.onAfterUnbindObservable = new BABYLON.Observable();
  56040. /**
  56041. * An event triggered before rendering the texture
  56042. * @type {BABYLON.Observable}
  56043. */
  56044. _this.onBeforeRenderObservable = new BABYLON.Observable();
  56045. /**
  56046. * An event triggered after rendering the texture
  56047. * @type {BABYLON.Observable}
  56048. */
  56049. _this.onAfterRenderObservable = new BABYLON.Observable();
  56050. /**
  56051. * An event triggered after the texture clear
  56052. * @type {BABYLON.Observable}
  56053. */
  56054. _this.onClearObservable = new BABYLON.Observable();
  56055. _this._currentRefreshId = -1;
  56056. _this._refreshRate = 1;
  56057. _this._samples = 1;
  56058. /**
  56059. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  56060. * It must define where the camera used to render the texture is set
  56061. */
  56062. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  56063. scene = _this.getScene();
  56064. if (!scene) {
  56065. return _this;
  56066. }
  56067. _this._engine = scene.getEngine();
  56068. _this.name = name;
  56069. _this.isRenderTarget = true;
  56070. _this._initialSizeParameter = size;
  56071. _this._processSizeParameter(size);
  56072. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  56073. });
  56074. _this._generateMipMaps = generateMipMaps ? true : false;
  56075. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  56076. // Rendering groups
  56077. _this._renderingManager = new BABYLON.RenderingManager(scene);
  56078. if (isMulti) {
  56079. return _this;
  56080. }
  56081. _this._renderTargetOptions = {
  56082. generateMipMaps: generateMipMaps,
  56083. type: type,
  56084. samplingMode: samplingMode,
  56085. generateDepthBuffer: generateDepthBuffer,
  56086. generateStencilBuffer: generateStencilBuffer
  56087. };
  56088. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  56089. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  56090. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  56091. }
  56092. if (isCube) {
  56093. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  56094. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  56095. _this._textureMatrix = BABYLON.Matrix.Identity();
  56096. }
  56097. else {
  56098. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  56099. }
  56100. return _this;
  56101. }
  56102. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  56103. get: function () {
  56104. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  56105. },
  56106. enumerable: true,
  56107. configurable: true
  56108. });
  56109. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  56110. get: function () {
  56111. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  56112. },
  56113. enumerable: true,
  56114. configurable: true
  56115. });
  56116. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  56117. get: function () {
  56118. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  56119. },
  56120. enumerable: true,
  56121. configurable: true
  56122. });
  56123. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  56124. set: function (callback) {
  56125. if (this._onAfterUnbindObserver) {
  56126. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  56127. }
  56128. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  56129. },
  56130. enumerable: true,
  56131. configurable: true
  56132. });
  56133. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  56134. set: function (callback) {
  56135. if (this._onBeforeRenderObserver) {
  56136. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  56137. }
  56138. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  56139. },
  56140. enumerable: true,
  56141. configurable: true
  56142. });
  56143. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  56144. set: function (callback) {
  56145. if (this._onAfterRenderObserver) {
  56146. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  56147. }
  56148. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  56149. },
  56150. enumerable: true,
  56151. configurable: true
  56152. });
  56153. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  56154. set: function (callback) {
  56155. if (this._onClearObserver) {
  56156. this.onClearObservable.remove(this._onClearObserver);
  56157. }
  56158. this._onClearObserver = this.onClearObservable.add(callback);
  56159. },
  56160. enumerable: true,
  56161. configurable: true
  56162. });
  56163. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  56164. get: function () {
  56165. return this._renderTargetOptions;
  56166. },
  56167. enumerable: true,
  56168. configurable: true
  56169. });
  56170. RenderTargetTexture.prototype._onRatioRescale = function () {
  56171. if (this._sizeRatio) {
  56172. this.resize(this._initialSizeParameter);
  56173. }
  56174. };
  56175. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  56176. get: function () {
  56177. return this._boundingBoxSize;
  56178. },
  56179. /**
  56180. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  56181. * When defined, the cubemap will switch to local mode
  56182. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  56183. * @example https://www.babylonjs-playground.com/#RNASML
  56184. */
  56185. set: function (value) {
  56186. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  56187. return;
  56188. }
  56189. this._boundingBoxSize = value;
  56190. var scene = this.getScene();
  56191. if (scene) {
  56192. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  56193. }
  56194. },
  56195. enumerable: true,
  56196. configurable: true
  56197. });
  56198. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  56199. if (size.ratio) {
  56200. this._sizeRatio = size.ratio;
  56201. this._size = {
  56202. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  56203. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  56204. };
  56205. }
  56206. else {
  56207. this._size = size;
  56208. }
  56209. };
  56210. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  56211. get: function () {
  56212. return this._samples;
  56213. },
  56214. set: function (value) {
  56215. if (this._samples === value) {
  56216. return;
  56217. }
  56218. var scene = this.getScene();
  56219. if (!scene) {
  56220. return;
  56221. }
  56222. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  56223. },
  56224. enumerable: true,
  56225. configurable: true
  56226. });
  56227. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  56228. this._currentRefreshId = -1;
  56229. };
  56230. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  56231. get: function () {
  56232. return this._refreshRate;
  56233. },
  56234. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  56235. set: function (value) {
  56236. this._refreshRate = value;
  56237. this.resetRefreshCounter();
  56238. },
  56239. enumerable: true,
  56240. configurable: true
  56241. });
  56242. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  56243. if (!this._postProcessManager) {
  56244. var scene = this.getScene();
  56245. if (!scene) {
  56246. return;
  56247. }
  56248. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  56249. this._postProcesses = new Array();
  56250. }
  56251. this._postProcesses.push(postProcess);
  56252. this._postProcesses[0].autoClear = false;
  56253. };
  56254. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  56255. if (!this._postProcesses) {
  56256. return;
  56257. }
  56258. if (dispose) {
  56259. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  56260. var postProcess = _a[_i];
  56261. postProcess.dispose();
  56262. }
  56263. }
  56264. this._postProcesses = [];
  56265. };
  56266. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  56267. if (!this._postProcesses) {
  56268. return;
  56269. }
  56270. var index = this._postProcesses.indexOf(postProcess);
  56271. if (index === -1) {
  56272. return;
  56273. }
  56274. this._postProcesses.splice(index, 1);
  56275. if (this._postProcesses.length > 0) {
  56276. this._postProcesses[0].autoClear = false;
  56277. }
  56278. };
  56279. RenderTargetTexture.prototype._shouldRender = function () {
  56280. if (this._currentRefreshId === -1) {
  56281. this._currentRefreshId = 1;
  56282. return true;
  56283. }
  56284. if (this.refreshRate === this._currentRefreshId) {
  56285. this._currentRefreshId = 1;
  56286. return true;
  56287. }
  56288. this._currentRefreshId++;
  56289. return false;
  56290. };
  56291. RenderTargetTexture.prototype.getRenderSize = function () {
  56292. if (this._size.width) {
  56293. return this._size.width;
  56294. }
  56295. return this._size;
  56296. };
  56297. RenderTargetTexture.prototype.getRenderWidth = function () {
  56298. if (this._size.width) {
  56299. return this._size.width;
  56300. }
  56301. return this._size;
  56302. };
  56303. RenderTargetTexture.prototype.getRenderHeight = function () {
  56304. if (this._size.width) {
  56305. return this._size.height;
  56306. }
  56307. return this._size;
  56308. };
  56309. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  56310. get: function () {
  56311. return true;
  56312. },
  56313. enumerable: true,
  56314. configurable: true
  56315. });
  56316. RenderTargetTexture.prototype.scale = function (ratio) {
  56317. var newSize = this.getRenderSize() * ratio;
  56318. this.resize(newSize);
  56319. };
  56320. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  56321. if (this.isCube) {
  56322. return this._textureMatrix;
  56323. }
  56324. return _super.prototype.getReflectionTextureMatrix.call(this);
  56325. };
  56326. RenderTargetTexture.prototype.resize = function (size) {
  56327. this.releaseInternalTexture();
  56328. var scene = this.getScene();
  56329. if (!scene) {
  56330. return;
  56331. }
  56332. this._processSizeParameter(size);
  56333. if (this.isCube) {
  56334. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  56335. }
  56336. else {
  56337. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  56338. }
  56339. };
  56340. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  56341. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  56342. if (dumpForDebug === void 0) { dumpForDebug = false; }
  56343. var scene = this.getScene();
  56344. if (!scene) {
  56345. return;
  56346. }
  56347. var engine = scene.getEngine();
  56348. if (this.useCameraPostProcesses !== undefined) {
  56349. useCameraPostProcess = this.useCameraPostProcesses;
  56350. }
  56351. if (this._waitingRenderList) {
  56352. this.renderList = [];
  56353. for (var index = 0; index < this._waitingRenderList.length; index++) {
  56354. var id = this._waitingRenderList[index];
  56355. var mesh_1 = scene.getMeshByID(id);
  56356. if (mesh_1) {
  56357. this.renderList.push(mesh_1);
  56358. }
  56359. }
  56360. delete this._waitingRenderList;
  56361. }
  56362. // Is predicate defined?
  56363. if (this.renderListPredicate) {
  56364. if (this.renderList) {
  56365. this.renderList.splice(0); // Clear previous renderList
  56366. }
  56367. else {
  56368. this.renderList = [];
  56369. }
  56370. var scene = this.getScene();
  56371. if (!scene) {
  56372. return;
  56373. }
  56374. var sceneMeshes = scene.meshes;
  56375. for (var index = 0; index < sceneMeshes.length; index++) {
  56376. var mesh = sceneMeshes[index];
  56377. if (this.renderListPredicate(mesh)) {
  56378. this.renderList.push(mesh);
  56379. }
  56380. }
  56381. }
  56382. this.onBeforeBindObservable.notifyObservers(this);
  56383. // Set custom projection.
  56384. // Needs to be before binding to prevent changing the aspect ratio.
  56385. var camera;
  56386. if (this.activeCamera) {
  56387. camera = this.activeCamera;
  56388. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  56389. if (this.activeCamera !== scene.activeCamera) {
  56390. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  56391. }
  56392. }
  56393. else {
  56394. camera = scene.activeCamera;
  56395. if (camera) {
  56396. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  56397. }
  56398. }
  56399. // Prepare renderingManager
  56400. this._renderingManager.reset();
  56401. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  56402. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  56403. var sceneRenderId = scene.getRenderId();
  56404. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  56405. var mesh = currentRenderList[meshIndex];
  56406. if (mesh) {
  56407. if (!mesh.isReady()) {
  56408. // Reset _currentRefreshId
  56409. this.resetRefreshCounter();
  56410. continue;
  56411. }
  56412. mesh._preActivateForIntermediateRendering(sceneRenderId);
  56413. var isMasked = void 0;
  56414. if (!this.renderList && camera) {
  56415. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  56416. }
  56417. else {
  56418. isMasked = false;
  56419. }
  56420. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  56421. mesh._activate(sceneRenderId);
  56422. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  56423. var subMesh = mesh.subMeshes[subIndex];
  56424. scene._activeIndices.addCount(subMesh.indexCount, false);
  56425. this._renderingManager.dispatch(subMesh, mesh);
  56426. }
  56427. }
  56428. }
  56429. }
  56430. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  56431. var particleSystem = scene.particleSystems[particleIndex];
  56432. var emitter = particleSystem.emitter;
  56433. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  56434. continue;
  56435. }
  56436. if (currentRenderList.indexOf(emitter) >= 0) {
  56437. this._renderingManager.dispatchParticles(particleSystem);
  56438. }
  56439. }
  56440. if (this.isCube) {
  56441. for (var face = 0; face < 6; face++) {
  56442. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  56443. scene.incrementRenderId();
  56444. scene.resetCachedMaterial();
  56445. }
  56446. }
  56447. else {
  56448. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  56449. }
  56450. this.onAfterUnbindObservable.notifyObservers(this);
  56451. if (scene.activeCamera) {
  56452. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  56453. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  56454. }
  56455. engine.setViewport(scene.activeCamera.viewport);
  56456. }
  56457. scene.resetCachedMaterial();
  56458. };
  56459. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  56460. var minimum = 128;
  56461. var x = renderDimension * scale;
  56462. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  56463. // Ensure we don't exceed the render dimension (while staying POT)
  56464. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  56465. };
  56466. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  56467. var _this = this;
  56468. if (!this._texture) {
  56469. return;
  56470. }
  56471. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  56472. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  56473. });
  56474. };
  56475. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  56476. var scene = this.getScene();
  56477. if (!scene) {
  56478. return;
  56479. }
  56480. var engine = scene.getEngine();
  56481. if (!this._texture) {
  56482. return;
  56483. }
  56484. // Bind
  56485. if (this._postProcessManager) {
  56486. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  56487. }
  56488. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  56489. if (this._texture) {
  56490. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport);
  56491. }
  56492. }
  56493. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  56494. // Clear
  56495. if (this.onClearObservable.hasObservers()) {
  56496. this.onClearObservable.notifyObservers(engine);
  56497. }
  56498. else {
  56499. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  56500. }
  56501. if (!this._doNotChangeAspectRatio) {
  56502. scene.updateTransformMatrix(true);
  56503. }
  56504. // Render
  56505. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  56506. if (this._postProcessManager) {
  56507. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  56508. }
  56509. else if (useCameraPostProcess) {
  56510. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  56511. }
  56512. if (!this._doNotChangeAspectRatio) {
  56513. scene.updateTransformMatrix(true);
  56514. }
  56515. // Dump ?
  56516. if (dumpForDebug) {
  56517. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  56518. }
  56519. // Unbind
  56520. if (!this.isCube || faceIndex === 5) {
  56521. if (this.isCube) {
  56522. if (faceIndex === 5) {
  56523. engine.generateMipMapsForCubemap(this._texture);
  56524. }
  56525. }
  56526. this.unbindFrameBuffer(engine, faceIndex);
  56527. }
  56528. else {
  56529. this.onAfterRenderObservable.notifyObservers(faceIndex);
  56530. }
  56531. };
  56532. /**
  56533. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  56534. * This allowed control for front to back rendering or reversly depending of the special needs.
  56535. *
  56536. * @param renderingGroupId The rendering group id corresponding to its index
  56537. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  56538. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  56539. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  56540. */
  56541. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  56542. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  56543. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  56544. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  56545. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  56546. };
  56547. /**
  56548. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  56549. *
  56550. * @param renderingGroupId The rendering group id corresponding to its index
  56551. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  56552. */
  56553. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  56554. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  56555. };
  56556. RenderTargetTexture.prototype.clone = function () {
  56557. var textureSize = this.getSize();
  56558. 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);
  56559. // Base texture
  56560. newTexture.hasAlpha = this.hasAlpha;
  56561. newTexture.level = this.level;
  56562. // RenderTarget Texture
  56563. newTexture.coordinatesMode = this.coordinatesMode;
  56564. if (this.renderList) {
  56565. newTexture.renderList = this.renderList.slice(0);
  56566. }
  56567. return newTexture;
  56568. };
  56569. RenderTargetTexture.prototype.serialize = function () {
  56570. if (!this.name) {
  56571. return null;
  56572. }
  56573. var serializationObject = _super.prototype.serialize.call(this);
  56574. serializationObject.renderTargetSize = this.getRenderSize();
  56575. serializationObject.renderList = [];
  56576. if (this.renderList) {
  56577. for (var index = 0; index < this.renderList.length; index++) {
  56578. serializationObject.renderList.push(this.renderList[index].id);
  56579. }
  56580. }
  56581. return serializationObject;
  56582. };
  56583. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  56584. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  56585. var objBuffer = this.getInternalTexture();
  56586. var scene = this.getScene();
  56587. if (objBuffer && scene) {
  56588. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  56589. }
  56590. };
  56591. RenderTargetTexture.prototype.dispose = function () {
  56592. if (this._postProcessManager) {
  56593. this._postProcessManager.dispose();
  56594. this._postProcessManager = null;
  56595. }
  56596. this.clearPostProcesses(true);
  56597. if (this._resizeObserver) {
  56598. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  56599. this._resizeObserver = null;
  56600. }
  56601. this.renderList = null;
  56602. // Remove from custom render targets
  56603. var scene = this.getScene();
  56604. if (!scene) {
  56605. return;
  56606. }
  56607. var index = scene.customRenderTargets.indexOf(this);
  56608. if (index >= 0) {
  56609. scene.customRenderTargets.splice(index, 1);
  56610. }
  56611. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  56612. var camera = _a[_i];
  56613. index = camera.customRenderTargets.indexOf(this);
  56614. if (index >= 0) {
  56615. camera.customRenderTargets.splice(index, 1);
  56616. }
  56617. }
  56618. _super.prototype.dispose.call(this);
  56619. };
  56620. RenderTargetTexture.prototype._rebuild = function () {
  56621. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  56622. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  56623. }
  56624. if (this._postProcessManager) {
  56625. this._postProcessManager._rebuild();
  56626. }
  56627. };
  56628. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  56629. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  56630. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  56631. return RenderTargetTexture;
  56632. }(BABYLON.Texture));
  56633. BABYLON.RenderTargetTexture = RenderTargetTexture;
  56634. })(BABYLON || (BABYLON = {}));
  56635. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  56636. var BABYLON;
  56637. (function (BABYLON) {
  56638. ;
  56639. var MultiRenderTarget = /** @class */ (function (_super) {
  56640. __extends(MultiRenderTarget, _super);
  56641. function MultiRenderTarget(name, size, count, scene, options) {
  56642. var _this = this;
  56643. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  56644. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  56645. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  56646. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  56647. _this._engine = scene.getEngine();
  56648. if (!_this.isSupported) {
  56649. _this.dispose();
  56650. return;
  56651. }
  56652. var types = [];
  56653. var samplingModes = [];
  56654. for (var i = 0; i < count; i++) {
  56655. if (options && options.types && options.types[i] !== undefined) {
  56656. types.push(options.types[i]);
  56657. }
  56658. else {
  56659. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  56660. }
  56661. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  56662. samplingModes.push(options.samplingModes[i]);
  56663. }
  56664. else {
  56665. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  56666. }
  56667. }
  56668. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  56669. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  56670. _this._size = size;
  56671. _this._multiRenderTargetOptions = {
  56672. samplingModes: samplingModes,
  56673. generateMipMaps: generateMipMaps,
  56674. generateDepthBuffer: generateDepthBuffer,
  56675. generateStencilBuffer: generateStencilBuffer,
  56676. generateDepthTexture: generateDepthTexture,
  56677. types: types,
  56678. textureCount: count
  56679. };
  56680. _this._createInternalTextures();
  56681. _this._createTextures();
  56682. return _this;
  56683. }
  56684. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  56685. get: function () {
  56686. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  56687. },
  56688. enumerable: true,
  56689. configurable: true
  56690. });
  56691. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  56692. get: function () {
  56693. return this._textures;
  56694. },
  56695. enumerable: true,
  56696. configurable: true
  56697. });
  56698. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  56699. get: function () {
  56700. return this._textures[this._textures.length - 1];
  56701. },
  56702. enumerable: true,
  56703. configurable: true
  56704. });
  56705. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  56706. set: function (wrap) {
  56707. if (this._textures) {
  56708. for (var i = 0; i < this._textures.length; i++) {
  56709. this._textures[i].wrapU = wrap;
  56710. }
  56711. }
  56712. },
  56713. enumerable: true,
  56714. configurable: true
  56715. });
  56716. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  56717. set: function (wrap) {
  56718. if (this._textures) {
  56719. for (var i = 0; i < this._textures.length; i++) {
  56720. this._textures[i].wrapV = wrap;
  56721. }
  56722. }
  56723. },
  56724. enumerable: true,
  56725. configurable: true
  56726. });
  56727. MultiRenderTarget.prototype._rebuild = function () {
  56728. this.releaseInternalTextures();
  56729. this._createInternalTextures();
  56730. for (var i = 0; i < this._internalTextures.length; i++) {
  56731. var texture = this._textures[i];
  56732. texture._texture = this._internalTextures[i];
  56733. }
  56734. // Keeps references to frame buffer and stencil/depth buffer
  56735. this._texture = this._internalTextures[0];
  56736. };
  56737. MultiRenderTarget.prototype._createInternalTextures = function () {
  56738. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  56739. };
  56740. MultiRenderTarget.prototype._createTextures = function () {
  56741. this._textures = [];
  56742. for (var i = 0; i < this._internalTextures.length; i++) {
  56743. var texture = new BABYLON.Texture(null, this.getScene());
  56744. texture._texture = this._internalTextures[i];
  56745. this._textures.push(texture);
  56746. }
  56747. // Keeps references to frame buffer and stencil/depth buffer
  56748. this._texture = this._internalTextures[0];
  56749. };
  56750. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  56751. get: function () {
  56752. return this._samples;
  56753. },
  56754. set: function (value) {
  56755. if (this._samples === value) {
  56756. return;
  56757. }
  56758. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  56759. },
  56760. enumerable: true,
  56761. configurable: true
  56762. });
  56763. MultiRenderTarget.prototype.resize = function (size) {
  56764. this.releaseInternalTextures();
  56765. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  56766. this._createInternalTextures();
  56767. };
  56768. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  56769. var _this = this;
  56770. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  56771. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  56772. });
  56773. };
  56774. MultiRenderTarget.prototype.dispose = function () {
  56775. this.releaseInternalTextures();
  56776. _super.prototype.dispose.call(this);
  56777. };
  56778. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  56779. if (!this._internalTextures) {
  56780. return;
  56781. }
  56782. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  56783. if (this._internalTextures[i] !== undefined) {
  56784. this._internalTextures[i].dispose();
  56785. this._internalTextures.splice(i, 1);
  56786. }
  56787. }
  56788. };
  56789. return MultiRenderTarget;
  56790. }(BABYLON.RenderTargetTexture));
  56791. BABYLON.MultiRenderTarget = MultiRenderTarget;
  56792. })(BABYLON || (BABYLON = {}));
  56793. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  56794. var BABYLON;
  56795. (function (BABYLON) {
  56796. var MirrorTexture = /** @class */ (function (_super) {
  56797. __extends(MirrorTexture, _super);
  56798. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  56799. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  56800. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  56801. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  56802. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  56803. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  56804. _this._transformMatrix = BABYLON.Matrix.Zero();
  56805. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  56806. _this._adaptiveBlurKernel = 0;
  56807. _this._blurKernelX = 0;
  56808. _this._blurKernelY = 0;
  56809. _this._blurRatio = 1.0;
  56810. _this.ignoreCameraViewport = true;
  56811. _this.onBeforeRenderObservable.add(function () {
  56812. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  56813. _this._savedViewMatrix = scene.getViewMatrix();
  56814. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  56815. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  56816. scene.clipPlane = _this.mirrorPlane;
  56817. scene.getEngine().cullBackFaces = false;
  56818. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  56819. });
  56820. _this.onAfterRenderObservable.add(function () {
  56821. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  56822. scene.getEngine().cullBackFaces = true;
  56823. scene._mirroredCameraPosition = null;
  56824. delete scene.clipPlane;
  56825. });
  56826. return _this;
  56827. }
  56828. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  56829. get: function () {
  56830. return this._blurRatio;
  56831. },
  56832. set: function (value) {
  56833. if (this._blurRatio === value) {
  56834. return;
  56835. }
  56836. this._blurRatio = value;
  56837. this._preparePostProcesses();
  56838. },
  56839. enumerable: true,
  56840. configurable: true
  56841. });
  56842. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  56843. set: function (value) {
  56844. this._adaptiveBlurKernel = value;
  56845. this._autoComputeBlurKernel();
  56846. },
  56847. enumerable: true,
  56848. configurable: true
  56849. });
  56850. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  56851. set: function (value) {
  56852. this.blurKernelX = value;
  56853. this.blurKernelY = value;
  56854. },
  56855. enumerable: true,
  56856. configurable: true
  56857. });
  56858. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  56859. get: function () {
  56860. return this._blurKernelX;
  56861. },
  56862. set: function (value) {
  56863. if (this._blurKernelX === value) {
  56864. return;
  56865. }
  56866. this._blurKernelX = value;
  56867. this._preparePostProcesses();
  56868. },
  56869. enumerable: true,
  56870. configurable: true
  56871. });
  56872. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  56873. get: function () {
  56874. return this._blurKernelY;
  56875. },
  56876. set: function (value) {
  56877. if (this._blurKernelY === value) {
  56878. return;
  56879. }
  56880. this._blurKernelY = value;
  56881. this._preparePostProcesses();
  56882. },
  56883. enumerable: true,
  56884. configurable: true
  56885. });
  56886. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  56887. var engine = this.getScene().getEngine();
  56888. var dw = this.getRenderWidth() / engine.getRenderWidth();
  56889. var dh = this.getRenderHeight() / engine.getRenderHeight();
  56890. this.blurKernelX = this._adaptiveBlurKernel * dw;
  56891. this.blurKernelY = this._adaptiveBlurKernel * dh;
  56892. };
  56893. MirrorTexture.prototype._onRatioRescale = function () {
  56894. if (this._sizeRatio) {
  56895. this.resize(this._initialSizeParameter);
  56896. if (!this._adaptiveBlurKernel) {
  56897. this._preparePostProcesses();
  56898. }
  56899. }
  56900. if (this._adaptiveBlurKernel) {
  56901. this._autoComputeBlurKernel();
  56902. }
  56903. };
  56904. MirrorTexture.prototype._preparePostProcesses = function () {
  56905. this.clearPostProcesses(true);
  56906. if (this._blurKernelX && this._blurKernelY) {
  56907. var engine = this.getScene().getEngine();
  56908. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  56909. 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);
  56910. this._blurX.autoClear = false;
  56911. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  56912. this._blurX.inputTexture = this._texture;
  56913. }
  56914. else {
  56915. this._blurX.alwaysForcePOT = true;
  56916. }
  56917. 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);
  56918. this._blurY.autoClear = false;
  56919. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  56920. this.addPostProcess(this._blurX);
  56921. this.addPostProcess(this._blurY);
  56922. }
  56923. else {
  56924. if (this._blurY) {
  56925. this.removePostProcess(this._blurY);
  56926. this._blurY.dispose();
  56927. this._blurY = null;
  56928. }
  56929. if (this._blurX) {
  56930. this.removePostProcess(this._blurX);
  56931. this._blurX.dispose();
  56932. this._blurX = null;
  56933. }
  56934. }
  56935. };
  56936. MirrorTexture.prototype.clone = function () {
  56937. var scene = this.getScene();
  56938. if (!scene) {
  56939. return this;
  56940. }
  56941. var textureSize = this.getSize();
  56942. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  56943. // Base texture
  56944. newTexture.hasAlpha = this.hasAlpha;
  56945. newTexture.level = this.level;
  56946. // Mirror Texture
  56947. newTexture.mirrorPlane = this.mirrorPlane.clone();
  56948. if (this.renderList) {
  56949. newTexture.renderList = this.renderList.slice(0);
  56950. }
  56951. return newTexture;
  56952. };
  56953. MirrorTexture.prototype.serialize = function () {
  56954. if (!this.name) {
  56955. return null;
  56956. }
  56957. var serializationObject = _super.prototype.serialize.call(this);
  56958. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  56959. return serializationObject;
  56960. };
  56961. return MirrorTexture;
  56962. }(BABYLON.RenderTargetTexture));
  56963. BABYLON.MirrorTexture = MirrorTexture;
  56964. })(BABYLON || (BABYLON = {}));
  56965. //# sourceMappingURL=babylon.mirrorTexture.js.map
  56966. var BABYLON;
  56967. (function (BABYLON) {
  56968. /**
  56969. * Creates a refraction texture used by refraction channel of the standard material.
  56970. * @param name the texture name
  56971. * @param size size of the underlying texture
  56972. * @param scene root scene
  56973. */
  56974. var RefractionTexture = /** @class */ (function (_super) {
  56975. __extends(RefractionTexture, _super);
  56976. function RefractionTexture(name, size, scene, generateMipMaps) {
  56977. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  56978. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  56979. _this.depth = 2.0;
  56980. _this.onBeforeRenderObservable.add(function () {
  56981. scene.clipPlane = _this.refractionPlane;
  56982. });
  56983. _this.onAfterRenderObservable.add(function () {
  56984. delete scene.clipPlane;
  56985. });
  56986. return _this;
  56987. }
  56988. RefractionTexture.prototype.clone = function () {
  56989. var scene = this.getScene();
  56990. if (!scene) {
  56991. return this;
  56992. }
  56993. var textureSize = this.getSize();
  56994. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  56995. // Base texture
  56996. newTexture.hasAlpha = this.hasAlpha;
  56997. newTexture.level = this.level;
  56998. // Refraction Texture
  56999. newTexture.refractionPlane = this.refractionPlane.clone();
  57000. if (this.renderList) {
  57001. newTexture.renderList = this.renderList.slice(0);
  57002. }
  57003. newTexture.depth = this.depth;
  57004. return newTexture;
  57005. };
  57006. RefractionTexture.prototype.serialize = function () {
  57007. if (!this.name) {
  57008. return null;
  57009. }
  57010. var serializationObject = _super.prototype.serialize.call(this);
  57011. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  57012. serializationObject.depth = this.depth;
  57013. return serializationObject;
  57014. };
  57015. return RefractionTexture;
  57016. }(BABYLON.RenderTargetTexture));
  57017. BABYLON.RefractionTexture = RefractionTexture;
  57018. })(BABYLON || (BABYLON = {}));
  57019. //# sourceMappingURL=babylon.refractionTexture.js.map
  57020. var BABYLON;
  57021. (function (BABYLON) {
  57022. var DynamicTexture = /** @class */ (function (_super) {
  57023. __extends(DynamicTexture, _super);
  57024. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  57025. if (scene === void 0) { scene = null; }
  57026. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  57027. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  57028. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  57029. _this.name = name;
  57030. _this._engine = _this.getScene().getEngine();
  57031. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  57032. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  57033. _this._generateMipMaps = generateMipMaps;
  57034. if (options.getContext) {
  57035. _this._canvas = options;
  57036. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  57037. }
  57038. else {
  57039. _this._canvas = document.createElement("canvas");
  57040. if (options.width) {
  57041. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  57042. }
  57043. else {
  57044. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  57045. }
  57046. }
  57047. var textureSize = _this.getSize();
  57048. _this._canvas.width = textureSize.width;
  57049. _this._canvas.height = textureSize.height;
  57050. _this._context = _this._canvas.getContext("2d");
  57051. return _this;
  57052. }
  57053. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  57054. get: function () {
  57055. return true;
  57056. },
  57057. enumerable: true,
  57058. configurable: true
  57059. });
  57060. DynamicTexture.prototype._recreate = function (textureSize) {
  57061. this._canvas.width = textureSize.width;
  57062. this._canvas.height = textureSize.height;
  57063. this.releaseInternalTexture();
  57064. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  57065. };
  57066. DynamicTexture.prototype.scale = function (ratio) {
  57067. var textureSize = this.getSize();
  57068. textureSize.width *= ratio;
  57069. textureSize.height *= ratio;
  57070. this._recreate(textureSize);
  57071. };
  57072. DynamicTexture.prototype.scaleTo = function (width, height) {
  57073. var textureSize = this.getSize();
  57074. textureSize.width = width;
  57075. textureSize.height = height;
  57076. this._recreate(textureSize);
  57077. };
  57078. DynamicTexture.prototype.getContext = function () {
  57079. return this._context;
  57080. };
  57081. DynamicTexture.prototype.clear = function () {
  57082. var size = this.getSize();
  57083. this._context.fillRect(0, 0, size.width, size.height);
  57084. };
  57085. DynamicTexture.prototype.update = function (invertY) {
  57086. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format || undefined);
  57087. };
  57088. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  57089. if (update === void 0) { update = true; }
  57090. var size = this.getSize();
  57091. if (clearColor) {
  57092. this._context.fillStyle = clearColor;
  57093. this._context.fillRect(0, 0, size.width, size.height);
  57094. }
  57095. this._context.font = font;
  57096. if (x === null || x === undefined) {
  57097. var textSize = this._context.measureText(text);
  57098. x = (size.width - textSize.width) / 2;
  57099. }
  57100. if (y === null || y === undefined) {
  57101. var fontSize = parseInt((font.replace(/\D/g, '')));
  57102. ;
  57103. y = (size.height / 2) + (fontSize / 3.65);
  57104. }
  57105. this._context.fillStyle = color;
  57106. this._context.fillText(text, x, y);
  57107. if (update) {
  57108. this.update(invertY);
  57109. }
  57110. };
  57111. DynamicTexture.prototype.clone = function () {
  57112. var scene = this.getScene();
  57113. if (!scene) {
  57114. return this;
  57115. }
  57116. var textureSize = this.getSize();
  57117. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  57118. // Base texture
  57119. newTexture.hasAlpha = this.hasAlpha;
  57120. newTexture.level = this.level;
  57121. // Dynamic Texture
  57122. newTexture.wrapU = this.wrapU;
  57123. newTexture.wrapV = this.wrapV;
  57124. return newTexture;
  57125. };
  57126. DynamicTexture.prototype._rebuild = function () {
  57127. this.update();
  57128. };
  57129. return DynamicTexture;
  57130. }(BABYLON.Texture));
  57131. BABYLON.DynamicTexture = DynamicTexture;
  57132. })(BABYLON || (BABYLON = {}));
  57133. //# sourceMappingURL=babylon.dynamicTexture.js.map
  57134. var BABYLON;
  57135. (function (BABYLON) {
  57136. var VideoTexture = /** @class */ (function (_super) {
  57137. __extends(VideoTexture, _super);
  57138. /**
  57139. * Creates a video texture.
  57140. * Sample : https://doc.babylonjs.com/how_to/video_texture
  57141. * @param {string | null} name optional name, will detect from video source, if not defined
  57142. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  57143. * @param {BABYLON.Scene} scene is obviously the current scene.
  57144. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  57145. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  57146. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  57147. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  57148. */
  57149. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  57150. if (generateMipMaps === void 0) { generateMipMaps = false; }
  57151. if (invertY === void 0) { invertY = false; }
  57152. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  57153. if (settings === void 0) { settings = {
  57154. autoPlay: true,
  57155. loop: true,
  57156. autoUpdateTexture: true,
  57157. }; }
  57158. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  57159. _this._createInternalTexture = function () {
  57160. if (_this._texture != null) {
  57161. return;
  57162. }
  57163. if (!_this._engine.needPOTTextures ||
  57164. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  57165. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  57166. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  57167. }
  57168. else {
  57169. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  57170. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  57171. _this._generateMipMaps = false;
  57172. }
  57173. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  57174. _this._texture.isReady = true;
  57175. _this._updateInternalTexture();
  57176. };
  57177. _this.reset = function () {
  57178. if (_this._texture == null) {
  57179. return;
  57180. }
  57181. _this._texture.dispose();
  57182. _this._texture = null;
  57183. };
  57184. _this._updateInternalTexture = function (e) {
  57185. if (_this._texture == null || !_this._texture.isReady) {
  57186. return;
  57187. }
  57188. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  57189. return;
  57190. }
  57191. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  57192. };
  57193. _this._engine = _this.getScene().getEngine();
  57194. _this._generateMipMaps = generateMipMaps;
  57195. _this._samplingMode = samplingMode;
  57196. _this.autoUpdateTexture = settings.autoUpdateTexture;
  57197. _this.name = name || _this._getName(src);
  57198. _this.video = _this._getVideo(src);
  57199. if (settings.autoPlay !== undefined) {
  57200. _this.video.autoplay = settings.autoPlay;
  57201. }
  57202. if (settings.loop !== undefined) {
  57203. _this.video.loop = settings.loop;
  57204. }
  57205. _this.video.addEventListener("canplay", _this._createInternalTexture);
  57206. _this.video.addEventListener("paused", _this._updateInternalTexture);
  57207. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  57208. _this.video.addEventListener("emptied", _this.reset);
  57209. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  57210. _this._createInternalTexture();
  57211. }
  57212. return _this;
  57213. }
  57214. VideoTexture.prototype._getName = function (src) {
  57215. if (src instanceof HTMLVideoElement) {
  57216. return src.currentSrc;
  57217. }
  57218. if (typeof src === "object") {
  57219. return src.toString();
  57220. }
  57221. return src;
  57222. };
  57223. ;
  57224. VideoTexture.prototype._getVideo = function (src) {
  57225. if (src instanceof HTMLVideoElement) {
  57226. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  57227. return src;
  57228. }
  57229. var video = document.createElement("video");
  57230. if (typeof src === "string") {
  57231. BABYLON.Tools.SetCorsBehavior(src, video);
  57232. video.src = src;
  57233. }
  57234. else {
  57235. BABYLON.Tools.SetCorsBehavior(src[0], video);
  57236. src.forEach(function (url) {
  57237. var source = document.createElement("source");
  57238. source.src = url;
  57239. video.appendChild(source);
  57240. });
  57241. }
  57242. return video;
  57243. };
  57244. ;
  57245. /**
  57246. * Internal method to initiate `update`.
  57247. */
  57248. VideoTexture.prototype._rebuild = function () {
  57249. this.update();
  57250. };
  57251. /**
  57252. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  57253. */
  57254. VideoTexture.prototype.update = function () {
  57255. if (!this.autoUpdateTexture) {
  57256. // Expecting user to call `updateTexture` manually
  57257. return;
  57258. }
  57259. this.updateTexture(true);
  57260. };
  57261. /**
  57262. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  57263. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  57264. */
  57265. VideoTexture.prototype.updateTexture = function (isVisible) {
  57266. if (!isVisible) {
  57267. return;
  57268. }
  57269. if (this.video.paused) {
  57270. return;
  57271. }
  57272. this._updateInternalTexture();
  57273. };
  57274. /**
  57275. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  57276. * @param url New url.
  57277. */
  57278. VideoTexture.prototype.updateURL = function (url) {
  57279. this.video.src = url;
  57280. };
  57281. VideoTexture.prototype.dispose = function () {
  57282. _super.prototype.dispose.call(this);
  57283. this.video.removeEventListener("canplay", this._createInternalTexture);
  57284. this.video.removeEventListener("paused", this._updateInternalTexture);
  57285. this.video.removeEventListener("seeked", this._updateInternalTexture);
  57286. this.video.removeEventListener("emptied", this.reset);
  57287. };
  57288. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  57289. var video = document.createElement("video");
  57290. var constraintsDeviceId;
  57291. if (constraints && constraints.deviceId) {
  57292. constraintsDeviceId = {
  57293. exact: constraints.deviceId,
  57294. };
  57295. }
  57296. navigator.getUserMedia =
  57297. navigator.getUserMedia ||
  57298. navigator.webkitGetUserMedia ||
  57299. navigator.mozGetUserMedia ||
  57300. navigator.msGetUserMedia;
  57301. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  57302. if (navigator.getUserMedia) {
  57303. navigator.getUserMedia({
  57304. video: {
  57305. deviceId: constraintsDeviceId,
  57306. width: {
  57307. min: (constraints && constraints.minWidth) || 256,
  57308. max: (constraints && constraints.maxWidth) || 640,
  57309. },
  57310. height: {
  57311. min: (constraints && constraints.minHeight) || 256,
  57312. max: (constraints && constraints.maxHeight) || 480,
  57313. },
  57314. },
  57315. }, function (stream) {
  57316. if (video.mozSrcObject !== undefined) {
  57317. // hack for Firefox < 19
  57318. video.mozSrcObject = stream;
  57319. }
  57320. else {
  57321. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  57322. }
  57323. video.play();
  57324. if (onReady) {
  57325. onReady(new VideoTexture("video", video, scene, true, true));
  57326. }
  57327. }, function (e) {
  57328. BABYLON.Tools.Error(e.name);
  57329. });
  57330. }
  57331. };
  57332. return VideoTexture;
  57333. }(BABYLON.Texture));
  57334. BABYLON.VideoTexture = VideoTexture;
  57335. })(BABYLON || (BABYLON = {}));
  57336. //# sourceMappingURL=babylon.videoTexture.js.map
  57337. var BABYLON;
  57338. (function (BABYLON) {
  57339. var RawTexture = /** @class */ (function (_super) {
  57340. __extends(RawTexture, _super);
  57341. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  57342. if (generateMipMaps === void 0) { generateMipMaps = true; }
  57343. if (invertY === void 0) { invertY = false; }
  57344. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  57345. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  57346. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  57347. _this.format = format;
  57348. _this._engine = scene.getEngine();
  57349. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  57350. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  57351. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  57352. return _this;
  57353. }
  57354. RawTexture.prototype.update = function (data) {
  57355. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  57356. };
  57357. // Statics
  57358. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  57359. if (generateMipMaps === void 0) { generateMipMaps = true; }
  57360. if (invertY === void 0) { invertY = false; }
  57361. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  57362. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  57363. };
  57364. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  57365. if (generateMipMaps === void 0) { generateMipMaps = true; }
  57366. if (invertY === void 0) { invertY = false; }
  57367. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  57368. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  57369. };
  57370. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  57371. if (generateMipMaps === void 0) { generateMipMaps = true; }
  57372. if (invertY === void 0) { invertY = false; }
  57373. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  57374. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  57375. };
  57376. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  57377. if (generateMipMaps === void 0) { generateMipMaps = true; }
  57378. if (invertY === void 0) { invertY = false; }
  57379. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  57380. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  57381. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  57382. };
  57383. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  57384. if (generateMipMaps === void 0) { generateMipMaps = true; }
  57385. if (invertY === void 0) { invertY = false; }
  57386. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  57387. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  57388. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  57389. };
  57390. return RawTexture;
  57391. }(BABYLON.Texture));
  57392. BABYLON.RawTexture = RawTexture;
  57393. })(BABYLON || (BABYLON = {}));
  57394. //# sourceMappingURL=babylon.rawTexture.js.map
  57395. var BABYLON;
  57396. (function (BABYLON) {
  57397. /**
  57398. * PostProcess can be used to apply a shader to a texture after it has been rendered
  57399. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  57400. */
  57401. var PostProcess = /** @class */ (function () {
  57402. /**
  57403. * Creates a new instance of @see PostProcess
  57404. * @param name The name of the PostProcess.
  57405. * @param fragmentUrl The url of the fragment shader to be used.
  57406. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  57407. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  57408. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  57409. * @param camera The camera to apply the render pass to.
  57410. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  57411. * @param engine The engine which the post process will be applied. (default: current engine)
  57412. * @param reusable If the post process can be reused on the same frame. (default: false)
  57413. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  57414. * @param textureType Type of textures used when performing the post process. (default: 0)
  57415. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  57416. * @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
  57417. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  57418. */
  57419. function PostProcess(/** Name of the PostProcess. */ name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  57420. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  57421. if (defines === void 0) { defines = null; }
  57422. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  57423. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  57424. if (blockCompilation === void 0) { blockCompilation = false; }
  57425. this.name = name;
  57426. /**
  57427. * Width of the texture to apply the post process on
  57428. */
  57429. this.width = -1;
  57430. /**
  57431. * Height of the texture to apply the post process on
  57432. */
  57433. this.height = -1;
  57434. /**
  57435. * If the buffer needs to be cleared before applying the post process. (default: true)
  57436. * Should be set to false if shader will overwrite all previous pixels.
  57437. */
  57438. this.autoClear = true;
  57439. /**
  57440. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  57441. */
  57442. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  57443. /**
  57444. * Animations to be used for the post processing
  57445. */
  57446. this.animations = new Array();
  57447. /**
  57448. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  57449. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  57450. */
  57451. this.enablePixelPerfectMode = false;
  57452. /**
  57453. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  57454. */
  57455. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  57456. /**
  57457. * Force textures to be a power of two (default: false)
  57458. */
  57459. this.alwaysForcePOT = false;
  57460. /**
  57461. * Number of sample textures (default: 1)
  57462. */
  57463. this.samples = 1;
  57464. /**
  57465. * Modify the scale of the post process to be the same as the viewport (default: false)
  57466. */
  57467. this.adaptScaleToCurrentViewport = false;
  57468. this._reusable = false;
  57469. /**
  57470. * Smart array of input and output textures for the post process.
  57471. */
  57472. this._textures = new BABYLON.SmartArray(2);
  57473. /**
  57474. * The index in _textures that corresponds to the output texture.
  57475. */
  57476. this._currentRenderTextureInd = 0;
  57477. this._scaleRatio = new BABYLON.Vector2(1, 1);
  57478. this._texelSize = BABYLON.Vector2.Zero();
  57479. // Events
  57480. /**
  57481. * An event triggered when the postprocess is activated.
  57482. * @type {BABYLON.Observable}
  57483. */
  57484. this.onActivateObservable = new BABYLON.Observable();
  57485. /**
  57486. * An event triggered when the postprocess changes its size.
  57487. * @type {BABYLON.Observable}
  57488. */
  57489. this.onSizeChangedObservable = new BABYLON.Observable();
  57490. /**
  57491. * An event triggered when the postprocess applies its effect.
  57492. * @type {BABYLON.Observable}
  57493. */
  57494. this.onApplyObservable = new BABYLON.Observable();
  57495. /**
  57496. * An event triggered before rendering the postprocess
  57497. * @type {BABYLON.Observable}
  57498. */
  57499. this.onBeforeRenderObservable = new BABYLON.Observable();
  57500. /**
  57501. * An event triggered after rendering the postprocess
  57502. * @type {BABYLON.Observable}
  57503. */
  57504. this.onAfterRenderObservable = new BABYLON.Observable();
  57505. if (camera != null) {
  57506. this._camera = camera;
  57507. this._scene = camera.getScene();
  57508. camera.attachPostProcess(this);
  57509. this._engine = this._scene.getEngine();
  57510. this._scene.postProcesses.push(this);
  57511. }
  57512. else if (engine) {
  57513. this._engine = engine;
  57514. this._engine.postProcesses.push(this);
  57515. }
  57516. this._options = options;
  57517. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  57518. this._reusable = reusable || false;
  57519. this._textureType = textureType;
  57520. this._samplers = samplers || [];
  57521. this._samplers.push("textureSampler");
  57522. this._fragmentUrl = fragmentUrl;
  57523. this._vertexUrl = vertexUrl;
  57524. this._parameters = parameters || [];
  57525. this._parameters.push("scale");
  57526. this._indexParameters = indexParameters;
  57527. if (!blockCompilation) {
  57528. this.updateEffect(defines);
  57529. }
  57530. }
  57531. Object.defineProperty(PostProcess.prototype, "onActivate", {
  57532. /**
  57533. * A function that is added to the onActivateObservable
  57534. */
  57535. set: function (callback) {
  57536. if (this._onActivateObserver) {
  57537. this.onActivateObservable.remove(this._onActivateObserver);
  57538. }
  57539. if (callback) {
  57540. this._onActivateObserver = this.onActivateObservable.add(callback);
  57541. }
  57542. },
  57543. enumerable: true,
  57544. configurable: true
  57545. });
  57546. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  57547. /**
  57548. * A function that is added to the onSizeChangedObservable
  57549. */
  57550. set: function (callback) {
  57551. if (this._onSizeChangedObserver) {
  57552. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  57553. }
  57554. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  57555. },
  57556. enumerable: true,
  57557. configurable: true
  57558. });
  57559. Object.defineProperty(PostProcess.prototype, "onApply", {
  57560. /**
  57561. * A function that is added to the onApplyObservable
  57562. */
  57563. set: function (callback) {
  57564. if (this._onApplyObserver) {
  57565. this.onApplyObservable.remove(this._onApplyObserver);
  57566. }
  57567. this._onApplyObserver = this.onApplyObservable.add(callback);
  57568. },
  57569. enumerable: true,
  57570. configurable: true
  57571. });
  57572. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  57573. /**
  57574. * A function that is added to the onBeforeRenderObservable
  57575. */
  57576. set: function (callback) {
  57577. if (this._onBeforeRenderObserver) {
  57578. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  57579. }
  57580. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  57581. },
  57582. enumerable: true,
  57583. configurable: true
  57584. });
  57585. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  57586. /**
  57587. * A function that is added to the onAfterRenderObservable
  57588. */
  57589. set: function (callback) {
  57590. if (this._onAfterRenderObserver) {
  57591. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  57592. }
  57593. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  57594. },
  57595. enumerable: true,
  57596. configurable: true
  57597. });
  57598. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  57599. /**
  57600. * 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
  57601. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  57602. */
  57603. get: function () {
  57604. return this._textures.data[this._currentRenderTextureInd];
  57605. },
  57606. set: function (value) {
  57607. this._forcedOutputTexture = value;
  57608. },
  57609. enumerable: true,
  57610. configurable: true
  57611. });
  57612. /**
  57613. * Gets the camera which post process is applied to.
  57614. * @returns The camera the post process is applied to.
  57615. */
  57616. PostProcess.prototype.getCamera = function () {
  57617. return this._camera;
  57618. };
  57619. Object.defineProperty(PostProcess.prototype, "texelSize", {
  57620. /**
  57621. * Gets the texel size of the postprocess.
  57622. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  57623. */
  57624. get: function () {
  57625. if (this._shareOutputWithPostProcess) {
  57626. return this._shareOutputWithPostProcess.texelSize;
  57627. }
  57628. if (this._forcedOutputTexture) {
  57629. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  57630. }
  57631. return this._texelSize;
  57632. },
  57633. enumerable: true,
  57634. configurable: true
  57635. });
  57636. /**
  57637. * Gets the engine which this post process belongs to.
  57638. * @returns The engine the post process was enabled with.
  57639. */
  57640. PostProcess.prototype.getEngine = function () {
  57641. return this._engine;
  57642. };
  57643. /**
  57644. * The effect that is created when initializing the post process.
  57645. * @returns The created effect corrisponding the the postprocess.
  57646. */
  57647. PostProcess.prototype.getEffect = function () {
  57648. return this._effect;
  57649. };
  57650. /**
  57651. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  57652. * @param postProcess The post process to share the output with.
  57653. * @returns This post process.
  57654. */
  57655. PostProcess.prototype.shareOutputWith = function (postProcess) {
  57656. this._disposeTextures();
  57657. this._shareOutputWithPostProcess = postProcess;
  57658. return this;
  57659. };
  57660. /**
  57661. * Updates the effect with the current post process compile time values and recompiles the shader.
  57662. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  57663. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  57664. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  57665. * @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
  57666. * @param onCompiled Called when the shader has been compiled.
  57667. * @param onError Called if there is an error when compiling a shader.
  57668. */
  57669. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  57670. if (defines === void 0) { defines = null; }
  57671. if (uniforms === void 0) { uniforms = null; }
  57672. if (samplers === void 0) { samplers = null; }
  57673. 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);
  57674. };
  57675. /**
  57676. * The post process is reusable if it can be used multiple times within one frame.
  57677. * @returns If the post process is reusable
  57678. */
  57679. PostProcess.prototype.isReusable = function () {
  57680. return this._reusable;
  57681. };
  57682. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  57683. PostProcess.prototype.markTextureDirty = function () {
  57684. this.width = -1;
  57685. };
  57686. /**
  57687. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  57688. * 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.
  57689. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  57690. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  57691. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  57692. */
  57693. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  57694. var _this = this;
  57695. if (sourceTexture === void 0) { sourceTexture = null; }
  57696. camera = camera || this._camera;
  57697. var scene = camera.getScene();
  57698. var engine = scene.getEngine();
  57699. var maxSize = engine.getCaps().maxTextureSize;
  57700. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  57701. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  57702. var desiredWidth = (this._options.width || requiredWidth);
  57703. var desiredHeight = this._options.height || requiredHeight;
  57704. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  57705. if (this.adaptScaleToCurrentViewport) {
  57706. var currentViewport = engine.currentViewport;
  57707. if (currentViewport) {
  57708. desiredWidth *= currentViewport.width;
  57709. desiredHeight *= currentViewport.height;
  57710. }
  57711. }
  57712. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  57713. if (!this._options.width) {
  57714. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  57715. }
  57716. if (!this._options.height) {
  57717. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  57718. }
  57719. }
  57720. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  57721. if (this._textures.length > 0) {
  57722. for (var i = 0; i < this._textures.length; i++) {
  57723. this._engine._releaseTexture(this._textures.data[i]);
  57724. }
  57725. this._textures.reset();
  57726. }
  57727. this.width = desiredWidth;
  57728. this.height = desiredHeight;
  57729. var textureSize = { width: this.width, height: this.height };
  57730. var textureOptions = {
  57731. generateMipMaps: false,
  57732. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  57733. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  57734. samplingMode: this.renderTargetSamplingMode,
  57735. type: this._textureType
  57736. };
  57737. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  57738. if (this._reusable) {
  57739. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  57740. }
  57741. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  57742. this.onSizeChangedObservable.notifyObservers(this);
  57743. }
  57744. this._textures.forEach(function (texture) {
  57745. if (texture.samples !== _this.samples) {
  57746. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  57747. }
  57748. });
  57749. }
  57750. var target;
  57751. if (this._shareOutputWithPostProcess) {
  57752. target = this._shareOutputWithPostProcess.inputTexture;
  57753. }
  57754. else if (this._forcedOutputTexture) {
  57755. target = this._forcedOutputTexture;
  57756. this.width = this._forcedOutputTexture.width;
  57757. this.height = this._forcedOutputTexture.height;
  57758. }
  57759. else {
  57760. target = this.inputTexture;
  57761. }
  57762. // Bind the input of this post process to be used as the output of the previous post process.
  57763. if (this.enablePixelPerfectMode) {
  57764. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  57765. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, true);
  57766. }
  57767. else {
  57768. this._scaleRatio.copyFromFloats(1, 1);
  57769. this._engine.bindFramebuffer(target, 0, undefined, undefined, true);
  57770. }
  57771. this.onActivateObservable.notifyObservers(camera);
  57772. // Clear
  57773. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  57774. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  57775. }
  57776. if (this._reusable) {
  57777. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  57778. }
  57779. };
  57780. Object.defineProperty(PostProcess.prototype, "isSupported", {
  57781. /**
  57782. * If the post process is supported.
  57783. */
  57784. get: function () {
  57785. return this._effect.isSupported;
  57786. },
  57787. enumerable: true,
  57788. configurable: true
  57789. });
  57790. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  57791. /**
  57792. * The aspect ratio of the output texture.
  57793. */
  57794. get: function () {
  57795. if (this._shareOutputWithPostProcess) {
  57796. return this._shareOutputWithPostProcess.aspectRatio;
  57797. }
  57798. if (this._forcedOutputTexture) {
  57799. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  57800. }
  57801. return this.width / this.height;
  57802. },
  57803. enumerable: true,
  57804. configurable: true
  57805. });
  57806. /**
  57807. * Get a value indicating if the post-process is ready to be used
  57808. * @returns true if the post-process is ready (shader is compiled)
  57809. */
  57810. PostProcess.prototype.isReady = function () {
  57811. return this._effect && this._effect.isReady();
  57812. };
  57813. /**
  57814. * Binds all textures and uniforms to the shader, this will be run on every pass.
  57815. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  57816. */
  57817. PostProcess.prototype.apply = function () {
  57818. // Check
  57819. if (!this._effect || !this._effect.isReady())
  57820. return null;
  57821. // States
  57822. this._engine.enableEffect(this._effect);
  57823. this._engine.setState(false);
  57824. this._engine.setDepthBuffer(false);
  57825. this._engine.setDepthWrite(false);
  57826. // Alpha
  57827. this._engine.setAlphaMode(this.alphaMode);
  57828. if (this.alphaConstants) {
  57829. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  57830. }
  57831. // Bind the output texture of the preivous post process as the input to this post process.
  57832. var source;
  57833. if (this._shareOutputWithPostProcess) {
  57834. source = this._shareOutputWithPostProcess.inputTexture;
  57835. }
  57836. else if (this._forcedOutputTexture) {
  57837. source = this._forcedOutputTexture;
  57838. }
  57839. else {
  57840. source = this.inputTexture;
  57841. }
  57842. this._effect._bindTexture("textureSampler", source);
  57843. // Parameters
  57844. this._effect.setVector2("scale", this._scaleRatio);
  57845. this.onApplyObservable.notifyObservers(this._effect);
  57846. return this._effect;
  57847. };
  57848. PostProcess.prototype._disposeTextures = function () {
  57849. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  57850. return;
  57851. }
  57852. if (this._textures.length > 0) {
  57853. for (var i = 0; i < this._textures.length; i++) {
  57854. this._engine._releaseTexture(this._textures.data[i]);
  57855. }
  57856. }
  57857. this._textures.dispose();
  57858. };
  57859. /**
  57860. * Disposes the post process.
  57861. * @param camera The camera to dispose the post process on.
  57862. */
  57863. PostProcess.prototype.dispose = function (camera) {
  57864. camera = camera || this._camera;
  57865. this._disposeTextures();
  57866. if (this._scene) {
  57867. var index_1 = this._scene.postProcesses.indexOf(this);
  57868. if (index_1 !== -1) {
  57869. this._scene.postProcesses.splice(index_1, 1);
  57870. }
  57871. }
  57872. else {
  57873. var index_2 = this._engine.postProcesses.indexOf(this);
  57874. if (index_2 !== -1) {
  57875. this._engine.postProcesses.splice(index_2, 1);
  57876. }
  57877. }
  57878. if (!camera) {
  57879. return;
  57880. }
  57881. camera.detachPostProcess(this);
  57882. var index = camera._postProcesses.indexOf(this);
  57883. if (index === 0 && camera._postProcesses.length > 0) {
  57884. this._camera._postProcesses[0].markTextureDirty();
  57885. }
  57886. this.onActivateObservable.clear();
  57887. this.onAfterRenderObservable.clear();
  57888. this.onApplyObservable.clear();
  57889. this.onBeforeRenderObservable.clear();
  57890. this.onSizeChangedObservable.clear();
  57891. };
  57892. return PostProcess;
  57893. }());
  57894. BABYLON.PostProcess = PostProcess;
  57895. })(BABYLON || (BABYLON = {}));
  57896. //# sourceMappingURL=babylon.postProcess.js.map
  57897. var BABYLON;
  57898. (function (BABYLON) {
  57899. var PassPostProcess = /** @class */ (function (_super) {
  57900. __extends(PassPostProcess, _super);
  57901. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  57902. if (camera === void 0) { camera = null; }
  57903. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  57904. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType) || this;
  57905. }
  57906. return PassPostProcess;
  57907. }(BABYLON.PostProcess));
  57908. BABYLON.PassPostProcess = PassPostProcess;
  57909. })(BABYLON || (BABYLON = {}));
  57910. //# sourceMappingURL=babylon.passPostProcess.js.map
  57911. var __assign = (this && this.__assign) || Object.assign || function(t) {
  57912. for (var s, i = 1, n = arguments.length; i < n; i++) {
  57913. s = arguments[i];
  57914. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  57915. t[p] = s[p];
  57916. }
  57917. return t;
  57918. };
  57919. var BABYLON;
  57920. (function (BABYLON) {
  57921. /**
  57922. * Default implementation of @see IShadowGenerator.
  57923. * This is the main object responsible of generating shadows in the framework.
  57924. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  57925. */
  57926. var ShadowGenerator = /** @class */ (function () {
  57927. /**
  57928. * Creates a ShadowGenerator object.
  57929. * A ShadowGenerator is the required tool to use the shadows.
  57930. * Each light casting shadows needs to use its own ShadowGenerator.
  57931. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  57932. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  57933. * @param light The light object generating the shadows.
  57934. * @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.
  57935. */
  57936. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  57937. this._bias = 0.00005;
  57938. this._blurBoxOffset = 1;
  57939. this._blurScale = 2;
  57940. this._blurKernel = 1;
  57941. this._useKernelBlur = false;
  57942. this._filter = ShadowGenerator.FILTER_NONE;
  57943. this._darkness = 0;
  57944. this._transparencyShadow = false;
  57945. /**
  57946. * Controls the extent to which the shadows fade out at the edge of the frustum
  57947. * Used only by directionals and spots
  57948. */
  57949. this.frustumEdgeFalloff = 0;
  57950. /**
  57951. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  57952. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  57953. * It might on the other hand introduce peter panning.
  57954. */
  57955. this.forceBackFacesOnly = false;
  57956. this._lightDirection = BABYLON.Vector3.Zero();
  57957. this._viewMatrix = BABYLON.Matrix.Zero();
  57958. this._projectionMatrix = BABYLON.Matrix.Zero();
  57959. this._transformMatrix = BABYLON.Matrix.Zero();
  57960. this._currentFaceIndex = 0;
  57961. this._currentFaceIndexCache = 0;
  57962. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  57963. this._mapSize = mapSize;
  57964. this._light = light;
  57965. this._scene = light.getScene();
  57966. light._shadowGenerator = this;
  57967. // Texture type fallback from float to int if not supported.
  57968. var caps = this._scene.getEngine().getCaps();
  57969. if (!useFullFloatFirst) {
  57970. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  57971. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  57972. }
  57973. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  57974. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  57975. }
  57976. else {
  57977. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  57978. }
  57979. }
  57980. else {
  57981. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  57982. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  57983. }
  57984. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  57985. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  57986. }
  57987. else {
  57988. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  57989. }
  57990. }
  57991. this._initializeGenerator();
  57992. }
  57993. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  57994. /**
  57995. * Shadow generator mode None: no filtering applied.
  57996. */
  57997. get: function () {
  57998. return ShadowGenerator._FILTER_NONE;
  57999. },
  58000. enumerable: true,
  58001. configurable: true
  58002. });
  58003. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  58004. /**
  58005. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  58006. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  58007. */
  58008. get: function () {
  58009. return ShadowGenerator._FILTER_POISSONSAMPLING;
  58010. },
  58011. enumerable: true,
  58012. configurable: true
  58013. });
  58014. Object.defineProperty(ShadowGenerator, "FILTER_EXPONENTIALSHADOWMAP", {
  58015. /**
  58016. * Shadow generator mode ESM: Exponential Shadow Mapping.
  58017. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  58018. */
  58019. get: function () {
  58020. return ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP;
  58021. },
  58022. enumerable: true,
  58023. configurable: true
  58024. });
  58025. Object.defineProperty(ShadowGenerator, "FILTER_BLUREXPONENTIALSHADOWMAP", {
  58026. /**
  58027. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  58028. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  58029. */
  58030. get: function () {
  58031. return ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP;
  58032. },
  58033. enumerable: true,
  58034. configurable: true
  58035. });
  58036. Object.defineProperty(ShadowGenerator, "FILTER_CLOSEEXPONENTIALSHADOWMAP", {
  58037. /**
  58038. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  58039. * edge artifacts on steep falloff.
  58040. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  58041. */
  58042. get: function () {
  58043. return ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP;
  58044. },
  58045. enumerable: true,
  58046. configurable: true
  58047. });
  58048. Object.defineProperty(ShadowGenerator, "FILTER_BLURCLOSEEXPONENTIALSHADOWMAP", {
  58049. /**
  58050. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  58051. * edge artifacts on steep falloff.
  58052. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  58053. */
  58054. get: function () {
  58055. return ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  58056. },
  58057. enumerable: true,
  58058. configurable: true
  58059. });
  58060. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  58061. /**
  58062. * Gets the bias: offset applied on the depth preventing acnea.
  58063. */
  58064. get: function () {
  58065. return this._bias;
  58066. },
  58067. /**
  58068. * Sets the bias: offset applied on the depth preventing acnea.
  58069. */
  58070. set: function (bias) {
  58071. this._bias = bias;
  58072. },
  58073. enumerable: true,
  58074. configurable: true
  58075. });
  58076. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  58077. /**
  58078. * Gets the blur box offset: offset applied during the blur pass.
  58079. * Only usefull if useKernelBlur = false
  58080. */
  58081. get: function () {
  58082. return this._blurBoxOffset;
  58083. },
  58084. /**
  58085. * Sets the blur box offset: offset applied during the blur pass.
  58086. * Only usefull if useKernelBlur = false
  58087. */
  58088. set: function (value) {
  58089. if (this._blurBoxOffset === value) {
  58090. return;
  58091. }
  58092. this._blurBoxOffset = value;
  58093. this._disposeBlurPostProcesses();
  58094. },
  58095. enumerable: true,
  58096. configurable: true
  58097. });
  58098. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  58099. /**
  58100. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  58101. * 2 means half of the size.
  58102. */
  58103. get: function () {
  58104. return this._blurScale;
  58105. },
  58106. /**
  58107. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  58108. * 2 means half of the size.
  58109. */
  58110. set: function (value) {
  58111. if (this._blurScale === value) {
  58112. return;
  58113. }
  58114. this._blurScale = value;
  58115. this._disposeBlurPostProcesses();
  58116. },
  58117. enumerable: true,
  58118. configurable: true
  58119. });
  58120. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  58121. /**
  58122. * Gets the blur kernel: kernel size of the blur pass.
  58123. * Only usefull if useKernelBlur = true
  58124. */
  58125. get: function () {
  58126. return this._blurKernel;
  58127. },
  58128. /**
  58129. * Sets the blur kernel: kernel size of the blur pass.
  58130. * Only usefull if useKernelBlur = true
  58131. */
  58132. set: function (value) {
  58133. if (this._blurKernel === value) {
  58134. return;
  58135. }
  58136. this._blurKernel = value;
  58137. this._disposeBlurPostProcesses();
  58138. },
  58139. enumerable: true,
  58140. configurable: true
  58141. });
  58142. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  58143. /**
  58144. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  58145. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  58146. */
  58147. get: function () {
  58148. return this._useKernelBlur;
  58149. },
  58150. /**
  58151. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  58152. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  58153. */
  58154. set: function (value) {
  58155. if (this._useKernelBlur === value) {
  58156. return;
  58157. }
  58158. this._useKernelBlur = value;
  58159. this._disposeBlurPostProcesses();
  58160. },
  58161. enumerable: true,
  58162. configurable: true
  58163. });
  58164. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  58165. /**
  58166. * Gets the depth scale used in ESM mode.
  58167. */
  58168. get: function () {
  58169. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  58170. },
  58171. /**
  58172. * Sets the depth scale used in ESM mode.
  58173. * This can override the scale stored on the light.
  58174. */
  58175. set: function (value) {
  58176. this._depthScale = value;
  58177. },
  58178. enumerable: true,
  58179. configurable: true
  58180. });
  58181. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  58182. /**
  58183. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  58184. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  58185. */
  58186. get: function () {
  58187. return this._filter;
  58188. },
  58189. /**
  58190. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  58191. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  58192. */
  58193. set: function (value) {
  58194. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  58195. if (this._light.needCube()) {
  58196. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  58197. this.useExponentialShadowMap = true;
  58198. return;
  58199. }
  58200. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  58201. this.useCloseExponentialShadowMap = true;
  58202. return;
  58203. }
  58204. }
  58205. if (this._filter === value) {
  58206. return;
  58207. }
  58208. this._filter = value;
  58209. this._disposeBlurPostProcesses();
  58210. this._applyFilterValues();
  58211. this._light._markMeshesAsLightDirty();
  58212. },
  58213. enumerable: true,
  58214. configurable: true
  58215. });
  58216. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  58217. /**
  58218. * Gets if the current filter is set to Poisson Sampling aka PCF.
  58219. */
  58220. get: function () {
  58221. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  58222. },
  58223. /**
  58224. * Sets the current filter to Poisson Sampling aka PCF.
  58225. */
  58226. set: function (value) {
  58227. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  58228. return;
  58229. }
  58230. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  58231. },
  58232. enumerable: true,
  58233. configurable: true
  58234. });
  58235. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  58236. /**
  58237. * Gets if the current filter is set to VSM.
  58238. * DEPRECATED. Should use useExponentialShadowMap instead.
  58239. */
  58240. get: function () {
  58241. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  58242. return this.useExponentialShadowMap;
  58243. },
  58244. /**
  58245. * Sets the current filter is to VSM.
  58246. * DEPRECATED. Should use useExponentialShadowMap instead.
  58247. */
  58248. set: function (value) {
  58249. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  58250. this.useExponentialShadowMap = value;
  58251. },
  58252. enumerable: true,
  58253. configurable: true
  58254. });
  58255. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  58256. /**
  58257. * Gets if the current filter is set to blurred VSM.
  58258. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  58259. */
  58260. get: function () {
  58261. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  58262. return this.useBlurExponentialShadowMap;
  58263. },
  58264. /**
  58265. * Sets the current filter is to blurred VSM.
  58266. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  58267. */
  58268. set: function (value) {
  58269. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  58270. this.useBlurExponentialShadowMap = value;
  58271. },
  58272. enumerable: true,
  58273. configurable: true
  58274. });
  58275. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  58276. /**
  58277. * Gets if the current filter is set to ESM.
  58278. */
  58279. get: function () {
  58280. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  58281. },
  58282. /**
  58283. * Sets the current filter is to ESM.
  58284. */
  58285. set: function (value) {
  58286. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  58287. return;
  58288. }
  58289. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  58290. },
  58291. enumerable: true,
  58292. configurable: true
  58293. });
  58294. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  58295. /**
  58296. * Gets if the current filter is set to filtered ESM.
  58297. */
  58298. get: function () {
  58299. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  58300. },
  58301. /**
  58302. * Gets if the current filter is set to filtered ESM.
  58303. */
  58304. set: function (value) {
  58305. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  58306. return;
  58307. }
  58308. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  58309. },
  58310. enumerable: true,
  58311. configurable: true
  58312. });
  58313. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  58314. /**
  58315. * Gets if the current filter is set to "close ESM" (using the inverse of the
  58316. * exponential to prevent steep falloff artifacts).
  58317. */
  58318. get: function () {
  58319. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  58320. },
  58321. /**
  58322. * Sets the current filter to "close ESM" (using the inverse of the
  58323. * exponential to prevent steep falloff artifacts).
  58324. */
  58325. set: function (value) {
  58326. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  58327. return;
  58328. }
  58329. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  58330. },
  58331. enumerable: true,
  58332. configurable: true
  58333. });
  58334. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  58335. /**
  58336. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  58337. * exponential to prevent steep falloff artifacts).
  58338. */
  58339. get: function () {
  58340. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  58341. },
  58342. /**
  58343. * Sets the current filter to fileterd "close ESM" (using the inverse of the
  58344. * exponential to prevent steep falloff artifacts).
  58345. */
  58346. set: function (value) {
  58347. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  58348. return;
  58349. }
  58350. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  58351. },
  58352. enumerable: true,
  58353. configurable: true
  58354. });
  58355. /**
  58356. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  58357. * 0 means strongest and 1 would means no shadow.
  58358. * @returns the darkness.
  58359. */
  58360. ShadowGenerator.prototype.getDarkness = function () {
  58361. return this._darkness;
  58362. };
  58363. /**
  58364. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  58365. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  58366. * @returns the shadow generator allowing fluent coding.
  58367. */
  58368. ShadowGenerator.prototype.setDarkness = function (darkness) {
  58369. if (darkness >= 1.0)
  58370. this._darkness = 1.0;
  58371. else if (darkness <= 0.0)
  58372. this._darkness = 0.0;
  58373. else
  58374. this._darkness = darkness;
  58375. return this;
  58376. };
  58377. /**
  58378. * Sets the ability to have transparent shadow (boolean).
  58379. * @param transparent True if transparent else False
  58380. * @returns the shadow generator allowing fluent coding
  58381. */
  58382. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  58383. this._transparencyShadow = transparent;
  58384. return this;
  58385. };
  58386. /**
  58387. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  58388. * @returns The render target texture if present otherwise, null
  58389. */
  58390. ShadowGenerator.prototype.getShadowMap = function () {
  58391. return this._shadowMap;
  58392. };
  58393. /**
  58394. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  58395. * @returns The render target texture if the shadow map is present otherwise, null
  58396. */
  58397. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  58398. if (this._shadowMap2) {
  58399. return this._shadowMap2;
  58400. }
  58401. return this._shadowMap;
  58402. };
  58403. /**
  58404. * Helper function to add a mesh and its descendants to the list of shadow casters.
  58405. * @param mesh Mesh to add
  58406. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  58407. * @returns the Shadow Generator itself
  58408. */
  58409. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  58410. if (includeDescendants === void 0) { includeDescendants = true; }
  58411. if (!this._shadowMap) {
  58412. return this;
  58413. }
  58414. if (!this._shadowMap.renderList) {
  58415. this._shadowMap.renderList = [];
  58416. }
  58417. this._shadowMap.renderList.push(mesh);
  58418. if (includeDescendants) {
  58419. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  58420. }
  58421. return this;
  58422. var _a;
  58423. };
  58424. /**
  58425. * Helper function to remove a mesh and its descendants from the list of shadow casters
  58426. * @param mesh Mesh to remove
  58427. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  58428. * @returns the Shadow Generator itself
  58429. */
  58430. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  58431. if (includeDescendants === void 0) { includeDescendants = true; }
  58432. if (!this._shadowMap || !this._shadowMap.renderList) {
  58433. return this;
  58434. }
  58435. var index = this._shadowMap.renderList.indexOf(mesh);
  58436. if (index !== -1) {
  58437. this._shadowMap.renderList.splice(index, 1);
  58438. }
  58439. if (includeDescendants) {
  58440. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  58441. var child = _a[_i];
  58442. this.removeShadowCaster(child);
  58443. }
  58444. }
  58445. return this;
  58446. };
  58447. /**
  58448. * Returns the associated light object.
  58449. * @returns the light generating the shadow
  58450. */
  58451. ShadowGenerator.prototype.getLight = function () {
  58452. return this._light;
  58453. };
  58454. ShadowGenerator.prototype._initializeGenerator = function () {
  58455. this._light._markMeshesAsLightDirty();
  58456. this._initializeShadowMap();
  58457. };
  58458. ShadowGenerator.prototype._initializeShadowMap = function () {
  58459. var _this = this;
  58460. // Render target
  58461. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  58462. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58463. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58464. this._shadowMap.anisotropicFilteringLevel = 1;
  58465. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  58466. this._shadowMap.renderParticles = false;
  58467. this._shadowMap.ignoreCameraViewport = true;
  58468. // Record Face Index before render.
  58469. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  58470. _this._currentFaceIndex = faceIndex;
  58471. });
  58472. // Custom render function.
  58473. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  58474. // Blur if required afer render.
  58475. this._shadowMap.onAfterUnbindObservable.add(function () {
  58476. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  58477. return;
  58478. }
  58479. var shadowMap = _this.getShadowMapForRendering();
  58480. if (shadowMap) {
  58481. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  58482. }
  58483. });
  58484. // Clear according to the chosen filter.
  58485. this._shadowMap.onClearObservable.add(function (engine) {
  58486. if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  58487. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true, true);
  58488. }
  58489. else {
  58490. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  58491. }
  58492. });
  58493. };
  58494. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  58495. var _this = this;
  58496. var engine = this._scene.getEngine();
  58497. var targetSize = this._mapSize / this.blurScale;
  58498. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  58499. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  58500. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58501. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58502. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  58503. }
  58504. if (this.useKernelBlur) {
  58505. 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);
  58506. this._kernelBlurXPostprocess.width = targetSize;
  58507. this._kernelBlurXPostprocess.height = targetSize;
  58508. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  58509. effect.setTexture("textureSampler", _this._shadowMap);
  58510. });
  58511. 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);
  58512. this._kernelBlurXPostprocess.autoClear = false;
  58513. this._kernelBlurYPostprocess.autoClear = false;
  58514. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  58515. this._kernelBlurXPostprocess.packedFloat = true;
  58516. this._kernelBlurYPostprocess.packedFloat = true;
  58517. }
  58518. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  58519. }
  58520. else {
  58521. 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);
  58522. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  58523. effect.setFloat2("screenSize", targetSize, targetSize);
  58524. effect.setTexture("textureSampler", _this._shadowMap);
  58525. });
  58526. this._boxBlurPostprocess.autoClear = false;
  58527. this._blurPostProcesses = [this._boxBlurPostprocess];
  58528. }
  58529. };
  58530. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  58531. var index;
  58532. var engine = this._scene.getEngine();
  58533. if (depthOnlySubMeshes.length) {
  58534. engine.setColorWrite(false);
  58535. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  58536. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  58537. }
  58538. engine.setColorWrite(true);
  58539. }
  58540. for (index = 0; index < opaqueSubMeshes.length; index++) {
  58541. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  58542. }
  58543. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  58544. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  58545. }
  58546. if (this._transparencyShadow) {
  58547. for (index = 0; index < transparentSubMeshes.length; index++) {
  58548. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  58549. }
  58550. }
  58551. };
  58552. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  58553. var _this = this;
  58554. var mesh = subMesh.getRenderingMesh();
  58555. var scene = this._scene;
  58556. var engine = scene.getEngine();
  58557. var material = subMesh.getMaterial();
  58558. if (!material) {
  58559. return;
  58560. }
  58561. // Culling
  58562. engine.setState(material.backFaceCulling);
  58563. // Managing instances
  58564. var batch = mesh._getInstancesRenderList(subMesh._id);
  58565. if (batch.mustReturn) {
  58566. return;
  58567. }
  58568. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  58569. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  58570. engine.enableEffect(this._effect);
  58571. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  58572. this._effect.setFloat2("biasAndScale", this.bias, this.depthScale);
  58573. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  58574. this._effect.setVector3("lightPosition", this.getLight().position);
  58575. if (scene.activeCamera) {
  58576. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  58577. }
  58578. // Alpha test
  58579. if (material && material.needAlphaTesting()) {
  58580. var alphaTexture = material.getAlphaTestTexture();
  58581. if (alphaTexture) {
  58582. this._effect.setTexture("diffuseSampler", alphaTexture);
  58583. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  58584. }
  58585. }
  58586. // Bones
  58587. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  58588. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  58589. }
  58590. if (this.forceBackFacesOnly) {
  58591. engine.setState(true, 0, false, true);
  58592. }
  58593. // Draw
  58594. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  58595. if (this.forceBackFacesOnly) {
  58596. engine.setState(true, 0, false, false);
  58597. }
  58598. }
  58599. else {
  58600. // Need to reset refresh rate of the shadowMap
  58601. if (this._shadowMap) {
  58602. this._shadowMap.resetRefreshCounter();
  58603. }
  58604. }
  58605. };
  58606. ShadowGenerator.prototype._applyFilterValues = function () {
  58607. if (!this._shadowMap) {
  58608. return;
  58609. }
  58610. if (this.filter === ShadowGenerator.FILTER_NONE) {
  58611. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  58612. }
  58613. else {
  58614. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  58615. }
  58616. };
  58617. /**
  58618. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  58619. * @param onCompiled Callback triggered at the and of the effects compilation
  58620. * @param options Sets of optional options forcing the compilation with different modes
  58621. */
  58622. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  58623. var _this = this;
  58624. var localOptions = __assign({ useInstances: false }, options);
  58625. var shadowMap = this.getShadowMap();
  58626. if (!shadowMap) {
  58627. if (onCompiled) {
  58628. onCompiled(this);
  58629. }
  58630. return;
  58631. }
  58632. var renderList = shadowMap.renderList;
  58633. if (!renderList) {
  58634. if (onCompiled) {
  58635. onCompiled(this);
  58636. }
  58637. return;
  58638. }
  58639. var subMeshes = new Array();
  58640. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  58641. var mesh = renderList_1[_i];
  58642. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  58643. }
  58644. if (subMeshes.length === 0) {
  58645. if (onCompiled) {
  58646. onCompiled(this);
  58647. }
  58648. return;
  58649. }
  58650. var currentIndex = 0;
  58651. var checkReady = function () {
  58652. if (!_this._scene || !_this._scene.getEngine()) {
  58653. return;
  58654. }
  58655. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  58656. currentIndex++;
  58657. if (currentIndex >= subMeshes.length) {
  58658. if (onCompiled) {
  58659. onCompiled(_this);
  58660. }
  58661. return;
  58662. }
  58663. }
  58664. setTimeout(checkReady, 16);
  58665. };
  58666. checkReady();
  58667. };
  58668. /**
  58669. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  58670. * @param options Sets of optional options forcing the compilation with different modes
  58671. * @returns A promise that resolves when the compilation completes
  58672. */
  58673. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  58674. var _this = this;
  58675. return new Promise(function (resolve) {
  58676. _this.forceCompilation(function () {
  58677. resolve();
  58678. }, options);
  58679. });
  58680. };
  58681. /**
  58682. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  58683. * @param subMesh The submesh we want to render in the shadow map
  58684. * @param useInstances Defines wether will draw in the map using instances
  58685. * @returns true if ready otherwise, false
  58686. */
  58687. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  58688. var defines = [];
  58689. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  58690. defines.push("#define FLOAT");
  58691. }
  58692. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  58693. defines.push("#define ESM");
  58694. }
  58695. var attribs = [BABYLON.VertexBuffer.PositionKind];
  58696. var mesh = subMesh.getMesh();
  58697. var material = subMesh.getMaterial();
  58698. // Alpha test
  58699. if (material && material.needAlphaTesting()) {
  58700. var alphaTexture = material.getAlphaTestTexture();
  58701. if (alphaTexture) {
  58702. defines.push("#define ALPHATEST");
  58703. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  58704. attribs.push(BABYLON.VertexBuffer.UVKind);
  58705. defines.push("#define UV1");
  58706. }
  58707. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  58708. if (alphaTexture.coordinatesIndex === 1) {
  58709. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  58710. defines.push("#define UV2");
  58711. }
  58712. }
  58713. }
  58714. }
  58715. // Bones
  58716. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  58717. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  58718. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  58719. if (mesh.numBoneInfluencers > 4) {
  58720. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  58721. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  58722. }
  58723. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  58724. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  58725. }
  58726. else {
  58727. defines.push("#define NUM_BONE_INFLUENCERS 0");
  58728. }
  58729. // Instances
  58730. if (useInstances) {
  58731. defines.push("#define INSTANCES");
  58732. attribs.push("world0");
  58733. attribs.push("world1");
  58734. attribs.push("world2");
  58735. attribs.push("world3");
  58736. }
  58737. // Get correct effect
  58738. var join = defines.join("\n");
  58739. if (this._cachedDefines !== join) {
  58740. this._cachedDefines = join;
  58741. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues", "biasAndScale"], ["diffuseSampler"], join);
  58742. }
  58743. if (!this._effect.isReady()) {
  58744. return false;
  58745. }
  58746. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  58747. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  58748. this._initializeBlurRTTAndPostProcesses();
  58749. }
  58750. }
  58751. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  58752. return false;
  58753. }
  58754. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  58755. return false;
  58756. }
  58757. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  58758. return false;
  58759. }
  58760. return true;
  58761. };
  58762. /**
  58763. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  58764. * @param defines Defines of the material we want to update
  58765. * @param lightIndex Index of the light in the enabled light list of the material
  58766. */
  58767. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  58768. var scene = this._scene;
  58769. var light = this._light;
  58770. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  58771. return;
  58772. }
  58773. defines["SHADOW" + lightIndex] = true;
  58774. if (this.usePoissonSampling) {
  58775. defines["SHADOWPCF" + lightIndex] = true;
  58776. }
  58777. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  58778. defines["SHADOWESM" + lightIndex] = true;
  58779. }
  58780. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  58781. defines["SHADOWCLOSEESM" + lightIndex] = true;
  58782. }
  58783. if (light.needCube()) {
  58784. defines["SHADOWCUBE" + lightIndex] = true;
  58785. }
  58786. };
  58787. /**
  58788. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  58789. * defined in the generator but impacting the effect).
  58790. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  58791. * @param effect The effect we are binfing the information for
  58792. */
  58793. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  58794. var light = this._light;
  58795. var scene = this._scene;
  58796. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  58797. return;
  58798. }
  58799. var camera = scene.activeCamera;
  58800. if (!camera) {
  58801. return;
  58802. }
  58803. var shadowMap = this.getShadowMap();
  58804. if (!shadowMap) {
  58805. return;
  58806. }
  58807. if (!light.needCube()) {
  58808. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  58809. }
  58810. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  58811. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  58812. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  58813. };
  58814. /**
  58815. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  58816. * (eq to shadow prjection matrix * light transform matrix)
  58817. * @returns The transform matrix used to create the shadow map
  58818. */
  58819. ShadowGenerator.prototype.getTransformMatrix = function () {
  58820. var scene = this._scene;
  58821. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  58822. return this._transformMatrix;
  58823. }
  58824. this._currentRenderID = scene.getRenderId();
  58825. this._currentFaceIndexCache = this._currentFaceIndex;
  58826. var lightPosition = this._light.position;
  58827. if (this._light.computeTransformedInformation()) {
  58828. lightPosition = this._light.transformedPosition;
  58829. }
  58830. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  58831. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  58832. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  58833. }
  58834. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  58835. this._cachedPosition = lightPosition.clone();
  58836. this._cachedDirection = this._lightDirection.clone();
  58837. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  58838. var shadowMap = this.getShadowMap();
  58839. if (shadowMap) {
  58840. var renderList = shadowMap.renderList;
  58841. if (renderList) {
  58842. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  58843. }
  58844. }
  58845. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  58846. }
  58847. return this._transformMatrix;
  58848. };
  58849. /**
  58850. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  58851. * Cube and 2D textures for instance.
  58852. */
  58853. ShadowGenerator.prototype.recreateShadowMap = function () {
  58854. var shadowMap = this._shadowMap;
  58855. if (!shadowMap) {
  58856. return;
  58857. }
  58858. // Track render list.
  58859. var renderList = shadowMap.renderList;
  58860. // Clean up existing data.
  58861. this._disposeRTTandPostProcesses();
  58862. // Reinitializes.
  58863. this._initializeGenerator();
  58864. // Reaffect the filter to ensure a correct fallback if necessary.
  58865. this.filter = this.filter;
  58866. // Reaffect the filter.
  58867. this._applyFilterValues();
  58868. // Reaffect Render List.
  58869. this._shadowMap.renderList = renderList;
  58870. };
  58871. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  58872. if (this._shadowMap2) {
  58873. this._shadowMap2.dispose();
  58874. this._shadowMap2 = null;
  58875. }
  58876. if (this._boxBlurPostprocess) {
  58877. this._boxBlurPostprocess.dispose();
  58878. this._boxBlurPostprocess = null;
  58879. }
  58880. if (this._kernelBlurXPostprocess) {
  58881. this._kernelBlurXPostprocess.dispose();
  58882. this._kernelBlurXPostprocess = null;
  58883. }
  58884. if (this._kernelBlurYPostprocess) {
  58885. this._kernelBlurYPostprocess.dispose();
  58886. this._kernelBlurYPostprocess = null;
  58887. }
  58888. this._blurPostProcesses = [];
  58889. };
  58890. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  58891. if (this._shadowMap) {
  58892. this._shadowMap.dispose();
  58893. this._shadowMap = null;
  58894. }
  58895. this._disposeBlurPostProcesses();
  58896. };
  58897. /**
  58898. * Disposes the ShadowGenerator.
  58899. * Returns nothing.
  58900. */
  58901. ShadowGenerator.prototype.dispose = function () {
  58902. this._disposeRTTandPostProcesses();
  58903. if (this._light) {
  58904. this._light._shadowGenerator = null;
  58905. this._light._markMeshesAsLightDirty();
  58906. }
  58907. };
  58908. /**
  58909. * Serializes the shadow generator setup to a json object.
  58910. * @returns The serialized JSON object
  58911. */
  58912. ShadowGenerator.prototype.serialize = function () {
  58913. var serializationObject = {};
  58914. var shadowMap = this.getShadowMap();
  58915. if (!shadowMap) {
  58916. return serializationObject;
  58917. }
  58918. serializationObject.lightId = this._light.id;
  58919. serializationObject.mapSize = shadowMap.getRenderSize();
  58920. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  58921. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  58922. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  58923. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  58924. serializationObject.usePoissonSampling = this.usePoissonSampling;
  58925. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  58926. serializationObject.depthScale = this.depthScale;
  58927. serializationObject.darkness = this.getDarkness();
  58928. serializationObject.blurBoxOffset = this.blurBoxOffset;
  58929. serializationObject.blurKernel = this.blurKernel;
  58930. serializationObject.blurScale = this.blurScale;
  58931. serializationObject.useKernelBlur = this.useKernelBlur;
  58932. serializationObject.transparencyShadow = this._transparencyShadow;
  58933. serializationObject.renderList = [];
  58934. if (shadowMap.renderList) {
  58935. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  58936. var mesh = shadowMap.renderList[meshIndex];
  58937. serializationObject.renderList.push(mesh.id);
  58938. }
  58939. }
  58940. return serializationObject;
  58941. };
  58942. /**
  58943. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  58944. * @param parsedShadowGenerator The JSON object to parse
  58945. * @param scene The scene to create the shadow map for
  58946. * @returns The parsed shadow generator
  58947. */
  58948. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  58949. //casting to point light, as light is missing the position attr and typescript complains.
  58950. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  58951. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  58952. var shadowMap = shadowGenerator.getShadowMap();
  58953. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  58954. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  58955. meshes.forEach(function (mesh) {
  58956. if (!shadowMap) {
  58957. return;
  58958. }
  58959. if (!shadowMap.renderList) {
  58960. shadowMap.renderList = [];
  58961. }
  58962. shadowMap.renderList.push(mesh);
  58963. });
  58964. }
  58965. if (parsedShadowGenerator.usePoissonSampling) {
  58966. shadowGenerator.usePoissonSampling = true;
  58967. }
  58968. else if (parsedShadowGenerator.useExponentialShadowMap) {
  58969. shadowGenerator.useExponentialShadowMap = true;
  58970. }
  58971. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  58972. shadowGenerator.useBlurExponentialShadowMap = true;
  58973. }
  58974. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  58975. shadowGenerator.useCloseExponentialShadowMap = true;
  58976. }
  58977. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  58978. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  58979. }
  58980. else if (parsedShadowGenerator.useVarianceShadowMap) {
  58981. shadowGenerator.useExponentialShadowMap = true;
  58982. }
  58983. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  58984. shadowGenerator.useBlurExponentialShadowMap = true;
  58985. }
  58986. if (parsedShadowGenerator.depthScale) {
  58987. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  58988. }
  58989. if (parsedShadowGenerator.blurScale) {
  58990. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  58991. }
  58992. if (parsedShadowGenerator.blurBoxOffset) {
  58993. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  58994. }
  58995. if (parsedShadowGenerator.useKernelBlur) {
  58996. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  58997. }
  58998. if (parsedShadowGenerator.blurKernel) {
  58999. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  59000. }
  59001. if (parsedShadowGenerator.bias !== undefined) {
  59002. shadowGenerator.bias = parsedShadowGenerator.bias;
  59003. }
  59004. if (parsedShadowGenerator.darkness) {
  59005. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  59006. }
  59007. if (parsedShadowGenerator.transparencyShadow) {
  59008. shadowGenerator.setTransparencyShadow(true);
  59009. }
  59010. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  59011. return shadowGenerator;
  59012. };
  59013. ShadowGenerator._FILTER_NONE = 0;
  59014. ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP = 1;
  59015. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  59016. ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  59017. ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  59018. ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  59019. return ShadowGenerator;
  59020. }());
  59021. BABYLON.ShadowGenerator = ShadowGenerator;
  59022. })(BABYLON || (BABYLON = {}));
  59023. //# sourceMappingURL=babylon.shadowGenerator.js.map
  59024. var BABYLON;
  59025. (function (BABYLON) {
  59026. var DefaultLoadingScreen = /** @class */ (function () {
  59027. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  59028. if (_loadingText === void 0) { _loadingText = ""; }
  59029. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  59030. var _this = this;
  59031. this._renderingCanvas = _renderingCanvas;
  59032. this._loadingText = _loadingText;
  59033. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  59034. // Resize
  59035. this._resizeLoadingUI = function () {
  59036. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  59037. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  59038. if (!_this._loadingDiv) {
  59039. return;
  59040. }
  59041. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  59042. _this._loadingDiv.style.left = canvasRect.left + "px";
  59043. _this._loadingDiv.style.top = canvasRect.top + "px";
  59044. _this._loadingDiv.style.width = canvasRect.width + "px";
  59045. _this._loadingDiv.style.height = canvasRect.height + "px";
  59046. };
  59047. }
  59048. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  59049. if (this._loadingDiv) {
  59050. // Do not add a loading screen if there is already one
  59051. return;
  59052. }
  59053. this._loadingDiv = document.createElement("div");
  59054. this._loadingDiv.id = "babylonjsLoadingDiv";
  59055. this._loadingDiv.style.opacity = "0";
  59056. this._loadingDiv.style.transition = "opacity 1.5s ease";
  59057. this._loadingDiv.style.pointerEvents = "none";
  59058. // Loading text
  59059. this._loadingTextDiv = document.createElement("div");
  59060. this._loadingTextDiv.style.position = "absolute";
  59061. this._loadingTextDiv.style.left = "0";
  59062. this._loadingTextDiv.style.top = "50%";
  59063. this._loadingTextDiv.style.marginTop = "80px";
  59064. this._loadingTextDiv.style.width = "100%";
  59065. this._loadingTextDiv.style.height = "20px";
  59066. this._loadingTextDiv.style.fontFamily = "Arial";
  59067. this._loadingTextDiv.style.fontSize = "14px";
  59068. this._loadingTextDiv.style.color = "white";
  59069. this._loadingTextDiv.style.textAlign = "center";
  59070. this._loadingTextDiv.innerHTML = "Loading";
  59071. this._loadingDiv.appendChild(this._loadingTextDiv);
  59072. //set the predefined text
  59073. this._loadingTextDiv.innerHTML = this._loadingText;
  59074. // Generating keyframes
  59075. var style = document.createElement('style');
  59076. style.type = 'text/css';
  59077. 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 }";
  59078. style.innerHTML = keyFrames;
  59079. document.getElementsByTagName('head')[0].appendChild(style);
  59080. // Loading img
  59081. var imgBack = new Image();
  59082. 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";
  59083. imgBack.style.position = "absolute";
  59084. imgBack.style.left = "50%";
  59085. imgBack.style.top = "50%";
  59086. imgBack.style.marginLeft = "-60px";
  59087. imgBack.style.marginTop = "-60px";
  59088. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  59089. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  59090. imgBack.style.transformOrigin = "50% 50%";
  59091. imgBack.style.webkitTransformOrigin = "50% 50%";
  59092. this._loadingDiv.appendChild(imgBack);
  59093. this._resizeLoadingUI();
  59094. window.addEventListener("resize", this._resizeLoadingUI);
  59095. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  59096. document.body.appendChild(this._loadingDiv);
  59097. this._loadingDiv.style.opacity = "1";
  59098. };
  59099. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  59100. var _this = this;
  59101. if (!this._loadingDiv) {
  59102. return;
  59103. }
  59104. var onTransitionEnd = function () {
  59105. if (!_this._loadingDiv) {
  59106. return;
  59107. }
  59108. document.body.removeChild(_this._loadingDiv);
  59109. window.removeEventListener("resize", _this._resizeLoadingUI);
  59110. _this._loadingDiv = null;
  59111. };
  59112. this._loadingDiv.style.opacity = "0";
  59113. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  59114. };
  59115. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  59116. set: function (text) {
  59117. this._loadingText = text;
  59118. if (this._loadingTextDiv) {
  59119. this._loadingTextDiv.innerHTML = this._loadingText;
  59120. }
  59121. },
  59122. enumerable: true,
  59123. configurable: true
  59124. });
  59125. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  59126. get: function () {
  59127. return this._loadingDivBackgroundColor;
  59128. },
  59129. set: function (color) {
  59130. this._loadingDivBackgroundColor = color;
  59131. if (!this._loadingDiv) {
  59132. return;
  59133. }
  59134. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  59135. },
  59136. enumerable: true,
  59137. configurable: true
  59138. });
  59139. return DefaultLoadingScreen;
  59140. }());
  59141. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  59142. })(BABYLON || (BABYLON = {}));
  59143. //# sourceMappingURL=babylon.loadingScreen.js.map
  59144. var BABYLON;
  59145. (function (BABYLON) {
  59146. var SceneLoaderProgressEvent = /** @class */ (function () {
  59147. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  59148. this.lengthComputable = lengthComputable;
  59149. this.loaded = loaded;
  59150. this.total = total;
  59151. }
  59152. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  59153. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  59154. };
  59155. return SceneLoaderProgressEvent;
  59156. }());
  59157. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  59158. var SceneLoader = /** @class */ (function () {
  59159. function SceneLoader() {
  59160. }
  59161. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  59162. get: function () {
  59163. return 0;
  59164. },
  59165. enumerable: true,
  59166. configurable: true
  59167. });
  59168. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  59169. get: function () {
  59170. return 1;
  59171. },
  59172. enumerable: true,
  59173. configurable: true
  59174. });
  59175. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  59176. get: function () {
  59177. return 2;
  59178. },
  59179. enumerable: true,
  59180. configurable: true
  59181. });
  59182. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  59183. get: function () {
  59184. return 3;
  59185. },
  59186. enumerable: true,
  59187. configurable: true
  59188. });
  59189. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  59190. get: function () {
  59191. return SceneLoader._ForceFullSceneLoadingForIncremental;
  59192. },
  59193. set: function (value) {
  59194. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  59195. },
  59196. enumerable: true,
  59197. configurable: true
  59198. });
  59199. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  59200. get: function () {
  59201. return SceneLoader._ShowLoadingScreen;
  59202. },
  59203. set: function (value) {
  59204. SceneLoader._ShowLoadingScreen = value;
  59205. },
  59206. enumerable: true,
  59207. configurable: true
  59208. });
  59209. Object.defineProperty(SceneLoader, "loggingLevel", {
  59210. get: function () {
  59211. return SceneLoader._loggingLevel;
  59212. },
  59213. set: function (value) {
  59214. SceneLoader._loggingLevel = value;
  59215. },
  59216. enumerable: true,
  59217. configurable: true
  59218. });
  59219. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  59220. get: function () {
  59221. return SceneLoader._CleanBoneMatrixWeights;
  59222. },
  59223. set: function (value) {
  59224. SceneLoader._CleanBoneMatrixWeights = value;
  59225. },
  59226. enumerable: true,
  59227. configurable: true
  59228. });
  59229. SceneLoader._getDefaultPlugin = function () {
  59230. return SceneLoader._registeredPlugins[".babylon"];
  59231. };
  59232. SceneLoader._getPluginForExtension = function (extension) {
  59233. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  59234. if (registeredPlugin) {
  59235. return registeredPlugin;
  59236. }
  59237. BABYLON.Tools.Warn("Unable to find a plugin to load " + extension + " files. Trying to use .babylon default plugin.");
  59238. return SceneLoader._getDefaultPlugin();
  59239. };
  59240. SceneLoader._getPluginForDirectLoad = function (data) {
  59241. for (var extension in SceneLoader._registeredPlugins) {
  59242. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  59243. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  59244. return SceneLoader._registeredPlugins[extension];
  59245. }
  59246. }
  59247. return SceneLoader._getDefaultPlugin();
  59248. };
  59249. SceneLoader._getPluginForFilename = function (sceneFilename) {
  59250. if (sceneFilename.name) {
  59251. sceneFilename = sceneFilename.name;
  59252. }
  59253. var queryStringPosition = sceneFilename.indexOf("?");
  59254. if (queryStringPosition !== -1) {
  59255. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  59256. }
  59257. var dotPosition = sceneFilename.lastIndexOf(".");
  59258. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  59259. return SceneLoader._getPluginForExtension(extension);
  59260. };
  59261. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  59262. SceneLoader._getDirectLoad = function (sceneFilename) {
  59263. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  59264. return sceneFilename.substr(5);
  59265. }
  59266. return null;
  59267. };
  59268. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  59269. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  59270. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  59271. var plugin;
  59272. if (registeredPlugin.plugin.createPlugin) {
  59273. plugin = registeredPlugin.plugin.createPlugin();
  59274. }
  59275. else {
  59276. plugin = registeredPlugin.plugin;
  59277. }
  59278. var useArrayBuffer = registeredPlugin.isBinary;
  59279. var database;
  59280. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  59281. var dataCallback = function (data, responseURL) {
  59282. if (scene.isDisposed) {
  59283. onError("Scene has been disposed");
  59284. return;
  59285. }
  59286. scene.database = database;
  59287. onSuccess(plugin, data, responseURL);
  59288. };
  59289. var request = null;
  59290. var pluginDisposed = false;
  59291. var onDisposeObservable = plugin.onDisposeObservable;
  59292. if (onDisposeObservable) {
  59293. onDisposeObservable.add(function () {
  59294. pluginDisposed = true;
  59295. if (request) {
  59296. request.abort();
  59297. request = null;
  59298. }
  59299. onDispose();
  59300. });
  59301. }
  59302. var manifestChecked = function () {
  59303. if (pluginDisposed) {
  59304. return;
  59305. }
  59306. var url = rootUrl + sceneFilename;
  59307. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  59308. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  59309. } : undefined, database, useArrayBuffer, function (request, exception) {
  59310. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  59311. });
  59312. };
  59313. if (directLoad) {
  59314. dataCallback(directLoad);
  59315. return plugin;
  59316. }
  59317. if (rootUrl.indexOf("file:") === -1) {
  59318. if (scene.getEngine().enableOfflineSupport) {
  59319. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  59320. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  59321. }
  59322. else {
  59323. manifestChecked();
  59324. }
  59325. }
  59326. else {
  59327. var fileOrString = sceneFilename;
  59328. if (fileOrString.name) {
  59329. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  59330. }
  59331. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  59332. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  59333. }
  59334. else {
  59335. onError("Unable to find file named " + sceneFilename);
  59336. }
  59337. }
  59338. return plugin;
  59339. };
  59340. // Public functions
  59341. SceneLoader.GetPluginForExtension = function (extension) {
  59342. return SceneLoader._getPluginForExtension(extension).plugin;
  59343. };
  59344. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  59345. return !!SceneLoader._registeredPlugins[extension];
  59346. };
  59347. SceneLoader.RegisterPlugin = function (plugin) {
  59348. if (typeof plugin.extensions === "string") {
  59349. var extension = plugin.extensions;
  59350. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  59351. plugin: plugin,
  59352. isBinary: false
  59353. };
  59354. }
  59355. else {
  59356. var extensions = plugin.extensions;
  59357. Object.keys(extensions).forEach(function (extension) {
  59358. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  59359. plugin: plugin,
  59360. isBinary: extensions[extension].isBinary
  59361. };
  59362. });
  59363. }
  59364. };
  59365. /**
  59366. * Import meshes into a scene
  59367. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  59368. * @param rootUrl a string that defines the root url for scene and resources
  59369. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  59370. * @param scene the instance of BABYLON.Scene to append to
  59371. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  59372. * @param onProgress a callback with a progress event for each file being loaded
  59373. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  59374. * @param pluginExtension the extension used to determine the plugin
  59375. * @returns The loaded plugin
  59376. */
  59377. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  59378. if (onSuccess === void 0) { onSuccess = null; }
  59379. if (onProgress === void 0) { onProgress = null; }
  59380. if (onError === void 0) { onError = null; }
  59381. if (pluginExtension === void 0) { pluginExtension = null; }
  59382. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  59383. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  59384. return null;
  59385. }
  59386. var loadingToken = {};
  59387. scene._addPendingData(loadingToken);
  59388. var disposeHandler = function () {
  59389. scene._removePendingData(loadingToken);
  59390. };
  59391. var errorHandler = function (message, exception) {
  59392. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  59393. if (onError) {
  59394. onError(scene, errorMessage, exception);
  59395. }
  59396. else {
  59397. BABYLON.Tools.Error(errorMessage);
  59398. // should the exception be thrown?
  59399. }
  59400. disposeHandler();
  59401. };
  59402. var progressHandler = onProgress ? function (event) {
  59403. try {
  59404. onProgress(event);
  59405. }
  59406. catch (e) {
  59407. errorHandler("Error in onProgress callback", e);
  59408. }
  59409. } : undefined;
  59410. var successHandler = function (meshes, particleSystems, skeletons) {
  59411. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  59412. if (onSuccess) {
  59413. try {
  59414. onSuccess(meshes, particleSystems, skeletons);
  59415. }
  59416. catch (e) {
  59417. errorHandler("Error in onSuccess callback", e);
  59418. }
  59419. }
  59420. scene._removePendingData(loadingToken);
  59421. };
  59422. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  59423. if (plugin.rewriteRootURL) {
  59424. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  59425. }
  59426. if (sceneFilename === "") {
  59427. if (sceneFilename === "") {
  59428. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  59429. }
  59430. }
  59431. if (plugin.importMesh) {
  59432. var syncedPlugin = plugin;
  59433. var meshes = new Array();
  59434. var particleSystems = new Array();
  59435. var skeletons = new Array();
  59436. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  59437. return;
  59438. }
  59439. scene.loadingPluginName = plugin.name;
  59440. successHandler(meshes, particleSystems, skeletons);
  59441. }
  59442. else {
  59443. var asyncedPlugin = plugin;
  59444. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, progressHandler).then(function (result) {
  59445. scene.loadingPluginName = plugin.name;
  59446. successHandler(result.meshes, result.particleSystems, result.skeletons);
  59447. }).catch(function (error) {
  59448. errorHandler(error.message, error);
  59449. });
  59450. }
  59451. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  59452. };
  59453. /**
  59454. * Import meshes into a scene
  59455. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  59456. * @param rootUrl a string that defines the root url for scene and resources
  59457. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  59458. * @param scene the instance of BABYLON.Scene to append to
  59459. * @param onProgress a callback with a progress event for each file being loaded
  59460. * @param pluginExtension the extension used to determine the plugin
  59461. * @returns The loaded list of imported meshes, particleSystems, and skeletons
  59462. */
  59463. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  59464. if (onProgress === void 0) { onProgress = null; }
  59465. if (pluginExtension === void 0) { pluginExtension = null; }
  59466. return new Promise(function (resolve, reject) {
  59467. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  59468. resolve({
  59469. meshes: meshes,
  59470. particleSystems: particleSystems,
  59471. skeletons: skeletons
  59472. });
  59473. }, onProgress, function (scene, message, exception) {
  59474. reject(exception || new Error(message));
  59475. });
  59476. });
  59477. };
  59478. /**
  59479. * Load a scene
  59480. * @param rootUrl a string that defines the root url for scene and resources
  59481. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  59482. * @param engine is the instance of BABYLON.Engine to use to create the scene
  59483. * @param onSuccess a callback with the scene when import succeeds
  59484. * @param onProgress a callback with a progress event for each file being loaded
  59485. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  59486. * @param pluginExtension the extension used to determine the plugin
  59487. * @returns The loaded plugin
  59488. */
  59489. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  59490. if (onSuccess === void 0) { onSuccess = null; }
  59491. if (onProgress === void 0) { onProgress = null; }
  59492. if (onError === void 0) { onError = null; }
  59493. if (pluginExtension === void 0) { pluginExtension = null; }
  59494. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  59495. };
  59496. /**
  59497. * Load a scene
  59498. * @param rootUrl a string that defines the root url for scene and resources
  59499. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  59500. * @param engine is the instance of BABYLON.Engine to use to create the scene
  59501. * @param onProgress a callback with a progress event for each file being loaded
  59502. * @param pluginExtension the extension used to determine the plugin
  59503. * @returns The loaded scene
  59504. */
  59505. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  59506. if (onProgress === void 0) { onProgress = null; }
  59507. if (pluginExtension === void 0) { pluginExtension = null; }
  59508. return new Promise(function (resolve, reject) {
  59509. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  59510. resolve(scene);
  59511. }, onProgress, function (scene, message, exception) {
  59512. reject(exception || new Error(message));
  59513. }, pluginExtension);
  59514. });
  59515. };
  59516. /**
  59517. * Append a scene
  59518. * @param rootUrl a string that defines the root url for scene and resources
  59519. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  59520. * @param scene is the instance of BABYLON.Scene to append to
  59521. * @param onSuccess a callback with the scene when import succeeds
  59522. * @param onProgress a callback with a progress event for each file being loaded
  59523. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  59524. * @param pluginExtension the extension used to determine the plugin
  59525. * @returns The loaded plugin
  59526. */
  59527. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  59528. if (onSuccess === void 0) { onSuccess = null; }
  59529. if (onProgress === void 0) { onProgress = null; }
  59530. if (onError === void 0) { onError = null; }
  59531. if (pluginExtension === void 0) { pluginExtension = null; }
  59532. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  59533. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  59534. return null;
  59535. }
  59536. if (SceneLoader.ShowLoadingScreen) {
  59537. scene.getEngine().displayLoadingUI();
  59538. }
  59539. var loadingToken = {};
  59540. scene._addPendingData(loadingToken);
  59541. var disposeHandler = function () {
  59542. scene._removePendingData(loadingToken);
  59543. scene.getEngine().hideLoadingUI();
  59544. };
  59545. var errorHandler = function (message, exception) {
  59546. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  59547. if (onError) {
  59548. onError(scene, errorMessage, exception);
  59549. }
  59550. else {
  59551. BABYLON.Tools.Error(errorMessage);
  59552. // should the exception be thrown?
  59553. }
  59554. disposeHandler();
  59555. };
  59556. var progressHandler = onProgress ? function (event) {
  59557. try {
  59558. onProgress(event);
  59559. }
  59560. catch (e) {
  59561. errorHandler("Error in onProgress callback", e);
  59562. }
  59563. } : undefined;
  59564. var successHandler = function () {
  59565. if (onSuccess) {
  59566. try {
  59567. onSuccess(scene);
  59568. }
  59569. catch (e) {
  59570. errorHandler("Error in onSuccess callback", e);
  59571. }
  59572. }
  59573. scene._removePendingData(loadingToken);
  59574. };
  59575. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  59576. if (sceneFilename === "") {
  59577. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  59578. }
  59579. if (plugin.load) {
  59580. var syncedPlugin = plugin;
  59581. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  59582. return;
  59583. }
  59584. scene.loadingPluginName = plugin.name;
  59585. successHandler();
  59586. }
  59587. else {
  59588. var asyncedPlugin = plugin;
  59589. asyncedPlugin.loadAsync(scene, data, rootUrl, progressHandler).then(function () {
  59590. scene.loadingPluginName = plugin.name;
  59591. successHandler();
  59592. }).catch(function (error) {
  59593. errorHandler(error.message, error);
  59594. });
  59595. }
  59596. if (SceneLoader.ShowLoadingScreen) {
  59597. scene.executeWhenReady(function () {
  59598. scene.getEngine().hideLoadingUI();
  59599. });
  59600. }
  59601. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  59602. };
  59603. /**
  59604. * Append a scene
  59605. * @param rootUrl a string that defines the root url for scene and resources
  59606. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  59607. * @param scene is the instance of BABYLON.Scene to append to
  59608. * @param onProgress a callback with a progress event for each file being loaded
  59609. * @param pluginExtension the extension used to determine the plugin
  59610. * @returns The given scene
  59611. */
  59612. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  59613. if (onProgress === void 0) { onProgress = null; }
  59614. if (pluginExtension === void 0) { pluginExtension = null; }
  59615. return new Promise(function (resolve, reject) {
  59616. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  59617. resolve(scene);
  59618. }, onProgress, function (scene, message, exception) {
  59619. reject(exception || new Error(message));
  59620. }, pluginExtension);
  59621. });
  59622. };
  59623. /**
  59624. * Load a scene into an asset container
  59625. * @param rootUrl a string that defines the root url for scene and resources
  59626. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  59627. * @param scene is the instance of BABYLON.Scene to append to
  59628. * @param onSuccess a callback with the scene when import succeeds
  59629. * @param onProgress a callback with a progress event for each file being loaded
  59630. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  59631. * @param pluginExtension the extension used to determine the plugin
  59632. * @returns The loaded plugin
  59633. */
  59634. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  59635. if (onSuccess === void 0) { onSuccess = null; }
  59636. if (onProgress === void 0) { onProgress = null; }
  59637. if (onError === void 0) { onError = null; }
  59638. if (pluginExtension === void 0) { pluginExtension = null; }
  59639. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  59640. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  59641. return null;
  59642. }
  59643. var loadingToken = {};
  59644. scene._addPendingData(loadingToken);
  59645. var disposeHandler = function () {
  59646. scene._removePendingData(loadingToken);
  59647. };
  59648. var errorHandler = function (message, exception) {
  59649. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  59650. if (onError) {
  59651. onError(scene, errorMessage, exception);
  59652. }
  59653. else {
  59654. BABYLON.Tools.Error(errorMessage);
  59655. // should the exception be thrown?
  59656. }
  59657. disposeHandler();
  59658. };
  59659. var progressHandler = onProgress ? function (event) {
  59660. try {
  59661. onProgress(event);
  59662. }
  59663. catch (e) {
  59664. errorHandler("Error in onProgress callback", e);
  59665. }
  59666. } : undefined;
  59667. var successHandler = function (assets) {
  59668. if (onSuccess) {
  59669. try {
  59670. onSuccess(assets);
  59671. }
  59672. catch (e) {
  59673. errorHandler("Error in onSuccess callback", e);
  59674. }
  59675. }
  59676. scene._removePendingData(loadingToken);
  59677. };
  59678. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  59679. if (plugin.loadAssetContainer) {
  59680. var syncedPlugin = plugin;
  59681. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, rootUrl, errorHandler);
  59682. if (!assetContainer) {
  59683. return;
  59684. }
  59685. scene.loadingPluginName = plugin.name;
  59686. successHandler(assetContainer);
  59687. }
  59688. else if (plugin.loadAssetContainerAsync) {
  59689. var asyncedPlugin = plugin;
  59690. asyncedPlugin.loadAssetContainerAsync(scene, data, rootUrl, progressHandler).then(function (assetContainer) {
  59691. scene.loadingPluginName = plugin.name;
  59692. successHandler(assetContainer);
  59693. }).catch(function (error) {
  59694. errorHandler(error.message, error);
  59695. });
  59696. }
  59697. else {
  59698. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  59699. }
  59700. if (SceneLoader.ShowLoadingScreen) {
  59701. scene.executeWhenReady(function () {
  59702. scene.getEngine().hideLoadingUI();
  59703. });
  59704. }
  59705. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  59706. };
  59707. /**
  59708. * Load a scene into an asset container
  59709. * @param rootUrl a string that defines the root url for scene and resources
  59710. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  59711. * @param scene is the instance of BABYLON.Scene to append to
  59712. * @param onProgress a callback with a progress event for each file being loaded
  59713. * @param pluginExtension the extension used to determine the plugin
  59714. * @returns The loaded asset container
  59715. */
  59716. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  59717. if (onProgress === void 0) { onProgress = null; }
  59718. if (pluginExtension === void 0) { pluginExtension = null; }
  59719. return new Promise(function (resolve, reject) {
  59720. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  59721. resolve(assetContainer);
  59722. }, onProgress, function (scene, message, exception) {
  59723. reject(exception || new Error(message));
  59724. }, pluginExtension);
  59725. });
  59726. };
  59727. // Flags
  59728. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  59729. SceneLoader._ShowLoadingScreen = true;
  59730. SceneLoader._CleanBoneMatrixWeights = false;
  59731. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  59732. // Members
  59733. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  59734. SceneLoader._registeredPlugins = {};
  59735. return SceneLoader;
  59736. }());
  59737. BABYLON.SceneLoader = SceneLoader;
  59738. ;
  59739. })(BABYLON || (BABYLON = {}));
  59740. //# sourceMappingURL=babylon.sceneLoader.js.map
  59741. var BABYLON;
  59742. (function (BABYLON) {
  59743. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  59744. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  59745. var parsedMaterial = parsedData.materials[index];
  59746. if (parsedMaterial.id === id) {
  59747. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  59748. }
  59749. }
  59750. return null;
  59751. };
  59752. var isDescendantOf = function (mesh, names, hierarchyIds) {
  59753. for (var i in names) {
  59754. if (mesh.name === names[i]) {
  59755. hierarchyIds.push(mesh.id);
  59756. return true;
  59757. }
  59758. }
  59759. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  59760. hierarchyIds.push(mesh.id);
  59761. return true;
  59762. }
  59763. return false;
  59764. };
  59765. var logOperation = function (operation, producer) {
  59766. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  59767. };
  59768. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  59769. if (addToScene === void 0) { addToScene = false; }
  59770. var container = new BABYLON.AssetContainer(scene);
  59771. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  59772. // when SceneLoader.debugLogging = true (default), or exception encountered.
  59773. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  59774. // and avoid problems with multiple concurrent .babylon loads.
  59775. var log = "importScene has failed JSON parse";
  59776. try {
  59777. var parsedData = JSON.parse(data);
  59778. log = "";
  59779. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  59780. var index;
  59781. var cache;
  59782. // Lights
  59783. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  59784. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  59785. var parsedLight = parsedData.lights[index];
  59786. var light = BABYLON.Light.Parse(parsedLight, scene);
  59787. if (light) {
  59788. container.lights.push(light);
  59789. log += (index === 0 ? "\n\tLights:" : "");
  59790. log += "\n\t\t" + light.toString(fullDetails);
  59791. }
  59792. }
  59793. }
  59794. // Animations
  59795. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  59796. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  59797. var parsedAnimation = parsedData.animations[index];
  59798. var animation = BABYLON.Animation.Parse(parsedAnimation);
  59799. scene.animations.push(animation);
  59800. container.animations.push(animation);
  59801. log += (index === 0 ? "\n\tAnimations:" : "");
  59802. log += "\n\t\t" + animation.toString(fullDetails);
  59803. }
  59804. }
  59805. // Materials
  59806. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  59807. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  59808. var parsedMaterial = parsedData.materials[index];
  59809. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  59810. container.materials.push(mat);
  59811. log += (index === 0 ? "\n\tMaterials:" : "");
  59812. log += "\n\t\t" + mat.toString(fullDetails);
  59813. }
  59814. }
  59815. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  59816. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  59817. var parsedMultiMaterial = parsedData.multiMaterials[index];
  59818. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  59819. container.multiMaterials.push(mmat);
  59820. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  59821. log += "\n\t\t" + mmat.toString(fullDetails);
  59822. }
  59823. }
  59824. // Morph targets
  59825. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  59826. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  59827. var managerData = _a[_i];
  59828. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  59829. }
  59830. }
  59831. // Skeletons
  59832. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  59833. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  59834. var parsedSkeleton = parsedData.skeletons[index];
  59835. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  59836. container.skeletons.push(skeleton);
  59837. log += (index === 0 ? "\n\tSkeletons:" : "");
  59838. log += "\n\t\t" + skeleton.toString(fullDetails);
  59839. }
  59840. }
  59841. // Geometries
  59842. var geometries = parsedData.geometries;
  59843. if (geometries !== undefined && geometries !== null) {
  59844. var addedGeometry = new Array();
  59845. // Boxes
  59846. var boxes = geometries.boxes;
  59847. if (boxes !== undefined && boxes !== null) {
  59848. for (index = 0, cache = boxes.length; index < cache; index++) {
  59849. var parsedBox = boxes[index];
  59850. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  59851. }
  59852. }
  59853. // Spheres
  59854. var spheres = geometries.spheres;
  59855. if (spheres !== undefined && spheres !== null) {
  59856. for (index = 0, cache = spheres.length; index < cache; index++) {
  59857. var parsedSphere = spheres[index];
  59858. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  59859. }
  59860. }
  59861. // Cylinders
  59862. var cylinders = geometries.cylinders;
  59863. if (cylinders !== undefined && cylinders !== null) {
  59864. for (index = 0, cache = cylinders.length; index < cache; index++) {
  59865. var parsedCylinder = cylinders[index];
  59866. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  59867. }
  59868. }
  59869. // Toruses
  59870. var toruses = geometries.toruses;
  59871. if (toruses !== undefined && toruses !== null) {
  59872. for (index = 0, cache = toruses.length; index < cache; index++) {
  59873. var parsedTorus = toruses[index];
  59874. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  59875. }
  59876. }
  59877. // Grounds
  59878. var grounds = geometries.grounds;
  59879. if (grounds !== undefined && grounds !== null) {
  59880. for (index = 0, cache = grounds.length; index < cache; index++) {
  59881. var parsedGround = grounds[index];
  59882. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  59883. }
  59884. }
  59885. // Planes
  59886. var planes = geometries.planes;
  59887. if (planes !== undefined && planes !== null) {
  59888. for (index = 0, cache = planes.length; index < cache; index++) {
  59889. var parsedPlane = planes[index];
  59890. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  59891. }
  59892. }
  59893. // TorusKnots
  59894. var torusKnots = geometries.torusKnots;
  59895. if (torusKnots !== undefined && torusKnots !== null) {
  59896. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  59897. var parsedTorusKnot = torusKnots[index];
  59898. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  59899. }
  59900. }
  59901. // VertexData
  59902. var vertexData = geometries.vertexData;
  59903. if (vertexData !== undefined && vertexData !== null) {
  59904. for (index = 0, cache = vertexData.length; index < cache; index++) {
  59905. var parsedVertexData = vertexData[index];
  59906. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  59907. }
  59908. }
  59909. addedGeometry.forEach(function (g) {
  59910. if (g) {
  59911. container.geometries.push(g);
  59912. }
  59913. });
  59914. }
  59915. // Transform nodes
  59916. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  59917. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  59918. var parsedTransformNode = parsedData.transformNodes[index];
  59919. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  59920. container.transformNodes.push(node);
  59921. }
  59922. }
  59923. // Meshes
  59924. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  59925. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  59926. var parsedMesh = parsedData.meshes[index];
  59927. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  59928. container.meshes.push(mesh);
  59929. log += (index === 0 ? "\n\tMeshes:" : "");
  59930. log += "\n\t\t" + mesh.toString(fullDetails);
  59931. }
  59932. }
  59933. // Cameras
  59934. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  59935. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  59936. var parsedCamera = parsedData.cameras[index];
  59937. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  59938. container.cameras.push(camera);
  59939. log += (index === 0 ? "\n\tCameras:" : "");
  59940. log += "\n\t\t" + camera.toString(fullDetails);
  59941. }
  59942. }
  59943. // Browsing all the graph to connect the dots
  59944. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  59945. var camera = scene.cameras[index];
  59946. if (camera._waitingParentId) {
  59947. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  59948. camera._waitingParentId = null;
  59949. }
  59950. }
  59951. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  59952. var light_1 = scene.lights[index];
  59953. if (light_1 && light_1._waitingParentId) {
  59954. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  59955. light_1._waitingParentId = null;
  59956. }
  59957. }
  59958. // Sounds
  59959. // TODO: add sound
  59960. var loadedSounds = [];
  59961. var loadedSound;
  59962. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  59963. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  59964. var parsedSound = parsedData.sounds[index];
  59965. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  59966. if (!parsedSound.url)
  59967. parsedSound.url = parsedSound.name;
  59968. if (!loadedSounds[parsedSound.url]) {
  59969. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  59970. loadedSounds[parsedSound.url] = loadedSound;
  59971. container.sounds.push(loadedSound);
  59972. }
  59973. else {
  59974. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  59975. }
  59976. }
  59977. else {
  59978. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  59979. }
  59980. }
  59981. }
  59982. loadedSounds = [];
  59983. // Connect parents & children and parse actions
  59984. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  59985. var transformNode = scene.transformNodes[index];
  59986. if (transformNode._waitingParentId) {
  59987. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  59988. transformNode._waitingParentId = null;
  59989. }
  59990. }
  59991. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  59992. var mesh = scene.meshes[index];
  59993. if (mesh._waitingParentId) {
  59994. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  59995. mesh._waitingParentId = null;
  59996. }
  59997. if (mesh._waitingActions) {
  59998. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  59999. mesh._waitingActions = null;
  60000. }
  60001. }
  60002. // freeze world matrix application
  60003. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  60004. var currentMesh = scene.meshes[index];
  60005. if (currentMesh._waitingFreezeWorldMatrix) {
  60006. currentMesh.freezeWorldMatrix();
  60007. currentMesh._waitingFreezeWorldMatrix = null;
  60008. }
  60009. else {
  60010. currentMesh.computeWorldMatrix(true);
  60011. }
  60012. }
  60013. // Particles Systems
  60014. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  60015. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  60016. var parsedParticleSystem = parsedData.particleSystems[index];
  60017. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  60018. container.particleSystems.push(ps);
  60019. }
  60020. }
  60021. // Lens flares
  60022. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  60023. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  60024. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  60025. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  60026. container.lensFlareSystems.push(lf);
  60027. }
  60028. }
  60029. // Shadows
  60030. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  60031. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  60032. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  60033. var sg = BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  60034. container.shadowGenerators.push(sg);
  60035. }
  60036. }
  60037. // Lights exclusions / inclusions
  60038. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  60039. var light_2 = scene.lights[index];
  60040. // Excluded check
  60041. if (light_2._excludedMeshesIds.length > 0) {
  60042. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  60043. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  60044. if (excludedMesh) {
  60045. light_2.excludedMeshes.push(excludedMesh);
  60046. }
  60047. }
  60048. light_2._excludedMeshesIds = [];
  60049. }
  60050. // Included check
  60051. if (light_2._includedOnlyMeshesIds.length > 0) {
  60052. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  60053. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  60054. if (includedOnlyMesh) {
  60055. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  60056. }
  60057. }
  60058. light_2._includedOnlyMeshesIds = [];
  60059. }
  60060. }
  60061. // Actions (scene)
  60062. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  60063. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  60064. }
  60065. if (!addToScene) {
  60066. container.removeAllFromScene();
  60067. }
  60068. }
  60069. catch (err) {
  60070. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  60071. if (onError) {
  60072. onError(msg, err);
  60073. }
  60074. else {
  60075. BABYLON.Tools.Log(msg);
  60076. throw err;
  60077. }
  60078. }
  60079. finally {
  60080. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  60081. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  60082. }
  60083. }
  60084. return container;
  60085. };
  60086. BABYLON.SceneLoader.RegisterPlugin({
  60087. name: "babylon.js",
  60088. extensions: ".babylon",
  60089. canDirectLoad: function (data) {
  60090. if (data.indexOf("babylon") !== -1) {
  60091. return true;
  60092. }
  60093. return false;
  60094. },
  60095. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  60096. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  60097. // when SceneLoader.debugLogging = true (default), or exception encountered.
  60098. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  60099. // and avoid problems with multiple concurrent .babylon loads.
  60100. var log = "importMesh has failed JSON parse";
  60101. try {
  60102. var parsedData = JSON.parse(data);
  60103. log = "";
  60104. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  60105. if (!meshesNames) {
  60106. meshesNames = null;
  60107. }
  60108. else if (!Array.isArray(meshesNames)) {
  60109. meshesNames = [meshesNames];
  60110. }
  60111. var hierarchyIds = new Array();
  60112. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  60113. var loadedSkeletonsIds = [];
  60114. var loadedMaterialsIds = [];
  60115. var index;
  60116. var cache;
  60117. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  60118. var parsedMesh = parsedData.meshes[index];
  60119. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  60120. if (meshesNames !== null) {
  60121. // Remove found mesh name from list.
  60122. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  60123. }
  60124. //Geometry?
  60125. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  60126. //does the file contain geometries?
  60127. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  60128. //find the correct geometry and add it to the scene
  60129. var found = false;
  60130. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  60131. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  60132. return;
  60133. }
  60134. else {
  60135. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  60136. if (parsedGeometryData.id === parsedMesh.geometryId) {
  60137. switch (geometryType) {
  60138. case "boxes":
  60139. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  60140. break;
  60141. case "spheres":
  60142. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  60143. break;
  60144. case "cylinders":
  60145. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  60146. break;
  60147. case "toruses":
  60148. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  60149. break;
  60150. case "grounds":
  60151. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  60152. break;
  60153. case "planes":
  60154. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  60155. break;
  60156. case "torusKnots":
  60157. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  60158. break;
  60159. case "vertexData":
  60160. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  60161. break;
  60162. }
  60163. found = true;
  60164. }
  60165. });
  60166. }
  60167. });
  60168. if (found === false) {
  60169. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  60170. }
  60171. }
  60172. }
  60173. // Material ?
  60174. if (parsedMesh.materialId) {
  60175. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  60176. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  60177. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  60178. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  60179. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  60180. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  60181. var subMatId = parsedMultiMaterial.materials[matIndex];
  60182. loadedMaterialsIds.push(subMatId);
  60183. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  60184. if (mat) {
  60185. log += "\n\tMaterial " + mat.toString(fullDetails);
  60186. }
  60187. }
  60188. loadedMaterialsIds.push(parsedMultiMaterial.id);
  60189. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  60190. if (mmat) {
  60191. materialFound = true;
  60192. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  60193. }
  60194. break;
  60195. }
  60196. }
  60197. }
  60198. if (materialFound === false) {
  60199. loadedMaterialsIds.push(parsedMesh.materialId);
  60200. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  60201. if (!mat) {
  60202. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  60203. }
  60204. else {
  60205. log += "\n\tMaterial " + mat.toString(fullDetails);
  60206. }
  60207. }
  60208. }
  60209. // Skeleton ?
  60210. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  60211. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  60212. if (skeletonAlreadyLoaded === false) {
  60213. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  60214. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  60215. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  60216. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  60217. skeletons.push(skeleton);
  60218. loadedSkeletonsIds.push(parsedSkeleton.id);
  60219. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  60220. }
  60221. }
  60222. }
  60223. }
  60224. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  60225. meshes.push(mesh);
  60226. log += "\n\tMesh " + mesh.toString(fullDetails);
  60227. }
  60228. }
  60229. // Connecting parents
  60230. var currentMesh;
  60231. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  60232. currentMesh = scene.meshes[index];
  60233. if (currentMesh._waitingParentId) {
  60234. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  60235. currentMesh._waitingParentId = null;
  60236. }
  60237. }
  60238. // freeze and compute world matrix application
  60239. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  60240. currentMesh = scene.meshes[index];
  60241. if (currentMesh._waitingFreezeWorldMatrix) {
  60242. currentMesh.freezeWorldMatrix();
  60243. currentMesh._waitingFreezeWorldMatrix = null;
  60244. }
  60245. else {
  60246. currentMesh.computeWorldMatrix(true);
  60247. }
  60248. }
  60249. }
  60250. // Particles
  60251. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  60252. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  60253. var parsedParticleSystem = parsedData.particleSystems[index];
  60254. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  60255. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  60256. }
  60257. }
  60258. }
  60259. return true;
  60260. }
  60261. catch (err) {
  60262. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  60263. if (onError) {
  60264. onError(msg, err);
  60265. }
  60266. else {
  60267. BABYLON.Tools.Log(msg);
  60268. throw err;
  60269. }
  60270. }
  60271. finally {
  60272. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  60273. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  60274. }
  60275. }
  60276. return false;
  60277. },
  60278. load: function (scene, data, rootUrl, onError) {
  60279. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  60280. // when SceneLoader.debugLogging = true (default), or exception encountered.
  60281. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  60282. // and avoid problems with multiple concurrent .babylon loads.
  60283. var log = "importScene has failed JSON parse";
  60284. try {
  60285. var parsedData = JSON.parse(data);
  60286. log = "";
  60287. // Scene
  60288. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  60289. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  60290. }
  60291. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  60292. scene.autoClear = parsedData.autoClear;
  60293. }
  60294. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  60295. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  60296. }
  60297. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  60298. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  60299. }
  60300. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  60301. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  60302. }
  60303. // Fog
  60304. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  60305. scene.fogMode = parsedData.fogMode;
  60306. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  60307. scene.fogStart = parsedData.fogStart;
  60308. scene.fogEnd = parsedData.fogEnd;
  60309. scene.fogDensity = parsedData.fogDensity;
  60310. log += "\tFog mode for scene: ";
  60311. switch (scene.fogMode) {
  60312. // getters not compiling, so using hardcoded
  60313. case 1:
  60314. log += "exp\n";
  60315. break;
  60316. case 2:
  60317. log += "exp2\n";
  60318. break;
  60319. case 3:
  60320. log += "linear\n";
  60321. break;
  60322. }
  60323. }
  60324. //Physics
  60325. if (parsedData.physicsEnabled) {
  60326. var physicsPlugin;
  60327. if (parsedData.physicsEngine === "cannon") {
  60328. physicsPlugin = new BABYLON.CannonJSPlugin();
  60329. }
  60330. else if (parsedData.physicsEngine === "oimo") {
  60331. physicsPlugin = new BABYLON.OimoJSPlugin();
  60332. }
  60333. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  60334. //else - default engine, which is currently oimo
  60335. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  60336. scene.enablePhysics(physicsGravity, physicsPlugin);
  60337. }
  60338. // Metadata
  60339. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  60340. scene.metadata = parsedData.metadata;
  60341. }
  60342. //collisions, if defined. otherwise, default is true
  60343. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  60344. scene.collisionsEnabled = parsedData.collisionsEnabled;
  60345. }
  60346. scene.workerCollisions = !!parsedData.workerCollisions;
  60347. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  60348. if (!container) {
  60349. return false;
  60350. }
  60351. if (parsedData.autoAnimate) {
  60352. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  60353. }
  60354. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  60355. scene.setActiveCameraByID(parsedData.activeCameraID);
  60356. }
  60357. // Environment texture
  60358. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  60359. scene.environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  60360. if (parsedData.createDefaultSkybox === true) {
  60361. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  60362. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  60363. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  60364. }
  60365. }
  60366. // Finish
  60367. return true;
  60368. }
  60369. catch (err) {
  60370. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  60371. if (onError) {
  60372. onError(msg, err);
  60373. }
  60374. else {
  60375. BABYLON.Tools.Log(msg);
  60376. throw err;
  60377. }
  60378. }
  60379. finally {
  60380. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  60381. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  60382. }
  60383. }
  60384. return false;
  60385. },
  60386. loadAssetContainer: function (scene, data, rootUrl, onError) {
  60387. var container = loadAssetContainer(scene, data, rootUrl, onError);
  60388. return container;
  60389. }
  60390. });
  60391. })(BABYLON || (BABYLON = {}));
  60392. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  60393. var BABYLON;
  60394. (function (BABYLON) {
  60395. var FilesInput = /** @class */ (function () {
  60396. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  60397. this.onProcessFileCallback = function () { return true; };
  60398. this._engine = engine;
  60399. this._currentScene = scene;
  60400. this._sceneLoadedCallback = sceneLoadedCallback;
  60401. this._progressCallback = progressCallback;
  60402. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  60403. this._textureLoadingCallback = textureLoadingCallback;
  60404. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  60405. this._onReloadCallback = onReloadCallback;
  60406. this._errorCallback = errorCallback;
  60407. }
  60408. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  60409. var _this = this;
  60410. if (elementToMonitor) {
  60411. this._elementToMonitor = elementToMonitor;
  60412. this._dragEnterHandler = function (e) { _this.drag(e); };
  60413. this._dragOverHandler = function (e) { _this.drag(e); };
  60414. this._dropHandler = function (e) { _this.drop(e); };
  60415. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  60416. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  60417. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  60418. }
  60419. };
  60420. FilesInput.prototype.dispose = function () {
  60421. if (!this._elementToMonitor) {
  60422. return;
  60423. }
  60424. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  60425. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  60426. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  60427. };
  60428. FilesInput.prototype.renderFunction = function () {
  60429. if (this._additionalRenderLoopLogicCallback) {
  60430. this._additionalRenderLoopLogicCallback();
  60431. }
  60432. if (this._currentScene) {
  60433. if (this._textureLoadingCallback) {
  60434. var remaining = this._currentScene.getWaitingItemsCount();
  60435. if (remaining > 0) {
  60436. this._textureLoadingCallback(remaining);
  60437. }
  60438. }
  60439. this._currentScene.render();
  60440. }
  60441. };
  60442. FilesInput.prototype.drag = function (e) {
  60443. e.stopPropagation();
  60444. e.preventDefault();
  60445. };
  60446. FilesInput.prototype.drop = function (eventDrop) {
  60447. eventDrop.stopPropagation();
  60448. eventDrop.preventDefault();
  60449. this.loadFiles(eventDrop);
  60450. };
  60451. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  60452. var _this = this;
  60453. var reader = folder.createReader();
  60454. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  60455. reader.readEntries(function (entries) {
  60456. remaining.count += entries.length;
  60457. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  60458. var entry = entries_1[_i];
  60459. if (entry.isFile) {
  60460. entry.file(function (file) {
  60461. file.correctName = relativePath + file.name;
  60462. files.push(file);
  60463. if (--remaining.count === 0) {
  60464. callback();
  60465. }
  60466. });
  60467. }
  60468. else if (entry.isDirectory) {
  60469. _this._traverseFolder(entry, files, remaining, callback);
  60470. }
  60471. }
  60472. if (--remaining.count) {
  60473. callback();
  60474. }
  60475. });
  60476. };
  60477. FilesInput.prototype._processFiles = function (files) {
  60478. for (var i = 0; i < files.length; i++) {
  60479. var name = files[i].correctName.toLowerCase();
  60480. var extension = name.split('.').pop();
  60481. if (!this.onProcessFileCallback(files[i], name, extension)) {
  60482. continue;
  60483. }
  60484. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  60485. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  60486. this._sceneFileToLoad = files[i];
  60487. }
  60488. else {
  60489. FilesInput.FilesToLoad[name] = files[i];
  60490. }
  60491. }
  60492. };
  60493. FilesInput.prototype.loadFiles = function (event) {
  60494. var _this = this;
  60495. if (this._startingProcessingFilesCallback)
  60496. this._startingProcessingFilesCallback();
  60497. // Handling data transfer via drag'n'drop
  60498. if (event && event.dataTransfer && event.dataTransfer.files) {
  60499. this._filesToLoad = event.dataTransfer.files;
  60500. }
  60501. // Handling files from input files
  60502. if (event && event.target && event.target.files) {
  60503. this._filesToLoad = event.target.files;
  60504. }
  60505. if (this._filesToLoad && this._filesToLoad.length > 0) {
  60506. var files_1 = new Array();
  60507. var folders = [];
  60508. var items = event.dataTransfer ? event.dataTransfer.items : null;
  60509. for (var i = 0; i < this._filesToLoad.length; i++) {
  60510. var fileToLoad = this._filesToLoad[i];
  60511. var name_1 = fileToLoad.name.toLowerCase();
  60512. var entry = void 0;
  60513. fileToLoad.correctName = name_1;
  60514. if (items) {
  60515. var item = items[i];
  60516. if (item.getAsEntry) {
  60517. entry = item.getAsEntry();
  60518. }
  60519. else if (item.webkitGetAsEntry) {
  60520. entry = item.webkitGetAsEntry();
  60521. }
  60522. }
  60523. if (!entry) {
  60524. files_1.push(fileToLoad);
  60525. }
  60526. else {
  60527. if (entry.isDirectory) {
  60528. folders.push(entry);
  60529. }
  60530. else {
  60531. files_1.push(fileToLoad);
  60532. }
  60533. }
  60534. }
  60535. if (folders.length === 0) {
  60536. this._processFiles(files_1);
  60537. this._processReload();
  60538. }
  60539. else {
  60540. var remaining = { count: folders.length };
  60541. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  60542. var folder = folders_1[_i];
  60543. this._traverseFolder(folder, files_1, remaining, function () {
  60544. _this._processFiles(files_1);
  60545. if (remaining.count === 0) {
  60546. _this._processReload();
  60547. }
  60548. });
  60549. }
  60550. }
  60551. }
  60552. };
  60553. FilesInput.prototype._processReload = function () {
  60554. if (this._onReloadCallback) {
  60555. this._onReloadCallback(this._sceneFileToLoad);
  60556. }
  60557. else {
  60558. this.reload();
  60559. }
  60560. };
  60561. FilesInput.prototype.reload = function () {
  60562. var _this = this;
  60563. // If a scene file has been provided
  60564. if (this._sceneFileToLoad) {
  60565. if (this._currentScene) {
  60566. if (BABYLON.Tools.errorsCount > 0) {
  60567. BABYLON.Tools.ClearLogCache();
  60568. }
  60569. this._engine.stopRenderLoop();
  60570. this._currentScene.dispose();
  60571. }
  60572. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad, this._engine, function (progress) {
  60573. if (_this._progressCallback) {
  60574. _this._progressCallback(progress);
  60575. }
  60576. }).then(function (scene) {
  60577. _this._currentScene = scene;
  60578. if (_this._sceneLoadedCallback) {
  60579. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  60580. }
  60581. // Wait for textures and shaders to be ready
  60582. _this._currentScene.executeWhenReady(function () {
  60583. _this._engine.runRenderLoop(function () {
  60584. _this.renderFunction();
  60585. });
  60586. });
  60587. }).catch(function (error) {
  60588. if (_this._errorCallback) {
  60589. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  60590. }
  60591. });
  60592. }
  60593. else {
  60594. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  60595. }
  60596. };
  60597. FilesInput.FilesToLoad = {};
  60598. return FilesInput;
  60599. }());
  60600. BABYLON.FilesInput = FilesInput;
  60601. })(BABYLON || (BABYLON = {}));
  60602. //# sourceMappingURL=babylon.filesInput.js.map
  60603. var BABYLON;
  60604. (function (BABYLON) {
  60605. /**
  60606. * This class implement a typical dictionary using a string as key and the generic type T as value.
  60607. * The underlying implementation relies on an associative array to ensure the best performances.
  60608. * The value can be anything including 'null' but except 'undefined'
  60609. */
  60610. var StringDictionary = /** @class */ (function () {
  60611. function StringDictionary() {
  60612. this._count = 0;
  60613. this._data = {};
  60614. }
  60615. /**
  60616. * This will clear this dictionary and copy the content from the 'source' one.
  60617. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  60618. * @param source the dictionary to take the content from and copy to this dictionary
  60619. */
  60620. StringDictionary.prototype.copyFrom = function (source) {
  60621. var _this = this;
  60622. this.clear();
  60623. source.forEach(function (t, v) { return _this.add(t, v); });
  60624. };
  60625. /**
  60626. * Get a value based from its key
  60627. * @param key the given key to get the matching value from
  60628. * @return the value if found, otherwise undefined is returned
  60629. */
  60630. StringDictionary.prototype.get = function (key) {
  60631. var val = this._data[key];
  60632. if (val !== undefined) {
  60633. return val;
  60634. }
  60635. return undefined;
  60636. };
  60637. /**
  60638. * Get a value from its key or add it if it doesn't exist.
  60639. * This method will ensure you that a given key/data will be present in the dictionary.
  60640. * @param key the given key to get the matching value from
  60641. * @param factory the factory that will create the value if the key is not present in the dictionary.
  60642. * The factory will only be invoked if there's no data for the given key.
  60643. * @return the value corresponding to the key.
  60644. */
  60645. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  60646. var val = this.get(key);
  60647. if (val !== undefined) {
  60648. return val;
  60649. }
  60650. val = factory(key);
  60651. if (val) {
  60652. this.add(key, val);
  60653. }
  60654. return val;
  60655. };
  60656. /**
  60657. * Get a value from its key if present in the dictionary otherwise add it
  60658. * @param key the key to get the value from
  60659. * @param val if there's no such key/value pair in the dictionary add it with this value
  60660. * @return the value corresponding to the key
  60661. */
  60662. StringDictionary.prototype.getOrAdd = function (key, val) {
  60663. var curVal = this.get(key);
  60664. if (curVal !== undefined) {
  60665. return curVal;
  60666. }
  60667. this.add(key, val);
  60668. return val;
  60669. };
  60670. /**
  60671. * Check if there's a given key in the dictionary
  60672. * @param key the key to check for
  60673. * @return true if the key is present, false otherwise
  60674. */
  60675. StringDictionary.prototype.contains = function (key) {
  60676. return this._data[key] !== undefined;
  60677. };
  60678. /**
  60679. * Add a new key and its corresponding value
  60680. * @param key the key to add
  60681. * @param value the value corresponding to the key
  60682. * @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
  60683. */
  60684. StringDictionary.prototype.add = function (key, value) {
  60685. if (this._data[key] !== undefined) {
  60686. return false;
  60687. }
  60688. this._data[key] = value;
  60689. ++this._count;
  60690. return true;
  60691. };
  60692. StringDictionary.prototype.set = function (key, value) {
  60693. if (this._data[key] === undefined) {
  60694. return false;
  60695. }
  60696. this._data[key] = value;
  60697. return true;
  60698. };
  60699. /**
  60700. * Get the element of the given key and remove it from the dictionary
  60701. * @param key
  60702. */
  60703. StringDictionary.prototype.getAndRemove = function (key) {
  60704. var val = this.get(key);
  60705. if (val !== undefined) {
  60706. delete this._data[key];
  60707. --this._count;
  60708. return val;
  60709. }
  60710. return null;
  60711. };
  60712. /**
  60713. * Remove a key/value from the dictionary.
  60714. * @param key the key to remove
  60715. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  60716. */
  60717. StringDictionary.prototype.remove = function (key) {
  60718. if (this.contains(key)) {
  60719. delete this._data[key];
  60720. --this._count;
  60721. return true;
  60722. }
  60723. return false;
  60724. };
  60725. /**
  60726. * Clear the whole content of the dictionary
  60727. */
  60728. StringDictionary.prototype.clear = function () {
  60729. this._data = {};
  60730. this._count = 0;
  60731. };
  60732. Object.defineProperty(StringDictionary.prototype, "count", {
  60733. get: function () {
  60734. return this._count;
  60735. },
  60736. enumerable: true,
  60737. configurable: true
  60738. });
  60739. /**
  60740. * Execute a callback on each key/val of the dictionary.
  60741. * Note that you can remove any element in this dictionary in the callback implementation
  60742. * @param callback the callback to execute on a given key/value pair
  60743. */
  60744. StringDictionary.prototype.forEach = function (callback) {
  60745. for (var cur in this._data) {
  60746. var val = this._data[cur];
  60747. callback(cur, val);
  60748. }
  60749. };
  60750. /**
  60751. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  60752. * If the callback returns null or undefined the method will iterate to the next key/value pair
  60753. * Note that you can remove any element in this dictionary in the callback implementation
  60754. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  60755. */
  60756. StringDictionary.prototype.first = function (callback) {
  60757. for (var cur in this._data) {
  60758. var val = this._data[cur];
  60759. var res = callback(cur, val);
  60760. if (res) {
  60761. return res;
  60762. }
  60763. }
  60764. return null;
  60765. };
  60766. return StringDictionary;
  60767. }());
  60768. BABYLON.StringDictionary = StringDictionary;
  60769. })(BABYLON || (BABYLON = {}));
  60770. //# sourceMappingURL=babylon.stringDictionary.js.map
  60771. var BABYLON;
  60772. (function (BABYLON) {
  60773. var Tags = /** @class */ (function () {
  60774. function Tags() {
  60775. }
  60776. Tags.EnableFor = function (obj) {
  60777. obj._tags = obj._tags || {};
  60778. obj.hasTags = function () {
  60779. return Tags.HasTags(obj);
  60780. };
  60781. obj.addTags = function (tagsString) {
  60782. return Tags.AddTagsTo(obj, tagsString);
  60783. };
  60784. obj.removeTags = function (tagsString) {
  60785. return Tags.RemoveTagsFrom(obj, tagsString);
  60786. };
  60787. obj.matchesTagsQuery = function (tagsQuery) {
  60788. return Tags.MatchesQuery(obj, tagsQuery);
  60789. };
  60790. };
  60791. Tags.DisableFor = function (obj) {
  60792. delete obj._tags;
  60793. delete obj.hasTags;
  60794. delete obj.addTags;
  60795. delete obj.removeTags;
  60796. delete obj.matchesTagsQuery;
  60797. };
  60798. Tags.HasTags = function (obj) {
  60799. if (!obj._tags) {
  60800. return false;
  60801. }
  60802. return !BABYLON.Tools.IsEmpty(obj._tags);
  60803. };
  60804. Tags.GetTags = function (obj, asString) {
  60805. if (asString === void 0) { asString = true; }
  60806. if (!obj._tags) {
  60807. return null;
  60808. }
  60809. if (asString) {
  60810. var tagsArray = [];
  60811. for (var tag in obj._tags) {
  60812. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  60813. tagsArray.push(tag);
  60814. }
  60815. }
  60816. return tagsArray.join(" ");
  60817. }
  60818. else {
  60819. return obj._tags;
  60820. }
  60821. };
  60822. // the tags 'true' and 'false' are reserved and cannot be used as tags
  60823. // a tag cannot start with '||', '&&', and '!'
  60824. // it cannot contain whitespaces
  60825. Tags.AddTagsTo = function (obj, tagsString) {
  60826. if (!tagsString) {
  60827. return;
  60828. }
  60829. if (typeof tagsString !== "string") {
  60830. return;
  60831. }
  60832. var tags = tagsString.split(" ");
  60833. tags.forEach(function (tag, index, array) {
  60834. Tags._AddTagTo(obj, tag);
  60835. });
  60836. };
  60837. Tags._AddTagTo = function (obj, tag) {
  60838. tag = tag.trim();
  60839. if (tag === "" || tag === "true" || tag === "false") {
  60840. return;
  60841. }
  60842. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  60843. return;
  60844. }
  60845. Tags.EnableFor(obj);
  60846. obj._tags[tag] = true;
  60847. };
  60848. Tags.RemoveTagsFrom = function (obj, tagsString) {
  60849. if (!Tags.HasTags(obj)) {
  60850. return;
  60851. }
  60852. var tags = tagsString.split(" ");
  60853. for (var t in tags) {
  60854. Tags._RemoveTagFrom(obj, tags[t]);
  60855. }
  60856. };
  60857. Tags._RemoveTagFrom = function (obj, tag) {
  60858. delete obj._tags[tag];
  60859. };
  60860. Tags.MatchesQuery = function (obj, tagsQuery) {
  60861. if (tagsQuery === undefined) {
  60862. return true;
  60863. }
  60864. if (tagsQuery === "") {
  60865. return Tags.HasTags(obj);
  60866. }
  60867. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  60868. };
  60869. return Tags;
  60870. }());
  60871. BABYLON.Tags = Tags;
  60872. })(BABYLON || (BABYLON = {}));
  60873. //# sourceMappingURL=babylon.tags.js.map
  60874. var BABYLON;
  60875. (function (BABYLON) {
  60876. var AndOrNotEvaluator = /** @class */ (function () {
  60877. function AndOrNotEvaluator() {
  60878. }
  60879. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  60880. if (!query.match(/\([^\(\)]*\)/g)) {
  60881. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  60882. }
  60883. else {
  60884. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  60885. // remove parenthesis
  60886. r = r.slice(1, r.length - 1);
  60887. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  60888. });
  60889. }
  60890. if (query === "true") {
  60891. return true;
  60892. }
  60893. if (query === "false") {
  60894. return false;
  60895. }
  60896. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  60897. };
  60898. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  60899. evaluateCallback = evaluateCallback || (function (r) {
  60900. return r === "true" ? true : false;
  60901. });
  60902. var result;
  60903. var or = parenthesisContent.split("||");
  60904. for (var i in or) {
  60905. if (or.hasOwnProperty(i)) {
  60906. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  60907. var and = ori.split("&&");
  60908. if (and.length > 1) {
  60909. for (var j = 0; j < and.length; ++j) {
  60910. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  60911. if (andj !== "true" && andj !== "false") {
  60912. if (andj[0] === "!") {
  60913. result = !evaluateCallback(andj.substring(1));
  60914. }
  60915. else {
  60916. result = evaluateCallback(andj);
  60917. }
  60918. }
  60919. else {
  60920. result = andj === "true" ? true : false;
  60921. }
  60922. if (!result) {
  60923. ori = "false";
  60924. break;
  60925. }
  60926. }
  60927. }
  60928. if (result || ori === "true") {
  60929. result = true;
  60930. break;
  60931. }
  60932. // result equals false (or undefined)
  60933. if (ori !== "true" && ori !== "false") {
  60934. if (ori[0] === "!") {
  60935. result = !evaluateCallback(ori.substring(1));
  60936. }
  60937. else {
  60938. result = evaluateCallback(ori);
  60939. }
  60940. }
  60941. else {
  60942. result = ori === "true" ? true : false;
  60943. }
  60944. }
  60945. }
  60946. // the whole parenthesis scope is replaced by 'true' or 'false'
  60947. return result ? "true" : "false";
  60948. };
  60949. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  60950. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  60951. // remove whitespaces
  60952. r = r.replace(/[\s]/g, function () { return ""; });
  60953. return r.length % 2 ? "!" : "";
  60954. });
  60955. booleanString = booleanString.trim();
  60956. if (booleanString === "!true") {
  60957. booleanString = "false";
  60958. }
  60959. else if (booleanString === "!false") {
  60960. booleanString = "true";
  60961. }
  60962. return booleanString;
  60963. };
  60964. return AndOrNotEvaluator;
  60965. }());
  60966. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  60967. })(BABYLON || (BABYLON = {}));
  60968. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  60969. var BABYLON;
  60970. (function (BABYLON) {
  60971. var Database = /** @class */ (function () {
  60972. function Database(urlToScene, callbackManifestChecked) {
  60973. // Handling various flavors of prefixed version of IndexedDB
  60974. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  60975. this.callbackManifestChecked = callbackManifestChecked;
  60976. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  60977. this.db = null;
  60978. this._enableSceneOffline = false;
  60979. this._enableTexturesOffline = false;
  60980. this.manifestVersionFound = 0;
  60981. this.mustUpdateRessources = false;
  60982. this.hasReachedQuota = false;
  60983. if (!Database.IDBStorageEnabled) {
  60984. this.callbackManifestChecked(true);
  60985. }
  60986. else {
  60987. this.checkManifestFile();
  60988. }
  60989. }
  60990. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  60991. get: function () {
  60992. return this._enableSceneOffline;
  60993. },
  60994. enumerable: true,
  60995. configurable: true
  60996. });
  60997. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  60998. get: function () {
  60999. return this._enableTexturesOffline;
  61000. },
  61001. enumerable: true,
  61002. configurable: true
  61003. });
  61004. Database.prototype.checkManifestFile = function () {
  61005. var _this = this;
  61006. var noManifestFile = function () {
  61007. _this._enableSceneOffline = false;
  61008. _this._enableTexturesOffline = false;
  61009. _this.callbackManifestChecked(false);
  61010. };
  61011. var timeStampUsed = false;
  61012. var manifestURL = this.currentSceneUrl + ".manifest";
  61013. var xhr = new XMLHttpRequest();
  61014. if (navigator.onLine) {
  61015. // Adding a timestamp to by-pass browsers' cache
  61016. timeStampUsed = true;
  61017. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  61018. }
  61019. xhr.open("GET", manifestURL, true);
  61020. xhr.addEventListener("load", function () {
  61021. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  61022. try {
  61023. var manifestFile = JSON.parse(xhr.response);
  61024. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  61025. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  61026. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  61027. _this.manifestVersionFound = manifestFile.version;
  61028. }
  61029. if (_this.callbackManifestChecked) {
  61030. _this.callbackManifestChecked(true);
  61031. }
  61032. }
  61033. catch (ex) {
  61034. noManifestFile();
  61035. }
  61036. }
  61037. else {
  61038. noManifestFile();
  61039. }
  61040. }, false);
  61041. xhr.addEventListener("error", function (event) {
  61042. if (timeStampUsed) {
  61043. timeStampUsed = false;
  61044. // Let's retry without the timeStamp
  61045. // It could fail when coupled with HTML5 Offline API
  61046. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  61047. xhr.open("GET", retryManifestURL, true);
  61048. xhr.send();
  61049. }
  61050. else {
  61051. noManifestFile();
  61052. }
  61053. }, false);
  61054. try {
  61055. xhr.send();
  61056. }
  61057. catch (ex) {
  61058. BABYLON.Tools.Error("Error on XHR send request.");
  61059. this.callbackManifestChecked(false);
  61060. }
  61061. };
  61062. Database.prototype.openAsync = function (successCallback, errorCallback) {
  61063. var _this = this;
  61064. var handleError = function () {
  61065. _this.isSupported = false;
  61066. if (errorCallback)
  61067. errorCallback();
  61068. };
  61069. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  61070. // Your browser doesn't support IndexedDB
  61071. this.isSupported = false;
  61072. if (errorCallback)
  61073. errorCallback();
  61074. }
  61075. else {
  61076. // If the DB hasn't been opened or created yet
  61077. if (!this.db) {
  61078. this.hasReachedQuota = false;
  61079. this.isSupported = true;
  61080. var request = this.idbFactory.open("babylonjs", 1);
  61081. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  61082. request.onerror = function (event) {
  61083. handleError();
  61084. };
  61085. // executes when a version change transaction cannot complete due to other active transactions
  61086. request.onblocked = function (event) {
  61087. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  61088. handleError();
  61089. };
  61090. // DB has been opened successfully
  61091. request.onsuccess = function (event) {
  61092. _this.db = request.result;
  61093. successCallback();
  61094. };
  61095. // Initialization of the DB. Creating Scenes & Textures stores
  61096. request.onupgradeneeded = function (event) {
  61097. _this.db = (event.target).result;
  61098. if (_this.db) {
  61099. try {
  61100. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  61101. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  61102. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  61103. }
  61104. catch (ex) {
  61105. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  61106. handleError();
  61107. }
  61108. }
  61109. };
  61110. }
  61111. else {
  61112. if (successCallback)
  61113. successCallback();
  61114. }
  61115. }
  61116. };
  61117. Database.prototype.loadImageFromDB = function (url, image) {
  61118. var _this = this;
  61119. var completeURL = Database.ReturnFullUrlLocation(url);
  61120. var saveAndLoadImage = function () {
  61121. if (!_this.hasReachedQuota && _this.db !== null) {
  61122. // the texture is not yet in the DB, let's try to save it
  61123. _this._saveImageIntoDBAsync(completeURL, image);
  61124. }
  61125. else {
  61126. image.src = url;
  61127. }
  61128. };
  61129. if (!this.mustUpdateRessources) {
  61130. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  61131. }
  61132. else {
  61133. saveAndLoadImage();
  61134. }
  61135. };
  61136. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  61137. if (this.isSupported && this.db !== null) {
  61138. var texture;
  61139. var transaction = this.db.transaction(["textures"]);
  61140. transaction.onabort = function (event) {
  61141. image.src = url;
  61142. };
  61143. transaction.oncomplete = function (event) {
  61144. var blobTextureURL;
  61145. if (texture) {
  61146. var URL = window.URL || window.webkitURL;
  61147. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  61148. image.onerror = function () {
  61149. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  61150. image.src = url;
  61151. };
  61152. image.src = blobTextureURL;
  61153. }
  61154. else {
  61155. notInDBCallback();
  61156. }
  61157. };
  61158. var getRequest = transaction.objectStore("textures").get(url);
  61159. getRequest.onsuccess = function (event) {
  61160. texture = (event.target).result;
  61161. };
  61162. getRequest.onerror = function (event) {
  61163. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  61164. image.src = url;
  61165. };
  61166. }
  61167. else {
  61168. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  61169. image.src = url;
  61170. }
  61171. };
  61172. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  61173. var _this = this;
  61174. if (this.isSupported) {
  61175. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  61176. var generateBlobUrl = function () {
  61177. var blobTextureURL;
  61178. if (blob) {
  61179. var URL = window.URL || window.webkitURL;
  61180. try {
  61181. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  61182. }
  61183. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  61184. catch (ex) {
  61185. blobTextureURL = URL.createObjectURL(blob);
  61186. }
  61187. }
  61188. if (blobTextureURL) {
  61189. image.src = blobTextureURL;
  61190. }
  61191. };
  61192. if (Database.IsUASupportingBlobStorage) {
  61193. var xhr = new XMLHttpRequest(), blob;
  61194. xhr.open("GET", url, true);
  61195. xhr.responseType = "blob";
  61196. xhr.addEventListener("load", function () {
  61197. if (xhr.status === 200 && _this.db) {
  61198. // Blob as response (XHR2)
  61199. blob = xhr.response;
  61200. var transaction = _this.db.transaction(["textures"], "readwrite");
  61201. // the transaction could abort because of a QuotaExceededError error
  61202. transaction.onabort = function (event) {
  61203. try {
  61204. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  61205. var srcElement = (event.srcElement || event.target);
  61206. var error = srcElement.error;
  61207. if (error && error.name === "QuotaExceededError") {
  61208. _this.hasReachedQuota = true;
  61209. }
  61210. }
  61211. catch (ex) { }
  61212. generateBlobUrl();
  61213. };
  61214. transaction.oncomplete = function (event) {
  61215. generateBlobUrl();
  61216. };
  61217. var newTexture = { textureUrl: url, data: blob };
  61218. try {
  61219. // Put the blob into the dabase
  61220. var addRequest = transaction.objectStore("textures").put(newTexture);
  61221. addRequest.onsuccess = function (event) {
  61222. };
  61223. addRequest.onerror = function (event) {
  61224. generateBlobUrl();
  61225. };
  61226. }
  61227. catch (ex) {
  61228. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  61229. if (ex.code === 25) {
  61230. Database.IsUASupportingBlobStorage = false;
  61231. }
  61232. image.src = url;
  61233. }
  61234. }
  61235. else {
  61236. image.src = url;
  61237. }
  61238. }, false);
  61239. xhr.addEventListener("error", function (event) {
  61240. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  61241. image.src = url;
  61242. }, false);
  61243. xhr.send();
  61244. }
  61245. else {
  61246. image.src = url;
  61247. }
  61248. }
  61249. else {
  61250. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  61251. image.src = url;
  61252. }
  61253. };
  61254. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  61255. var _this = this;
  61256. var updateVersion = function () {
  61257. // the version is not yet in the DB or we need to update it
  61258. _this._saveVersionIntoDBAsync(url, versionLoaded);
  61259. };
  61260. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  61261. };
  61262. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  61263. var _this = this;
  61264. if (this.isSupported && this.db) {
  61265. var version;
  61266. try {
  61267. var transaction = this.db.transaction(["versions"]);
  61268. transaction.oncomplete = function (event) {
  61269. if (version) {
  61270. // If the version in the JSON file is > than the version in DB
  61271. if (_this.manifestVersionFound > version.data) {
  61272. _this.mustUpdateRessources = true;
  61273. updateInDBCallback();
  61274. }
  61275. else {
  61276. callback(version.data);
  61277. }
  61278. }
  61279. else {
  61280. _this.mustUpdateRessources = true;
  61281. updateInDBCallback();
  61282. }
  61283. };
  61284. transaction.onabort = function (event) {
  61285. callback(-1);
  61286. };
  61287. var getRequest = transaction.objectStore("versions").get(url);
  61288. getRequest.onsuccess = function (event) {
  61289. version = (event.target).result;
  61290. };
  61291. getRequest.onerror = function (event) {
  61292. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  61293. callback(-1);
  61294. };
  61295. }
  61296. catch (ex) {
  61297. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  61298. callback(-1);
  61299. }
  61300. }
  61301. else {
  61302. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  61303. callback(-1);
  61304. }
  61305. };
  61306. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  61307. var _this = this;
  61308. if (this.isSupported && !this.hasReachedQuota && this.db) {
  61309. try {
  61310. // Open a transaction to the database
  61311. var transaction = this.db.transaction(["versions"], "readwrite");
  61312. // the transaction could abort because of a QuotaExceededError error
  61313. transaction.onabort = function (event) {
  61314. try {
  61315. var error = event.srcElement['error'];
  61316. if (error && error.name === "QuotaExceededError") {
  61317. _this.hasReachedQuota = true;
  61318. }
  61319. }
  61320. catch (ex) { }
  61321. callback(-1);
  61322. };
  61323. transaction.oncomplete = function (event) {
  61324. callback(_this.manifestVersionFound);
  61325. };
  61326. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  61327. // Put the scene into the database
  61328. var addRequest = transaction.objectStore("versions").put(newVersion);
  61329. addRequest.onsuccess = function (event) {
  61330. };
  61331. addRequest.onerror = function (event) {
  61332. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  61333. };
  61334. }
  61335. catch (ex) {
  61336. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  61337. callback(-1);
  61338. }
  61339. }
  61340. else {
  61341. callback(-1);
  61342. }
  61343. };
  61344. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  61345. var _this = this;
  61346. var completeUrl = Database.ReturnFullUrlLocation(url);
  61347. var saveAndLoadFile = function () {
  61348. // the scene is not yet in the DB, let's try to save it
  61349. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  61350. };
  61351. this._checkVersionFromDB(completeUrl, function (version) {
  61352. if (version !== -1) {
  61353. if (!_this.mustUpdateRessources) {
  61354. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  61355. }
  61356. else {
  61357. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  61358. }
  61359. }
  61360. else {
  61361. if (errorCallback) {
  61362. errorCallback();
  61363. }
  61364. }
  61365. });
  61366. };
  61367. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  61368. if (this.isSupported && this.db) {
  61369. var targetStore;
  61370. if (url.indexOf(".babylon") !== -1) {
  61371. targetStore = "scenes";
  61372. }
  61373. else {
  61374. targetStore = "textures";
  61375. }
  61376. var file;
  61377. var transaction = this.db.transaction([targetStore]);
  61378. transaction.oncomplete = function (event) {
  61379. if (file) {
  61380. callback(file.data);
  61381. }
  61382. else {
  61383. notInDBCallback();
  61384. }
  61385. };
  61386. transaction.onabort = function (event) {
  61387. notInDBCallback();
  61388. };
  61389. var getRequest = transaction.objectStore(targetStore).get(url);
  61390. getRequest.onsuccess = function (event) {
  61391. file = (event.target).result;
  61392. };
  61393. getRequest.onerror = function (event) {
  61394. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  61395. notInDBCallback();
  61396. };
  61397. }
  61398. else {
  61399. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  61400. callback();
  61401. }
  61402. };
  61403. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  61404. var _this = this;
  61405. if (this.isSupported) {
  61406. var targetStore;
  61407. if (url.indexOf(".babylon") !== -1) {
  61408. targetStore = "scenes";
  61409. }
  61410. else {
  61411. targetStore = "textures";
  61412. }
  61413. // Create XHR
  61414. var xhr = new XMLHttpRequest();
  61415. var fileData;
  61416. xhr.open("GET", url, true);
  61417. if (useArrayBuffer) {
  61418. xhr.responseType = "arraybuffer";
  61419. }
  61420. if (progressCallback) {
  61421. xhr.onprogress = progressCallback;
  61422. }
  61423. xhr.addEventListener("load", function () {
  61424. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  61425. // Blob as response (XHR2)
  61426. //fileData = xhr.responseText;
  61427. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  61428. if (!_this.hasReachedQuota && _this.db) {
  61429. // Open a transaction to the database
  61430. var transaction = _this.db.transaction([targetStore], "readwrite");
  61431. // the transaction could abort because of a QuotaExceededError error
  61432. transaction.onabort = function (event) {
  61433. try {
  61434. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  61435. var error = event.srcElement['error'];
  61436. if (error && error.name === "QuotaExceededError") {
  61437. _this.hasReachedQuota = true;
  61438. }
  61439. }
  61440. catch (ex) { }
  61441. callback(fileData);
  61442. };
  61443. transaction.oncomplete = function (event) {
  61444. callback(fileData);
  61445. };
  61446. var newFile;
  61447. if (targetStore === "scenes") {
  61448. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  61449. }
  61450. else {
  61451. newFile = { textureUrl: url, data: fileData };
  61452. }
  61453. try {
  61454. // Put the scene into the database
  61455. var addRequest = transaction.objectStore(targetStore).put(newFile);
  61456. addRequest.onsuccess = function (event) {
  61457. };
  61458. addRequest.onerror = function (event) {
  61459. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  61460. };
  61461. }
  61462. catch (ex) {
  61463. callback(fileData);
  61464. }
  61465. }
  61466. else {
  61467. callback(fileData);
  61468. }
  61469. }
  61470. else {
  61471. callback();
  61472. }
  61473. }, false);
  61474. xhr.addEventListener("error", function (event) {
  61475. BABYLON.Tools.Error("error on XHR request.");
  61476. callback();
  61477. }, false);
  61478. xhr.send();
  61479. }
  61480. else {
  61481. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  61482. callback();
  61483. }
  61484. };
  61485. Database.IsUASupportingBlobStorage = true;
  61486. Database.IDBStorageEnabled = true;
  61487. Database.parseURL = function (url) {
  61488. var a = document.createElement('a');
  61489. a.href = url;
  61490. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  61491. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  61492. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  61493. return absLocation;
  61494. };
  61495. Database.ReturnFullUrlLocation = function (url) {
  61496. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  61497. return (Database.parseURL(window.location.href) + url);
  61498. }
  61499. else {
  61500. return url;
  61501. }
  61502. };
  61503. return Database;
  61504. }());
  61505. BABYLON.Database = Database;
  61506. })(BABYLON || (BABYLON = {}));
  61507. //# sourceMappingURL=babylon.database.js.map
  61508. var BABYLON;
  61509. (function (BABYLON) {
  61510. var FresnelParameters = /** @class */ (function () {
  61511. function FresnelParameters() {
  61512. this._isEnabled = true;
  61513. this.leftColor = BABYLON.Color3.White();
  61514. this.rightColor = BABYLON.Color3.Black();
  61515. this.bias = 0;
  61516. this.power = 1;
  61517. }
  61518. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  61519. get: function () {
  61520. return this._isEnabled;
  61521. },
  61522. set: function (value) {
  61523. if (this._isEnabled === value) {
  61524. return;
  61525. }
  61526. this._isEnabled = value;
  61527. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  61528. },
  61529. enumerable: true,
  61530. configurable: true
  61531. });
  61532. FresnelParameters.prototype.clone = function () {
  61533. var newFresnelParameters = new FresnelParameters();
  61534. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  61535. return newFresnelParameters;
  61536. };
  61537. FresnelParameters.prototype.serialize = function () {
  61538. var serializationObject = {};
  61539. serializationObject.isEnabled = this.isEnabled;
  61540. serializationObject.leftColor = this.leftColor;
  61541. serializationObject.rightColor = this.rightColor;
  61542. serializationObject.bias = this.bias;
  61543. serializationObject.power = this.power;
  61544. return serializationObject;
  61545. };
  61546. FresnelParameters.Parse = function (parsedFresnelParameters) {
  61547. var fresnelParameters = new FresnelParameters();
  61548. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  61549. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  61550. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  61551. fresnelParameters.bias = parsedFresnelParameters.bias;
  61552. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  61553. return fresnelParameters;
  61554. };
  61555. return FresnelParameters;
  61556. }());
  61557. BABYLON.FresnelParameters = FresnelParameters;
  61558. })(BABYLON || (BABYLON = {}));
  61559. //# sourceMappingURL=babylon.fresnelParameters.js.map
  61560. var BABYLON;
  61561. (function (BABYLON) {
  61562. var MultiMaterial = /** @class */ (function (_super) {
  61563. __extends(MultiMaterial, _super);
  61564. function MultiMaterial(name, scene) {
  61565. var _this = _super.call(this, name, scene, true) || this;
  61566. scene.multiMaterials.push(_this);
  61567. _this.subMaterials = new Array();
  61568. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  61569. return _this;
  61570. }
  61571. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  61572. get: function () {
  61573. return this._subMaterials;
  61574. },
  61575. set: function (value) {
  61576. this._subMaterials = value;
  61577. this._hookArray(value);
  61578. },
  61579. enumerable: true,
  61580. configurable: true
  61581. });
  61582. MultiMaterial.prototype._hookArray = function (array) {
  61583. var _this = this;
  61584. var oldPush = array.push;
  61585. array.push = function () {
  61586. var items = [];
  61587. for (var _i = 0; _i < arguments.length; _i++) {
  61588. items[_i] = arguments[_i];
  61589. }
  61590. var result = oldPush.apply(array, items);
  61591. _this._markAllSubMeshesAsTexturesDirty();
  61592. return result;
  61593. };
  61594. var oldSplice = array.splice;
  61595. array.splice = function (index, deleteCount) {
  61596. var deleted = oldSplice.apply(array, [index, deleteCount]);
  61597. _this._markAllSubMeshesAsTexturesDirty();
  61598. return deleted;
  61599. };
  61600. };
  61601. // Properties
  61602. MultiMaterial.prototype.getSubMaterial = function (index) {
  61603. if (index < 0 || index >= this.subMaterials.length) {
  61604. return this.getScene().defaultMaterial;
  61605. }
  61606. return this.subMaterials[index];
  61607. };
  61608. MultiMaterial.prototype.getActiveTextures = function () {
  61609. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  61610. if (subMaterial) {
  61611. return subMaterial.getActiveTextures();
  61612. }
  61613. else {
  61614. return [];
  61615. }
  61616. }));
  61617. var _a;
  61618. };
  61619. // Methods
  61620. MultiMaterial.prototype.getClassName = function () {
  61621. return "MultiMaterial";
  61622. };
  61623. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  61624. for (var index = 0; index < this.subMaterials.length; index++) {
  61625. var subMaterial = this.subMaterials[index];
  61626. if (subMaterial) {
  61627. if (subMaterial.storeEffectOnSubMeshes) {
  61628. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  61629. return false;
  61630. }
  61631. continue;
  61632. }
  61633. if (!subMaterial.isReady(mesh)) {
  61634. return false;
  61635. }
  61636. }
  61637. }
  61638. return true;
  61639. };
  61640. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  61641. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  61642. for (var index = 0; index < this.subMaterials.length; index++) {
  61643. var subMaterial = null;
  61644. var current = this.subMaterials[index];
  61645. if (cloneChildren && current) {
  61646. subMaterial = current.clone(name + "-" + current.name);
  61647. }
  61648. else {
  61649. subMaterial = this.subMaterials[index];
  61650. }
  61651. newMultiMaterial.subMaterials.push(subMaterial);
  61652. }
  61653. return newMultiMaterial;
  61654. };
  61655. MultiMaterial.prototype.serialize = function () {
  61656. var serializationObject = {};
  61657. serializationObject.name = this.name;
  61658. serializationObject.id = this.id;
  61659. if (BABYLON.Tags) {
  61660. serializationObject.tags = BABYLON.Tags.GetTags(this);
  61661. }
  61662. serializationObject.materials = [];
  61663. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  61664. var subMat = this.subMaterials[matIndex];
  61665. if (subMat) {
  61666. serializationObject.materials.push(subMat.id);
  61667. }
  61668. else {
  61669. serializationObject.materials.push(null);
  61670. }
  61671. }
  61672. return serializationObject;
  61673. };
  61674. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  61675. var scene = this.getScene();
  61676. if (!scene) {
  61677. return;
  61678. }
  61679. var index = scene.multiMaterials.indexOf(this);
  61680. if (index >= 0) {
  61681. scene.multiMaterials.splice(index, 1);
  61682. }
  61683. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  61684. };
  61685. return MultiMaterial;
  61686. }(BABYLON.Material));
  61687. BABYLON.MultiMaterial = MultiMaterial;
  61688. })(BABYLON || (BABYLON = {}));
  61689. //# sourceMappingURL=babylon.multiMaterial.js.map
  61690. var BABYLON;
  61691. (function (BABYLON) {
  61692. var FreeCameraTouchInput = /** @class */ (function () {
  61693. function FreeCameraTouchInput() {
  61694. this._offsetX = null;
  61695. this._offsetY = null;
  61696. this._pointerPressed = new Array();
  61697. this.touchAngularSensibility = 200000.0;
  61698. this.touchMoveSensibility = 250.0;
  61699. }
  61700. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  61701. var _this = this;
  61702. var previousPosition = null;
  61703. if (this._pointerInput === undefined) {
  61704. this._onLostFocus = function (evt) {
  61705. _this._offsetX = null;
  61706. _this._offsetY = null;
  61707. };
  61708. this._pointerInput = function (p, s) {
  61709. var evt = p.event;
  61710. if (evt.pointerType === "mouse") {
  61711. return;
  61712. }
  61713. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  61714. if (!noPreventDefault) {
  61715. evt.preventDefault();
  61716. }
  61717. _this._pointerPressed.push(evt.pointerId);
  61718. if (_this._pointerPressed.length !== 1) {
  61719. return;
  61720. }
  61721. previousPosition = {
  61722. x: evt.clientX,
  61723. y: evt.clientY
  61724. };
  61725. }
  61726. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  61727. if (!noPreventDefault) {
  61728. evt.preventDefault();
  61729. }
  61730. var index = _this._pointerPressed.indexOf(evt.pointerId);
  61731. if (index === -1) {
  61732. return;
  61733. }
  61734. _this._pointerPressed.splice(index, 1);
  61735. if (index != 0) {
  61736. return;
  61737. }
  61738. previousPosition = null;
  61739. _this._offsetX = null;
  61740. _this._offsetY = null;
  61741. }
  61742. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  61743. if (!noPreventDefault) {
  61744. evt.preventDefault();
  61745. }
  61746. if (!previousPosition) {
  61747. return;
  61748. }
  61749. var index = _this._pointerPressed.indexOf(evt.pointerId);
  61750. if (index != 0) {
  61751. return;
  61752. }
  61753. _this._offsetX = evt.clientX - previousPosition.x;
  61754. _this._offsetY = -(evt.clientY - previousPosition.y);
  61755. }
  61756. };
  61757. }
  61758. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  61759. if (this._onLostFocus) {
  61760. element.addEventListener("blur", this._onLostFocus);
  61761. }
  61762. };
  61763. FreeCameraTouchInput.prototype.detachControl = function (element) {
  61764. if (this._pointerInput && element) {
  61765. if (this._observer) {
  61766. this.camera.getScene().onPointerObservable.remove(this._observer);
  61767. this._observer = null;
  61768. }
  61769. if (this._onLostFocus) {
  61770. element.removeEventListener("blur", this._onLostFocus);
  61771. this._onLostFocus = null;
  61772. }
  61773. this._pointerPressed = [];
  61774. this._offsetX = null;
  61775. this._offsetY = null;
  61776. }
  61777. };
  61778. FreeCameraTouchInput.prototype.checkInputs = function () {
  61779. if (this._offsetX && this._offsetY) {
  61780. var camera = this.camera;
  61781. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  61782. if (this._pointerPressed.length > 1) {
  61783. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  61784. }
  61785. else {
  61786. var speed = camera._computeLocalCameraSpeed();
  61787. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  61788. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  61789. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  61790. }
  61791. }
  61792. };
  61793. FreeCameraTouchInput.prototype.getClassName = function () {
  61794. return "FreeCameraTouchInput";
  61795. };
  61796. FreeCameraTouchInput.prototype.getSimpleName = function () {
  61797. return "touch";
  61798. };
  61799. __decorate([
  61800. BABYLON.serialize()
  61801. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  61802. __decorate([
  61803. BABYLON.serialize()
  61804. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  61805. return FreeCameraTouchInput;
  61806. }());
  61807. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  61808. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  61809. })(BABYLON || (BABYLON = {}));
  61810. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  61811. var BABYLON;
  61812. (function (BABYLON) {
  61813. // We're mainly based on the logic defined into the FreeCamera code
  61814. var TouchCamera = /** @class */ (function (_super) {
  61815. __extends(TouchCamera, _super);
  61816. //-- end properties for backward compatibility for inputs
  61817. function TouchCamera(name, position, scene) {
  61818. var _this = _super.call(this, name, position, scene) || this;
  61819. _this.inputs.addTouch();
  61820. _this._setupInputs();
  61821. return _this;
  61822. }
  61823. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  61824. //-- Begin properties for backward compatibility for inputs
  61825. get: function () {
  61826. var touch = this.inputs.attached["touch"];
  61827. if (touch)
  61828. return touch.touchAngularSensibility;
  61829. return 0;
  61830. },
  61831. set: function (value) {
  61832. var touch = this.inputs.attached["touch"];
  61833. if (touch)
  61834. touch.touchAngularSensibility = value;
  61835. },
  61836. enumerable: true,
  61837. configurable: true
  61838. });
  61839. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  61840. get: function () {
  61841. var touch = this.inputs.attached["touch"];
  61842. if (touch)
  61843. return touch.touchMoveSensibility;
  61844. return 0;
  61845. },
  61846. set: function (value) {
  61847. var touch = this.inputs.attached["touch"];
  61848. if (touch)
  61849. touch.touchMoveSensibility = value;
  61850. },
  61851. enumerable: true,
  61852. configurable: true
  61853. });
  61854. TouchCamera.prototype.getClassName = function () {
  61855. return "TouchCamera";
  61856. };
  61857. TouchCamera.prototype._setupInputs = function () {
  61858. var mouse = this.inputs.attached["mouse"];
  61859. if (mouse) {
  61860. mouse.touchEnabled = false;
  61861. }
  61862. };
  61863. return TouchCamera;
  61864. }(BABYLON.FreeCamera));
  61865. BABYLON.TouchCamera = TouchCamera;
  61866. })(BABYLON || (BABYLON = {}));
  61867. //# sourceMappingURL=babylon.touchCamera.js.map
  61868. var BABYLON;
  61869. (function (BABYLON) {
  61870. var ProceduralTexture = /** @class */ (function (_super) {
  61871. __extends(ProceduralTexture, _super);
  61872. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  61873. if (fallbackTexture === void 0) { fallbackTexture = null; }
  61874. if (generateMipMaps === void 0) { generateMipMaps = true; }
  61875. if (isCube === void 0) { isCube = false; }
  61876. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  61877. _this.isCube = isCube;
  61878. _this.isEnabled = true;
  61879. _this._currentRefreshId = -1;
  61880. _this._refreshRate = 1;
  61881. _this._vertexBuffers = {};
  61882. _this._uniforms = new Array();
  61883. _this._samplers = new Array();
  61884. _this._textures = {};
  61885. _this._floats = {};
  61886. _this._floatsArrays = {};
  61887. _this._colors3 = {};
  61888. _this._colors4 = {};
  61889. _this._vectors2 = {};
  61890. _this._vectors3 = {};
  61891. _this._matrices = {};
  61892. _this._fallbackTextureUsed = false;
  61893. scene._proceduralTextures.push(_this);
  61894. _this._engine = scene.getEngine();
  61895. _this.name = name;
  61896. _this.isRenderTarget = true;
  61897. _this._size = size;
  61898. _this._generateMipMaps = generateMipMaps;
  61899. _this.setFragment(fragment);
  61900. _this._fallbackTexture = fallbackTexture;
  61901. if (isCube) {
  61902. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  61903. _this.setFloat("face", 0);
  61904. }
  61905. else {
  61906. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  61907. }
  61908. // VBO
  61909. var vertices = [];
  61910. vertices.push(1, 1);
  61911. vertices.push(-1, 1);
  61912. vertices.push(-1, -1);
  61913. vertices.push(1, -1);
  61914. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  61915. _this._createIndexBuffer();
  61916. return _this;
  61917. }
  61918. ProceduralTexture.prototype._createIndexBuffer = function () {
  61919. var engine = this._engine;
  61920. // Indices
  61921. var indices = [];
  61922. indices.push(0);
  61923. indices.push(1);
  61924. indices.push(2);
  61925. indices.push(0);
  61926. indices.push(2);
  61927. indices.push(3);
  61928. this._indexBuffer = engine.createIndexBuffer(indices);
  61929. };
  61930. ProceduralTexture.prototype._rebuild = function () {
  61931. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  61932. if (vb) {
  61933. vb._rebuild();
  61934. }
  61935. this._createIndexBuffer();
  61936. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  61937. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  61938. }
  61939. };
  61940. ProceduralTexture.prototype.reset = function () {
  61941. if (this._effect === undefined) {
  61942. return;
  61943. }
  61944. var engine = this._engine;
  61945. engine._releaseEffect(this._effect);
  61946. };
  61947. ProceduralTexture.prototype.isReady = function () {
  61948. var _this = this;
  61949. var engine = this._engine;
  61950. var shaders;
  61951. if (!this._fragment) {
  61952. return false;
  61953. }
  61954. if (this._fallbackTextureUsed) {
  61955. return true;
  61956. }
  61957. if (this._fragment.fragmentElement !== undefined) {
  61958. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  61959. }
  61960. else {
  61961. shaders = { vertex: "procedural", fragment: this._fragment };
  61962. }
  61963. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  61964. _this.releaseInternalTexture();
  61965. if (_this._fallbackTexture) {
  61966. _this._texture = _this._fallbackTexture._texture;
  61967. if (_this._texture) {
  61968. _this._texture.incrementReferences();
  61969. }
  61970. }
  61971. _this._fallbackTextureUsed = true;
  61972. });
  61973. return this._effect.isReady();
  61974. };
  61975. ProceduralTexture.prototype.resetRefreshCounter = function () {
  61976. this._currentRefreshId = -1;
  61977. };
  61978. ProceduralTexture.prototype.setFragment = function (fragment) {
  61979. this._fragment = fragment;
  61980. };
  61981. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  61982. get: function () {
  61983. return this._refreshRate;
  61984. },
  61985. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  61986. set: function (value) {
  61987. this._refreshRate = value;
  61988. this.resetRefreshCounter();
  61989. },
  61990. enumerable: true,
  61991. configurable: true
  61992. });
  61993. ProceduralTexture.prototype._shouldRender = function () {
  61994. if (!this.isEnabled || !this.isReady() || !this._texture) {
  61995. return false;
  61996. }
  61997. if (this._fallbackTextureUsed) {
  61998. return false;
  61999. }
  62000. if (this._currentRefreshId === -1) {
  62001. this._currentRefreshId = 1;
  62002. return true;
  62003. }
  62004. if (this.refreshRate === this._currentRefreshId) {
  62005. this._currentRefreshId = 1;
  62006. return true;
  62007. }
  62008. this._currentRefreshId++;
  62009. return false;
  62010. };
  62011. ProceduralTexture.prototype.getRenderSize = function () {
  62012. return this._size;
  62013. };
  62014. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  62015. if (this._fallbackTextureUsed) {
  62016. return;
  62017. }
  62018. this.releaseInternalTexture();
  62019. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  62020. };
  62021. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  62022. if (this._uniforms.indexOf(uniformName) === -1) {
  62023. this._uniforms.push(uniformName);
  62024. }
  62025. };
  62026. ProceduralTexture.prototype.setTexture = function (name, texture) {
  62027. if (this._samplers.indexOf(name) === -1) {
  62028. this._samplers.push(name);
  62029. }
  62030. this._textures[name] = texture;
  62031. return this;
  62032. };
  62033. ProceduralTexture.prototype.setFloat = function (name, value) {
  62034. this._checkUniform(name);
  62035. this._floats[name] = value;
  62036. return this;
  62037. };
  62038. ProceduralTexture.prototype.setFloats = function (name, value) {
  62039. this._checkUniform(name);
  62040. this._floatsArrays[name] = value;
  62041. return this;
  62042. };
  62043. ProceduralTexture.prototype.setColor3 = function (name, value) {
  62044. this._checkUniform(name);
  62045. this._colors3[name] = value;
  62046. return this;
  62047. };
  62048. ProceduralTexture.prototype.setColor4 = function (name, value) {
  62049. this._checkUniform(name);
  62050. this._colors4[name] = value;
  62051. return this;
  62052. };
  62053. ProceduralTexture.prototype.setVector2 = function (name, value) {
  62054. this._checkUniform(name);
  62055. this._vectors2[name] = value;
  62056. return this;
  62057. };
  62058. ProceduralTexture.prototype.setVector3 = function (name, value) {
  62059. this._checkUniform(name);
  62060. this._vectors3[name] = value;
  62061. return this;
  62062. };
  62063. ProceduralTexture.prototype.setMatrix = function (name, value) {
  62064. this._checkUniform(name);
  62065. this._matrices[name] = value;
  62066. return this;
  62067. };
  62068. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  62069. var scene = this.getScene();
  62070. if (!scene) {
  62071. return;
  62072. }
  62073. var engine = this._engine;
  62074. // Render
  62075. engine.enableEffect(this._effect);
  62076. engine.setState(false);
  62077. // Texture
  62078. for (var name in this._textures) {
  62079. this._effect.setTexture(name, this._textures[name]);
  62080. }
  62081. // Float
  62082. for (name in this._floats) {
  62083. this._effect.setFloat(name, this._floats[name]);
  62084. }
  62085. // Floats
  62086. for (name in this._floatsArrays) {
  62087. this._effect.setArray(name, this._floatsArrays[name]);
  62088. }
  62089. // Color3
  62090. for (name in this._colors3) {
  62091. this._effect.setColor3(name, this._colors3[name]);
  62092. }
  62093. // Color4
  62094. for (name in this._colors4) {
  62095. var color = this._colors4[name];
  62096. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  62097. }
  62098. // Vector2
  62099. for (name in this._vectors2) {
  62100. this._effect.setVector2(name, this._vectors2[name]);
  62101. }
  62102. // Vector3
  62103. for (name in this._vectors3) {
  62104. this._effect.setVector3(name, this._vectors3[name]);
  62105. }
  62106. // Matrix
  62107. for (name in this._matrices) {
  62108. this._effect.setMatrix(name, this._matrices[name]);
  62109. }
  62110. if (!this._texture) {
  62111. return;
  62112. }
  62113. if (this.isCube) {
  62114. for (var face = 0; face < 6; face++) {
  62115. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  62116. // VBOs
  62117. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  62118. this._effect.setFloat("face", face);
  62119. // Clear
  62120. engine.clear(scene.clearColor, true, true, true);
  62121. // Draw order
  62122. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  62123. // Mipmaps
  62124. if (face === 5) {
  62125. engine.generateMipMapsForCubemap(this._texture);
  62126. }
  62127. }
  62128. }
  62129. else {
  62130. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  62131. // VBOs
  62132. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  62133. // Clear
  62134. engine.clear(scene.clearColor, true, true, true);
  62135. // Draw order
  62136. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  62137. }
  62138. // Unbind
  62139. engine.unBindFramebuffer(this._texture, this.isCube);
  62140. if (this.onGenerated) {
  62141. this.onGenerated();
  62142. }
  62143. };
  62144. ProceduralTexture.prototype.clone = function () {
  62145. var textureSize = this.getSize();
  62146. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  62147. // Base texture
  62148. newTexture.hasAlpha = this.hasAlpha;
  62149. newTexture.level = this.level;
  62150. // RenderTarget Texture
  62151. newTexture.coordinatesMode = this.coordinatesMode;
  62152. return newTexture;
  62153. };
  62154. ProceduralTexture.prototype.dispose = function () {
  62155. var scene = this.getScene();
  62156. if (!scene) {
  62157. return;
  62158. }
  62159. var index = scene._proceduralTextures.indexOf(this);
  62160. if (index >= 0) {
  62161. scene._proceduralTextures.splice(index, 1);
  62162. }
  62163. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  62164. if (vertexBuffer) {
  62165. vertexBuffer.dispose();
  62166. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  62167. }
  62168. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  62169. this._indexBuffer = null;
  62170. }
  62171. _super.prototype.dispose.call(this);
  62172. };
  62173. return ProceduralTexture;
  62174. }(BABYLON.Texture));
  62175. BABYLON.ProceduralTexture = ProceduralTexture;
  62176. })(BABYLON || (BABYLON = {}));
  62177. //# sourceMappingURL=babylon.proceduralTexture.js.map
  62178. var BABYLON;
  62179. (function (BABYLON) {
  62180. var CustomProceduralTexture = /** @class */ (function (_super) {
  62181. __extends(CustomProceduralTexture, _super);
  62182. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  62183. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  62184. _this._animate = true;
  62185. _this._time = 0;
  62186. _this._texturePath = texturePath;
  62187. //Try to load json
  62188. _this.loadJson(texturePath);
  62189. _this.refreshRate = 1;
  62190. return _this;
  62191. }
  62192. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  62193. var _this = this;
  62194. var noConfigFile = function () {
  62195. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  62196. try {
  62197. _this.setFragment(_this._texturePath);
  62198. }
  62199. catch (ex) {
  62200. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  62201. }
  62202. };
  62203. var configFileUrl = jsonUrl + "/config.json";
  62204. var xhr = new XMLHttpRequest();
  62205. xhr.open("GET", configFileUrl, true);
  62206. xhr.addEventListener("load", function () {
  62207. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  62208. try {
  62209. _this._config = JSON.parse(xhr.response);
  62210. _this.updateShaderUniforms();
  62211. _this.updateTextures();
  62212. _this.setFragment(_this._texturePath + "/custom");
  62213. _this._animate = _this._config.animate;
  62214. _this.refreshRate = _this._config.refreshrate;
  62215. }
  62216. catch (ex) {
  62217. noConfigFile();
  62218. }
  62219. }
  62220. else {
  62221. noConfigFile();
  62222. }
  62223. }, false);
  62224. xhr.addEventListener("error", function () {
  62225. noConfigFile();
  62226. }, false);
  62227. try {
  62228. xhr.send();
  62229. }
  62230. catch (ex) {
  62231. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  62232. }
  62233. };
  62234. CustomProceduralTexture.prototype.isReady = function () {
  62235. if (!_super.prototype.isReady.call(this)) {
  62236. return false;
  62237. }
  62238. for (var name in this._textures) {
  62239. var texture = this._textures[name];
  62240. if (!texture.isReady()) {
  62241. return false;
  62242. }
  62243. }
  62244. return true;
  62245. };
  62246. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  62247. var scene = this.getScene();
  62248. if (this._animate && scene) {
  62249. this._time += scene.getAnimationRatio() * 0.03;
  62250. this.updateShaderUniforms();
  62251. }
  62252. _super.prototype.render.call(this, useCameraPostProcess);
  62253. };
  62254. CustomProceduralTexture.prototype.updateTextures = function () {
  62255. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  62256. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  62257. }
  62258. };
  62259. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  62260. if (this._config) {
  62261. for (var j = 0; j < this._config.uniforms.length; j++) {
  62262. var uniform = this._config.uniforms[j];
  62263. switch (uniform.type) {
  62264. case "float":
  62265. this.setFloat(uniform.name, uniform.value);
  62266. break;
  62267. case "color3":
  62268. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  62269. break;
  62270. case "color4":
  62271. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  62272. break;
  62273. case "vector2":
  62274. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  62275. break;
  62276. case "vector3":
  62277. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  62278. break;
  62279. }
  62280. }
  62281. }
  62282. this.setFloat("time", this._time);
  62283. };
  62284. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  62285. get: function () {
  62286. return this._animate;
  62287. },
  62288. set: function (value) {
  62289. this._animate = value;
  62290. },
  62291. enumerable: true,
  62292. configurable: true
  62293. });
  62294. return CustomProceduralTexture;
  62295. }(BABYLON.ProceduralTexture));
  62296. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  62297. })(BABYLON || (BABYLON = {}));
  62298. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  62299. var BABYLON;
  62300. (function (BABYLON) {
  62301. var FreeCameraGamepadInput = /** @class */ (function () {
  62302. function FreeCameraGamepadInput() {
  62303. this.gamepadAngularSensibility = 200;
  62304. this.gamepadMoveSensibility = 40;
  62305. // private members
  62306. this._cameraTransform = BABYLON.Matrix.Identity();
  62307. this._deltaTransform = BABYLON.Vector3.Zero();
  62308. this._vector3 = BABYLON.Vector3.Zero();
  62309. this._vector2 = BABYLON.Vector2.Zero();
  62310. }
  62311. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  62312. var _this = this;
  62313. var manager = this.camera.getScene().gamepadManager;
  62314. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  62315. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  62316. // prioritize XBOX gamepads.
  62317. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  62318. _this.gamepad = gamepad;
  62319. }
  62320. }
  62321. });
  62322. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  62323. if (_this.gamepad === gamepad) {
  62324. _this.gamepad = null;
  62325. }
  62326. });
  62327. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  62328. };
  62329. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  62330. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  62331. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  62332. this.gamepad = null;
  62333. };
  62334. FreeCameraGamepadInput.prototype.checkInputs = function () {
  62335. if (this.gamepad && this.gamepad.leftStick) {
  62336. var camera = this.camera;
  62337. var LSValues = this.gamepad.leftStick;
  62338. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  62339. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  62340. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  62341. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  62342. var RSValues = this.gamepad.rightStick;
  62343. if (RSValues) {
  62344. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  62345. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  62346. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  62347. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  62348. }
  62349. else {
  62350. RSValues = { x: 0, y: 0 };
  62351. }
  62352. if (!camera.rotationQuaternion) {
  62353. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  62354. }
  62355. else {
  62356. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  62357. }
  62358. var speed = camera._computeLocalCameraSpeed() * 50.0;
  62359. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  62360. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  62361. camera.cameraDirection.addInPlace(this._deltaTransform);
  62362. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  62363. camera.cameraRotation.addInPlace(this._vector2);
  62364. }
  62365. };
  62366. FreeCameraGamepadInput.prototype.getClassName = function () {
  62367. return "FreeCameraGamepadInput";
  62368. };
  62369. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  62370. return "gamepad";
  62371. };
  62372. __decorate([
  62373. BABYLON.serialize()
  62374. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  62375. __decorate([
  62376. BABYLON.serialize()
  62377. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  62378. return FreeCameraGamepadInput;
  62379. }());
  62380. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  62381. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  62382. })(BABYLON || (BABYLON = {}));
  62383. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  62384. var BABYLON;
  62385. (function (BABYLON) {
  62386. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  62387. function ArcRotateCameraGamepadInput() {
  62388. this.gamepadRotationSensibility = 80;
  62389. this.gamepadMoveSensibility = 40;
  62390. }
  62391. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  62392. var _this = this;
  62393. var manager = this.camera.getScene().gamepadManager;
  62394. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  62395. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  62396. // prioritize XBOX gamepads.
  62397. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  62398. _this.gamepad = gamepad;
  62399. }
  62400. }
  62401. });
  62402. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  62403. if (_this.gamepad === gamepad) {
  62404. _this.gamepad = null;
  62405. }
  62406. });
  62407. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  62408. };
  62409. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  62410. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  62411. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  62412. this.gamepad = null;
  62413. };
  62414. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  62415. if (this.gamepad) {
  62416. var camera = this.camera;
  62417. var RSValues = this.gamepad.rightStick;
  62418. if (RSValues) {
  62419. if (RSValues.x != 0) {
  62420. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  62421. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  62422. camera.inertialAlphaOffset += normalizedRX;
  62423. }
  62424. }
  62425. if (RSValues.y != 0) {
  62426. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  62427. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  62428. camera.inertialBetaOffset += normalizedRY;
  62429. }
  62430. }
  62431. }
  62432. var LSValues = this.gamepad.leftStick;
  62433. if (LSValues && LSValues.y != 0) {
  62434. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  62435. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  62436. this.camera.inertialRadiusOffset -= normalizedLY;
  62437. }
  62438. }
  62439. }
  62440. };
  62441. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  62442. return "ArcRotateCameraGamepadInput";
  62443. };
  62444. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  62445. return "gamepad";
  62446. };
  62447. __decorate([
  62448. BABYLON.serialize()
  62449. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  62450. __decorate([
  62451. BABYLON.serialize()
  62452. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  62453. return ArcRotateCameraGamepadInput;
  62454. }());
  62455. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  62456. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  62457. })(BABYLON || (BABYLON = {}));
  62458. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  62459. var BABYLON;
  62460. (function (BABYLON) {
  62461. var GamepadManager = /** @class */ (function () {
  62462. function GamepadManager(_scene) {
  62463. var _this = this;
  62464. this._scene = _scene;
  62465. this._babylonGamepads = [];
  62466. this._oneGamepadConnected = false;
  62467. this._isMonitoring = false;
  62468. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  62469. if (!BABYLON.Tools.IsWindowObjectExist()) {
  62470. this._gamepadEventSupported = false;
  62471. }
  62472. else {
  62473. this._gamepadEventSupported = 'GamepadEvent' in window;
  62474. this._gamepadSupport = (navigator.getGamepads ||
  62475. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  62476. }
  62477. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  62478. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  62479. for (var i in _this._babylonGamepads) {
  62480. var gamepad = _this._babylonGamepads[i];
  62481. if (gamepad && gamepad._isConnected) {
  62482. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  62483. }
  62484. }
  62485. });
  62486. this._onGamepadConnectedEvent = function (evt) {
  62487. var gamepad = evt.gamepad;
  62488. if (gamepad.index in _this._babylonGamepads) {
  62489. if (_this._babylonGamepads[gamepad.index].isConnected) {
  62490. return;
  62491. }
  62492. }
  62493. var newGamepad;
  62494. if (_this._babylonGamepads[gamepad.index]) {
  62495. newGamepad = _this._babylonGamepads[gamepad.index];
  62496. newGamepad.browserGamepad = gamepad;
  62497. newGamepad._isConnected = true;
  62498. }
  62499. else {
  62500. newGamepad = _this._addNewGamepad(gamepad);
  62501. }
  62502. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  62503. _this._startMonitoringGamepads();
  62504. };
  62505. this._onGamepadDisconnectedEvent = function (evt) {
  62506. var gamepad = evt.gamepad;
  62507. // Remove the gamepad from the list of gamepads to monitor.
  62508. for (var i in _this._babylonGamepads) {
  62509. if (_this._babylonGamepads[i].index === gamepad.index) {
  62510. var disconnectedGamepad = _this._babylonGamepads[i];
  62511. disconnectedGamepad._isConnected = false;
  62512. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  62513. break;
  62514. }
  62515. }
  62516. };
  62517. if (this._gamepadSupport) {
  62518. //first add already-connected gamepads
  62519. this._updateGamepadObjects();
  62520. if (this._babylonGamepads.length) {
  62521. this._startMonitoringGamepads();
  62522. }
  62523. // Checking if the gamepad connected event is supported (like in Firefox)
  62524. if (this._gamepadEventSupported) {
  62525. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  62526. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  62527. }
  62528. else {
  62529. this._startMonitoringGamepads();
  62530. }
  62531. }
  62532. }
  62533. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  62534. get: function () {
  62535. return this._babylonGamepads;
  62536. },
  62537. enumerable: true,
  62538. configurable: true
  62539. });
  62540. GamepadManager.prototype.getGamepadByType = function (type) {
  62541. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  62542. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  62543. var gamepad = _a[_i];
  62544. if (gamepad && gamepad.type === type) {
  62545. return gamepad;
  62546. }
  62547. }
  62548. return null;
  62549. };
  62550. GamepadManager.prototype.dispose = function () {
  62551. if (this._gamepadEventSupported) {
  62552. if (this._onGamepadConnectedEvent) {
  62553. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  62554. }
  62555. if (this._onGamepadDisconnectedEvent) {
  62556. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  62557. }
  62558. this._onGamepadConnectedEvent = null;
  62559. this._onGamepadDisconnectedEvent = null;
  62560. }
  62561. this._babylonGamepads.forEach(function (gamepad) {
  62562. gamepad.dispose();
  62563. });
  62564. this.onGamepadConnectedObservable.clear();
  62565. this.onGamepadDisconnectedObservable.clear();
  62566. this._oneGamepadConnected = false;
  62567. this._stopMonitoringGamepads();
  62568. this._babylonGamepads = [];
  62569. };
  62570. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  62571. if (!this._oneGamepadConnected) {
  62572. this._oneGamepadConnected = true;
  62573. }
  62574. var newGamepad;
  62575. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  62576. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  62577. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  62578. }
  62579. else if (gamepad.pose) {
  62580. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  62581. }
  62582. else {
  62583. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  62584. }
  62585. this._babylonGamepads[newGamepad.index] = newGamepad;
  62586. return newGamepad;
  62587. };
  62588. GamepadManager.prototype._startMonitoringGamepads = function () {
  62589. if (!this._isMonitoring) {
  62590. this._isMonitoring = true;
  62591. //back-comp
  62592. if (!this._scene) {
  62593. this._checkGamepadsStatus();
  62594. }
  62595. }
  62596. };
  62597. GamepadManager.prototype._stopMonitoringGamepads = function () {
  62598. this._isMonitoring = false;
  62599. };
  62600. GamepadManager.prototype._checkGamepadsStatus = function () {
  62601. var _this = this;
  62602. // Hack to be compatible Chrome
  62603. this._updateGamepadObjects();
  62604. for (var i in this._babylonGamepads) {
  62605. var gamepad = this._babylonGamepads[i];
  62606. if (!gamepad || !gamepad.isConnected) {
  62607. continue;
  62608. }
  62609. gamepad.update();
  62610. }
  62611. if (this._isMonitoring && !this._scene) {
  62612. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  62613. }
  62614. };
  62615. // This function is called only on Chrome, which does not properly support
  62616. // connection/disconnection events and forces you to recopy again the gamepad object
  62617. GamepadManager.prototype._updateGamepadObjects = function () {
  62618. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  62619. for (var i = 0; i < gamepads.length; i++) {
  62620. if (gamepads[i]) {
  62621. if (!this._babylonGamepads[gamepads[i].index]) {
  62622. var newGamepad = this._addNewGamepad(gamepads[i]);
  62623. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  62624. }
  62625. else {
  62626. // Forced to copy again this object for Chrome for unknown reason
  62627. this._babylonGamepads[i].browserGamepad = gamepads[i];
  62628. if (!this._babylonGamepads[i].isConnected) {
  62629. this._babylonGamepads[i]._isConnected = true;
  62630. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  62631. }
  62632. }
  62633. }
  62634. }
  62635. };
  62636. return GamepadManager;
  62637. }());
  62638. BABYLON.GamepadManager = GamepadManager;
  62639. })(BABYLON || (BABYLON = {}));
  62640. //# sourceMappingURL=babylon.gamepadManager.js.map
  62641. var BABYLON;
  62642. (function (BABYLON) {
  62643. var StickValues = /** @class */ (function () {
  62644. function StickValues(x, y) {
  62645. this.x = x;
  62646. this.y = y;
  62647. }
  62648. return StickValues;
  62649. }());
  62650. BABYLON.StickValues = StickValues;
  62651. var Gamepad = /** @class */ (function () {
  62652. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  62653. if (leftStickX === void 0) { leftStickX = 0; }
  62654. if (leftStickY === void 0) { leftStickY = 1; }
  62655. if (rightStickX === void 0) { rightStickX = 2; }
  62656. if (rightStickY === void 0) { rightStickY = 3; }
  62657. this.id = id;
  62658. this.index = index;
  62659. this.browserGamepad = browserGamepad;
  62660. this._isConnected = true;
  62661. this._invertLeftStickY = false;
  62662. this.type = Gamepad.GAMEPAD;
  62663. this._leftStickAxisX = leftStickX;
  62664. this._leftStickAxisY = leftStickY;
  62665. this._rightStickAxisX = rightStickX;
  62666. this._rightStickAxisY = rightStickY;
  62667. if (this.browserGamepad.axes.length >= 2) {
  62668. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  62669. }
  62670. if (this.browserGamepad.axes.length >= 4) {
  62671. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  62672. }
  62673. }
  62674. Object.defineProperty(Gamepad.prototype, "isConnected", {
  62675. get: function () {
  62676. return this._isConnected;
  62677. },
  62678. enumerable: true,
  62679. configurable: true
  62680. });
  62681. Gamepad.prototype.onleftstickchanged = function (callback) {
  62682. this._onleftstickchanged = callback;
  62683. };
  62684. Gamepad.prototype.onrightstickchanged = function (callback) {
  62685. this._onrightstickchanged = callback;
  62686. };
  62687. Object.defineProperty(Gamepad.prototype, "leftStick", {
  62688. get: function () {
  62689. return this._leftStick;
  62690. },
  62691. set: function (newValues) {
  62692. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  62693. this._onleftstickchanged(newValues);
  62694. }
  62695. this._leftStick = newValues;
  62696. },
  62697. enumerable: true,
  62698. configurable: true
  62699. });
  62700. Object.defineProperty(Gamepad.prototype, "rightStick", {
  62701. get: function () {
  62702. return this._rightStick;
  62703. },
  62704. set: function (newValues) {
  62705. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  62706. this._onrightstickchanged(newValues);
  62707. }
  62708. this._rightStick = newValues;
  62709. },
  62710. enumerable: true,
  62711. configurable: true
  62712. });
  62713. Gamepad.prototype.update = function () {
  62714. if (this._leftStick) {
  62715. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  62716. if (this._invertLeftStickY) {
  62717. this.leftStick.y *= -1;
  62718. }
  62719. }
  62720. if (this._rightStick) {
  62721. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  62722. }
  62723. };
  62724. Gamepad.prototype.dispose = function () {
  62725. };
  62726. Gamepad.GAMEPAD = 0;
  62727. Gamepad.GENERIC = 1;
  62728. Gamepad.XBOX = 2;
  62729. Gamepad.POSE_ENABLED = 3;
  62730. return Gamepad;
  62731. }());
  62732. BABYLON.Gamepad = Gamepad;
  62733. var GenericPad = /** @class */ (function (_super) {
  62734. __extends(GenericPad, _super);
  62735. function GenericPad(id, index, browserGamepad) {
  62736. var _this = _super.call(this, id, index, browserGamepad) || this;
  62737. _this.onButtonDownObservable = new BABYLON.Observable();
  62738. _this.onButtonUpObservable = new BABYLON.Observable();
  62739. _this.type = Gamepad.GENERIC;
  62740. _this._buttons = new Array(browserGamepad.buttons.length);
  62741. return _this;
  62742. }
  62743. GenericPad.prototype.onbuttondown = function (callback) {
  62744. this._onbuttondown = callback;
  62745. };
  62746. GenericPad.prototype.onbuttonup = function (callback) {
  62747. this._onbuttonup = callback;
  62748. };
  62749. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  62750. if (newValue !== currentValue) {
  62751. if (newValue === 1) {
  62752. if (this._onbuttondown) {
  62753. this._onbuttondown(buttonIndex);
  62754. }
  62755. this.onButtonDownObservable.notifyObservers(buttonIndex);
  62756. }
  62757. if (newValue === 0) {
  62758. if (this._onbuttonup) {
  62759. this._onbuttonup(buttonIndex);
  62760. }
  62761. this.onButtonUpObservable.notifyObservers(buttonIndex);
  62762. }
  62763. }
  62764. return newValue;
  62765. };
  62766. GenericPad.prototype.update = function () {
  62767. _super.prototype.update.call(this);
  62768. for (var index = 0; index < this._buttons.length; index++) {
  62769. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  62770. }
  62771. };
  62772. GenericPad.prototype.dispose = function () {
  62773. _super.prototype.dispose.call(this);
  62774. this.onButtonDownObservable.clear();
  62775. this.onButtonUpObservable.clear();
  62776. };
  62777. return GenericPad;
  62778. }(Gamepad));
  62779. BABYLON.GenericPad = GenericPad;
  62780. })(BABYLON || (BABYLON = {}));
  62781. //# sourceMappingURL=babylon.gamepad.js.map
  62782. var BABYLON;
  62783. (function (BABYLON) {
  62784. var Xbox360Button;
  62785. (function (Xbox360Button) {
  62786. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  62787. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  62788. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  62789. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  62790. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  62791. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  62792. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  62793. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  62794. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  62795. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  62796. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  62797. var Xbox360Dpad;
  62798. (function (Xbox360Dpad) {
  62799. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  62800. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  62801. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  62802. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  62803. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  62804. var Xbox360Pad = /** @class */ (function (_super) {
  62805. __extends(Xbox360Pad, _super);
  62806. function Xbox360Pad(id, index, gamepad, xboxOne) {
  62807. if (xboxOne === void 0) { xboxOne = false; }
  62808. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  62809. _this._leftTrigger = 0;
  62810. _this._rightTrigger = 0;
  62811. _this.onButtonDownObservable = new BABYLON.Observable();
  62812. _this.onButtonUpObservable = new BABYLON.Observable();
  62813. _this.onPadDownObservable = new BABYLON.Observable();
  62814. _this.onPadUpObservable = new BABYLON.Observable();
  62815. _this._buttonA = 0;
  62816. _this._buttonB = 0;
  62817. _this._buttonX = 0;
  62818. _this._buttonY = 0;
  62819. _this._buttonBack = 0;
  62820. _this._buttonStart = 0;
  62821. _this._buttonLB = 0;
  62822. _this._buttonRB = 0;
  62823. _this._buttonLeftStick = 0;
  62824. _this._buttonRightStick = 0;
  62825. _this._dPadUp = 0;
  62826. _this._dPadDown = 0;
  62827. _this._dPadLeft = 0;
  62828. _this._dPadRight = 0;
  62829. _this._isXboxOnePad = false;
  62830. _this.type = BABYLON.Gamepad.XBOX;
  62831. _this._isXboxOnePad = xboxOne;
  62832. return _this;
  62833. }
  62834. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  62835. this._onlefttriggerchanged = callback;
  62836. };
  62837. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  62838. this._onrighttriggerchanged = callback;
  62839. };
  62840. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  62841. get: function () {
  62842. return this._leftTrigger;
  62843. },
  62844. set: function (newValue) {
  62845. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  62846. this._onlefttriggerchanged(newValue);
  62847. }
  62848. this._leftTrigger = newValue;
  62849. },
  62850. enumerable: true,
  62851. configurable: true
  62852. });
  62853. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  62854. get: function () {
  62855. return this._rightTrigger;
  62856. },
  62857. set: function (newValue) {
  62858. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  62859. this._onrighttriggerchanged(newValue);
  62860. }
  62861. this._rightTrigger = newValue;
  62862. },
  62863. enumerable: true,
  62864. configurable: true
  62865. });
  62866. Xbox360Pad.prototype.onbuttondown = function (callback) {
  62867. this._onbuttondown = callback;
  62868. };
  62869. Xbox360Pad.prototype.onbuttonup = function (callback) {
  62870. this._onbuttonup = callback;
  62871. };
  62872. Xbox360Pad.prototype.ondpaddown = function (callback) {
  62873. this._ondpaddown = callback;
  62874. };
  62875. Xbox360Pad.prototype.ondpadup = function (callback) {
  62876. this._ondpadup = callback;
  62877. };
  62878. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  62879. if (newValue !== currentValue) {
  62880. if (newValue === 1) {
  62881. if (this._onbuttondown) {
  62882. this._onbuttondown(buttonType);
  62883. }
  62884. this.onButtonDownObservable.notifyObservers(buttonType);
  62885. }
  62886. if (newValue === 0) {
  62887. if (this._onbuttonup) {
  62888. this._onbuttonup(buttonType);
  62889. }
  62890. this.onButtonUpObservable.notifyObservers(buttonType);
  62891. }
  62892. }
  62893. return newValue;
  62894. };
  62895. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  62896. if (newValue !== currentValue) {
  62897. if (newValue === 1) {
  62898. if (this._ondpaddown) {
  62899. this._ondpaddown(buttonType);
  62900. }
  62901. this.onPadDownObservable.notifyObservers(buttonType);
  62902. }
  62903. if (newValue === 0) {
  62904. if (this._ondpadup) {
  62905. this._ondpadup(buttonType);
  62906. }
  62907. this.onPadUpObservable.notifyObservers(buttonType);
  62908. }
  62909. }
  62910. return newValue;
  62911. };
  62912. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  62913. get: function () {
  62914. return this._buttonA;
  62915. },
  62916. set: function (value) {
  62917. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  62918. },
  62919. enumerable: true,
  62920. configurable: true
  62921. });
  62922. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  62923. get: function () {
  62924. return this._buttonB;
  62925. },
  62926. set: function (value) {
  62927. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  62928. },
  62929. enumerable: true,
  62930. configurable: true
  62931. });
  62932. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  62933. get: function () {
  62934. return this._buttonX;
  62935. },
  62936. set: function (value) {
  62937. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  62938. },
  62939. enumerable: true,
  62940. configurable: true
  62941. });
  62942. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  62943. get: function () {
  62944. return this._buttonY;
  62945. },
  62946. set: function (value) {
  62947. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  62948. },
  62949. enumerable: true,
  62950. configurable: true
  62951. });
  62952. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  62953. get: function () {
  62954. return this._buttonStart;
  62955. },
  62956. set: function (value) {
  62957. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  62958. },
  62959. enumerable: true,
  62960. configurable: true
  62961. });
  62962. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  62963. get: function () {
  62964. return this._buttonBack;
  62965. },
  62966. set: function (value) {
  62967. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  62968. },
  62969. enumerable: true,
  62970. configurable: true
  62971. });
  62972. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  62973. get: function () {
  62974. return this._buttonLB;
  62975. },
  62976. set: function (value) {
  62977. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  62978. },
  62979. enumerable: true,
  62980. configurable: true
  62981. });
  62982. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  62983. get: function () {
  62984. return this._buttonRB;
  62985. },
  62986. set: function (value) {
  62987. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  62988. },
  62989. enumerable: true,
  62990. configurable: true
  62991. });
  62992. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  62993. get: function () {
  62994. return this._buttonLeftStick;
  62995. },
  62996. set: function (value) {
  62997. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  62998. },
  62999. enumerable: true,
  63000. configurable: true
  63001. });
  63002. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  63003. get: function () {
  63004. return this._buttonRightStick;
  63005. },
  63006. set: function (value) {
  63007. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  63008. },
  63009. enumerable: true,
  63010. configurable: true
  63011. });
  63012. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  63013. get: function () {
  63014. return this._dPadUp;
  63015. },
  63016. set: function (value) {
  63017. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  63018. },
  63019. enumerable: true,
  63020. configurable: true
  63021. });
  63022. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  63023. get: function () {
  63024. return this._dPadDown;
  63025. },
  63026. set: function (value) {
  63027. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  63028. },
  63029. enumerable: true,
  63030. configurable: true
  63031. });
  63032. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  63033. get: function () {
  63034. return this._dPadLeft;
  63035. },
  63036. set: function (value) {
  63037. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  63038. },
  63039. enumerable: true,
  63040. configurable: true
  63041. });
  63042. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  63043. get: function () {
  63044. return this._dPadRight;
  63045. },
  63046. set: function (value) {
  63047. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  63048. },
  63049. enumerable: true,
  63050. configurable: true
  63051. });
  63052. Xbox360Pad.prototype.update = function () {
  63053. _super.prototype.update.call(this);
  63054. if (this._isXboxOnePad) {
  63055. this.buttonA = this.browserGamepad.buttons[0].value;
  63056. this.buttonB = this.browserGamepad.buttons[1].value;
  63057. this.buttonX = this.browserGamepad.buttons[2].value;
  63058. this.buttonY = this.browserGamepad.buttons[3].value;
  63059. this.buttonLB = this.browserGamepad.buttons[4].value;
  63060. this.buttonRB = this.browserGamepad.buttons[5].value;
  63061. this.leftTrigger = this.browserGamepad.axes[2];
  63062. this.rightTrigger = this.browserGamepad.axes[5];
  63063. this.buttonBack = this.browserGamepad.buttons[9].value;
  63064. this.buttonStart = this.browserGamepad.buttons[8].value;
  63065. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  63066. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  63067. this.dPadUp = this.browserGamepad.buttons[11].value;
  63068. this.dPadDown = this.browserGamepad.buttons[12].value;
  63069. this.dPadLeft = this.browserGamepad.buttons[13].value;
  63070. this.dPadRight = this.browserGamepad.buttons[14].value;
  63071. }
  63072. else {
  63073. this.buttonA = this.browserGamepad.buttons[0].value;
  63074. this.buttonB = this.browserGamepad.buttons[1].value;
  63075. this.buttonX = this.browserGamepad.buttons[2].value;
  63076. this.buttonY = this.browserGamepad.buttons[3].value;
  63077. this.buttonLB = this.browserGamepad.buttons[4].value;
  63078. this.buttonRB = this.browserGamepad.buttons[5].value;
  63079. this.leftTrigger = this.browserGamepad.buttons[6].value;
  63080. this.rightTrigger = this.browserGamepad.buttons[7].value;
  63081. this.buttonBack = this.browserGamepad.buttons[8].value;
  63082. this.buttonStart = this.browserGamepad.buttons[9].value;
  63083. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  63084. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  63085. this.dPadUp = this.browserGamepad.buttons[12].value;
  63086. this.dPadDown = this.browserGamepad.buttons[13].value;
  63087. this.dPadLeft = this.browserGamepad.buttons[14].value;
  63088. this.dPadRight = this.browserGamepad.buttons[15].value;
  63089. }
  63090. };
  63091. Xbox360Pad.prototype.dispose = function () {
  63092. _super.prototype.dispose.call(this);
  63093. this.onButtonDownObservable.clear();
  63094. this.onButtonUpObservable.clear();
  63095. this.onPadDownObservable.clear();
  63096. this.onPadUpObservable.clear();
  63097. };
  63098. return Xbox360Pad;
  63099. }(BABYLON.Gamepad));
  63100. BABYLON.Xbox360Pad = Xbox360Pad;
  63101. })(BABYLON || (BABYLON = {}));
  63102. //# sourceMappingURL=babylon.xboxGamepad.js.map
  63103. var BABYLON;
  63104. (function (BABYLON) {
  63105. var PoseEnabledControllerType;
  63106. (function (PoseEnabledControllerType) {
  63107. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  63108. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  63109. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  63110. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  63111. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 4] = "GENERIC";
  63112. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  63113. var PoseEnabledControllerHelper = /** @class */ (function () {
  63114. function PoseEnabledControllerHelper() {
  63115. }
  63116. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  63117. // Oculus Touch
  63118. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  63119. return new BABYLON.OculusTouchController(vrGamepad);
  63120. }
  63121. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  63122. return new BABYLON.WindowsMotionController(vrGamepad);
  63123. }
  63124. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  63125. return new BABYLON.ViveController(vrGamepad);
  63126. }
  63127. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0) {
  63128. return new BABYLON.GearVRController(vrGamepad);
  63129. }
  63130. else {
  63131. return new BABYLON.GenericController(vrGamepad);
  63132. }
  63133. };
  63134. return PoseEnabledControllerHelper;
  63135. }());
  63136. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  63137. var PoseEnabledController = /** @class */ (function (_super) {
  63138. __extends(PoseEnabledController, _super);
  63139. function PoseEnabledController(browserGamepad) {
  63140. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  63141. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  63142. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  63143. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  63144. // Represents device position and rotation in babylon space
  63145. _this.devicePosition = BABYLON.Vector3.Zero();
  63146. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  63147. _this.deviceScaleFactor = 1;
  63148. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  63149. _this._deviceToWorld = BABYLON.Matrix.Identity();
  63150. _this._workingMatrix = BABYLON.Matrix.Identity();
  63151. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  63152. _this.controllerType = PoseEnabledControllerType.GENERIC;
  63153. _this.position = BABYLON.Vector3.Zero();
  63154. _this.rotationQuaternion = new BABYLON.Quaternion();
  63155. _this._calculatedPosition = BABYLON.Vector3.Zero();
  63156. _this._calculatedRotation = new BABYLON.Quaternion();
  63157. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  63158. return _this;
  63159. }
  63160. PoseEnabledController.prototype.update = function () {
  63161. _super.prototype.update.call(this);
  63162. var pose = this.browserGamepad.pose;
  63163. this.updateFromDevice(pose);
  63164. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  63165. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  63166. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  63167. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  63168. if (this._mesh) {
  63169. this._mesh.position.copyFrom(this.devicePosition);
  63170. if (this._mesh.rotationQuaternion) {
  63171. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  63172. }
  63173. }
  63174. };
  63175. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  63176. if (poseData) {
  63177. this.rawPose = poseData;
  63178. if (poseData.position) {
  63179. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  63180. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  63181. this._deviceRoomPosition.z *= -1;
  63182. }
  63183. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  63184. this._calculatedPosition.addInPlace(this.position);
  63185. }
  63186. var pose = this.rawPose;
  63187. if (poseData.orientation && pose.orientation) {
  63188. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  63189. if (this._mesh) {
  63190. if (this._mesh.getScene().useRightHandedSystem) {
  63191. this._deviceRoomRotationQuaternion.z *= -1;
  63192. this._deviceRoomRotationQuaternion.w *= -1;
  63193. }
  63194. else {
  63195. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  63196. }
  63197. }
  63198. // if the camera is set, rotate to the camera's rotation
  63199. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  63200. }
  63201. }
  63202. };
  63203. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  63204. if (this._mesh) {
  63205. this._mesh.parent = null;
  63206. }
  63207. this._mesh = mesh;
  63208. if (this._poseControlledCamera) {
  63209. this._mesh.parent = this._poseControlledCamera;
  63210. }
  63211. if (!this._mesh.rotationQuaternion) {
  63212. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  63213. }
  63214. };
  63215. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  63216. this._poseControlledCamera = camera;
  63217. if (this._mesh) {
  63218. this._mesh.parent = this._poseControlledCamera;
  63219. }
  63220. };
  63221. PoseEnabledController.prototype.dispose = function () {
  63222. if (this._mesh) {
  63223. this._mesh.dispose();
  63224. }
  63225. this._mesh = null;
  63226. _super.prototype.dispose.call(this);
  63227. };
  63228. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  63229. get: function () {
  63230. return this._mesh;
  63231. },
  63232. enumerable: true,
  63233. configurable: true
  63234. });
  63235. PoseEnabledController.prototype.getForwardRay = function (length) {
  63236. if (length === void 0) { length = 100; }
  63237. if (!this.mesh) {
  63238. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  63239. }
  63240. var m = this.mesh.getWorldMatrix();
  63241. var origin = m.getTranslation();
  63242. var forward = new BABYLON.Vector3(0, 0, -1);
  63243. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  63244. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  63245. return new BABYLON.Ray(origin, direction, length);
  63246. };
  63247. return PoseEnabledController;
  63248. }(BABYLON.Gamepad));
  63249. BABYLON.PoseEnabledController = PoseEnabledController;
  63250. })(BABYLON || (BABYLON = {}));
  63251. //# sourceMappingURL=babylon.poseEnabledController.js.map
  63252. var BABYLON;
  63253. (function (BABYLON) {
  63254. var WebVRController = /** @class */ (function (_super) {
  63255. __extends(WebVRController, _super);
  63256. function WebVRController(vrGamepad) {
  63257. var _this = _super.call(this, vrGamepad) || this;
  63258. // Observables
  63259. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  63260. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  63261. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  63262. _this.onPadStateChangedObservable = new BABYLON.Observable();
  63263. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  63264. _this.pad = { x: 0, y: 0 };
  63265. // avoid GC, store state in a tmp object
  63266. _this._changes = {
  63267. pressChanged: false,
  63268. touchChanged: false,
  63269. valueChanged: false,
  63270. changed: false
  63271. };
  63272. _this._buttons = new Array(vrGamepad.buttons.length);
  63273. _this.hand = vrGamepad.hand;
  63274. return _this;
  63275. }
  63276. WebVRController.prototype.onButtonStateChange = function (callback) {
  63277. this._onButtonStateChange = callback;
  63278. };
  63279. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  63280. get: function () {
  63281. return this._defaultModel;
  63282. },
  63283. enumerable: true,
  63284. configurable: true
  63285. });
  63286. WebVRController.prototype.update = function () {
  63287. _super.prototype.update.call(this);
  63288. for (var index = 0; index < this._buttons.length; index++) {
  63289. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  63290. }
  63291. ;
  63292. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  63293. this.pad.x = this.leftStick.x;
  63294. this.pad.y = this.leftStick.y;
  63295. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  63296. }
  63297. };
  63298. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  63299. if (!newState) {
  63300. newState = {
  63301. pressed: false,
  63302. touched: false,
  63303. value: 0
  63304. };
  63305. }
  63306. if (!currentState) {
  63307. this._buttons[buttonIndex] = {
  63308. pressed: newState.pressed,
  63309. touched: newState.touched,
  63310. value: newState.value
  63311. };
  63312. return;
  63313. }
  63314. this._checkChanges(newState, currentState);
  63315. if (this._changes.changed) {
  63316. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  63317. this.handleButtonChange(buttonIndex, newState, this._changes);
  63318. }
  63319. this._buttons[buttonIndex].pressed = newState.pressed;
  63320. this._buttons[buttonIndex].touched = newState.touched;
  63321. // oculus triggers are never 0, thou not touched.
  63322. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  63323. };
  63324. WebVRController.prototype._checkChanges = function (newState, currentState) {
  63325. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  63326. this._changes.touchChanged = newState.touched !== currentState.touched;
  63327. this._changes.valueChanged = newState.value !== currentState.value;
  63328. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  63329. return this._changes;
  63330. };
  63331. WebVRController.prototype.dispose = function () {
  63332. _super.prototype.dispose.call(this);
  63333. this.onTriggerStateChangedObservable.clear();
  63334. this.onMainButtonStateChangedObservable.clear();
  63335. this.onSecondaryButtonStateChangedObservable.clear();
  63336. this.onPadStateChangedObservable.clear();
  63337. this.onPadValuesChangedObservable.clear();
  63338. };
  63339. return WebVRController;
  63340. }(BABYLON.PoseEnabledController));
  63341. BABYLON.WebVRController = WebVRController;
  63342. })(BABYLON || (BABYLON = {}));
  63343. //# sourceMappingURL=babylon.webVRController.js.map
  63344. var BABYLON;
  63345. (function (BABYLON) {
  63346. var OculusTouchController = /** @class */ (function (_super) {
  63347. __extends(OculusTouchController, _super);
  63348. function OculusTouchController(vrGamepad) {
  63349. var _this = _super.call(this, vrGamepad) || this;
  63350. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  63351. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  63352. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  63353. return _this;
  63354. }
  63355. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  63356. var _this = this;
  63357. var meshName;
  63358. // Hand
  63359. if (this.hand === 'left') {
  63360. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  63361. }
  63362. else {
  63363. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  63364. }
  63365. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  63366. /*
  63367. Parent Mesh name: oculus_touch_left
  63368. - body
  63369. - trigger
  63370. - thumbstick
  63371. - grip
  63372. - button_y
  63373. - button_x
  63374. - button_enter
  63375. */
  63376. _this._defaultModel = newMeshes[1];
  63377. _this.attachToMesh(_this._defaultModel);
  63378. if (meshLoaded) {
  63379. meshLoaded(_this._defaultModel);
  63380. }
  63381. });
  63382. };
  63383. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  63384. // helper getters for left and right hand.
  63385. get: function () {
  63386. if (this.hand === 'right') {
  63387. return this.onMainButtonStateChangedObservable;
  63388. }
  63389. else {
  63390. throw new Error('No A button on left hand');
  63391. }
  63392. },
  63393. enumerable: true,
  63394. configurable: true
  63395. });
  63396. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  63397. get: function () {
  63398. if (this.hand === 'right') {
  63399. return this.onSecondaryButtonStateChangedObservable;
  63400. }
  63401. else {
  63402. throw new Error('No B button on left hand');
  63403. }
  63404. },
  63405. enumerable: true,
  63406. configurable: true
  63407. });
  63408. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  63409. get: function () {
  63410. if (this.hand === 'left') {
  63411. return this.onMainButtonStateChangedObservable;
  63412. }
  63413. else {
  63414. throw new Error('No X button on right hand');
  63415. }
  63416. },
  63417. enumerable: true,
  63418. configurable: true
  63419. });
  63420. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  63421. get: function () {
  63422. if (this.hand === 'left') {
  63423. return this.onSecondaryButtonStateChangedObservable;
  63424. }
  63425. else {
  63426. throw new Error('No Y button on right hand');
  63427. }
  63428. },
  63429. enumerable: true,
  63430. configurable: true
  63431. });
  63432. /*
  63433. 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  63434. 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  63435. 2) secondary trigger (same)
  63436. 3) A (right) X (left), touch, pressed = value
  63437. 4) B / Y
  63438. 5) thumb rest
  63439. */
  63440. OculusTouchController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  63441. var notifyObject = state; //{ state: state, changes: changes };
  63442. var triggerDirection = this.hand === 'right' ? -1 : 1;
  63443. switch (buttonIdx) {
  63444. case 0:
  63445. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  63446. return;
  63447. case 1:// index trigger
  63448. if (this._defaultModel) {
  63449. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  63450. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  63451. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  63452. }
  63453. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  63454. return;
  63455. case 2:// secondary trigger
  63456. if (this._defaultModel) {
  63457. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  63458. }
  63459. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  63460. return;
  63461. case 3:
  63462. if (this._defaultModel) {
  63463. if (notifyObject.pressed) {
  63464. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  63465. }
  63466. else {
  63467. (this._defaultModel.getChildren()[1]).position.y = 0;
  63468. }
  63469. }
  63470. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  63471. return;
  63472. case 4:
  63473. if (this._defaultModel) {
  63474. if (notifyObject.pressed) {
  63475. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  63476. }
  63477. else {
  63478. (this._defaultModel.getChildren()[2]).position.y = 0;
  63479. }
  63480. }
  63481. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  63482. return;
  63483. case 5:
  63484. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  63485. return;
  63486. }
  63487. };
  63488. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  63489. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  63490. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  63491. return OculusTouchController;
  63492. }(BABYLON.WebVRController));
  63493. BABYLON.OculusTouchController = OculusTouchController;
  63494. })(BABYLON || (BABYLON = {}));
  63495. //# sourceMappingURL=babylon.oculusTouchController.js.map
  63496. var BABYLON;
  63497. (function (BABYLON) {
  63498. var ViveController = /** @class */ (function (_super) {
  63499. __extends(ViveController, _super);
  63500. function ViveController(vrGamepad) {
  63501. var _this = _super.call(this, vrGamepad) || this;
  63502. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  63503. _this._invertLeftStickY = true;
  63504. return _this;
  63505. }
  63506. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  63507. var _this = this;
  63508. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  63509. /*
  63510. Parent Mesh name: ViveWand
  63511. - body
  63512. - r_gripper
  63513. - l_gripper
  63514. - menu_button
  63515. - system_button
  63516. - trackpad
  63517. - trigger
  63518. - LED
  63519. */
  63520. _this._defaultModel = newMeshes[1];
  63521. _this.attachToMesh(_this._defaultModel);
  63522. if (meshLoaded) {
  63523. meshLoaded(_this._defaultModel);
  63524. }
  63525. });
  63526. };
  63527. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  63528. get: function () {
  63529. return this.onMainButtonStateChangedObservable;
  63530. },
  63531. enumerable: true,
  63532. configurable: true
  63533. });
  63534. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  63535. get: function () {
  63536. return this.onMainButtonStateChangedObservable;
  63537. },
  63538. enumerable: true,
  63539. configurable: true
  63540. });
  63541. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  63542. get: function () {
  63543. return this.onSecondaryButtonStateChangedObservable;
  63544. },
  63545. enumerable: true,
  63546. configurable: true
  63547. });
  63548. /**
  63549. * Vive mapping:
  63550. * 0: touchpad
  63551. * 1: trigger
  63552. * 2: left AND right buttons
  63553. * 3: menu button
  63554. */
  63555. ViveController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  63556. var notifyObject = state; //{ state: state, changes: changes };
  63557. switch (buttonIdx) {
  63558. case 0:
  63559. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  63560. return;
  63561. case 1:// index trigger
  63562. if (this._defaultModel) {
  63563. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  63564. }
  63565. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  63566. return;
  63567. case 2:// left AND right button
  63568. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  63569. return;
  63570. case 3:
  63571. if (this._defaultModel) {
  63572. if (notifyObject.pressed) {
  63573. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  63574. }
  63575. else {
  63576. (this._defaultModel.getChildren()[2]).position.y = 0;
  63577. }
  63578. }
  63579. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  63580. return;
  63581. }
  63582. };
  63583. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  63584. ViveController.MODEL_FILENAME = 'wand.babylon';
  63585. return ViveController;
  63586. }(BABYLON.WebVRController));
  63587. BABYLON.ViveController = ViveController;
  63588. })(BABYLON || (BABYLON = {}));
  63589. //# sourceMappingURL=babylon.viveController.js.map
  63590. var BABYLON;
  63591. (function (BABYLON) {
  63592. var GenericController = /** @class */ (function (_super) {
  63593. __extends(GenericController, _super);
  63594. function GenericController(vrGamepad) {
  63595. return _super.call(this, vrGamepad) || this;
  63596. }
  63597. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  63598. var _this = this;
  63599. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  63600. _this._defaultModel = newMeshes[1];
  63601. _this.attachToMesh(_this._defaultModel);
  63602. if (meshLoaded) {
  63603. meshLoaded(_this._defaultModel);
  63604. }
  63605. });
  63606. };
  63607. GenericController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  63608. console.log("Button id: " + buttonIdx + "state: ");
  63609. console.dir(state);
  63610. };
  63611. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  63612. GenericController.MODEL_FILENAME = 'generic.babylon';
  63613. return GenericController;
  63614. }(BABYLON.WebVRController));
  63615. BABYLON.GenericController = GenericController;
  63616. })(BABYLON || (BABYLON = {}));
  63617. //# sourceMappingURL=babylon.genericController.js.map
  63618. var BABYLON;
  63619. (function (BABYLON) {
  63620. var LoadedMeshInfo = /** @class */ (function () {
  63621. function LoadedMeshInfo() {
  63622. this.buttonMeshes = {};
  63623. this.axisMeshes = {};
  63624. }
  63625. return LoadedMeshInfo;
  63626. }());
  63627. var WindowsMotionController = /** @class */ (function (_super) {
  63628. __extends(WindowsMotionController, _super);
  63629. function WindowsMotionController(vrGamepad) {
  63630. var _this = _super.call(this, vrGamepad) || this;
  63631. _this._mapping = {
  63632. // Semantic button names
  63633. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  63634. // A mapping of the button name to glTF model node name
  63635. // that should be transformed by button value.
  63636. buttonMeshNames: {
  63637. 'trigger': 'SELECT',
  63638. 'menu': 'MENU',
  63639. 'grip': 'GRASP',
  63640. 'thumbstick': 'THUMBSTICK_PRESS',
  63641. 'trackpad': 'TOUCHPAD_PRESS'
  63642. },
  63643. // This mapping is used to translate from the Motion Controller to Babylon semantics
  63644. buttonObservableNames: {
  63645. 'trigger': 'onTriggerStateChangedObservable',
  63646. 'menu': 'onSecondaryButtonStateChangedObservable',
  63647. 'grip': 'onMainButtonStateChangedObservable',
  63648. 'thumbstick': 'onPadStateChangedObservable',
  63649. 'trackpad': 'onTrackpadChangedObservable'
  63650. },
  63651. // A mapping of the axis name to glTF model node name
  63652. // that should be transformed by axis value.
  63653. // This array mirrors the browserGamepad.axes array, such that
  63654. // the mesh corresponding to axis 0 is in this array index 0.
  63655. axisMeshNames: [
  63656. 'THUMBSTICK_X',
  63657. 'THUMBSTICK_Y',
  63658. 'TOUCHPAD_TOUCH_X',
  63659. 'TOUCHPAD_TOUCH_Y'
  63660. ],
  63661. pointingPoseMeshName: 'POINTING_POSE'
  63662. };
  63663. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  63664. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  63665. _this.trackpad = { x: 0, y: 0 };
  63666. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  63667. _this._loadedMeshInfo = null;
  63668. return _this;
  63669. }
  63670. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  63671. get: function () {
  63672. return this.onTriggerStateChangedObservable;
  63673. },
  63674. enumerable: true,
  63675. configurable: true
  63676. });
  63677. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  63678. get: function () {
  63679. return this.onSecondaryButtonStateChangedObservable;
  63680. },
  63681. enumerable: true,
  63682. configurable: true
  63683. });
  63684. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  63685. get: function () {
  63686. return this.onMainButtonStateChangedObservable;
  63687. },
  63688. enumerable: true,
  63689. configurable: true
  63690. });
  63691. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  63692. get: function () {
  63693. return this.onPadStateChangedObservable;
  63694. },
  63695. enumerable: true,
  63696. configurable: true
  63697. });
  63698. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  63699. get: function () {
  63700. return this.onTrackpadChangedObservable;
  63701. },
  63702. enumerable: true,
  63703. configurable: true
  63704. });
  63705. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  63706. get: function () {
  63707. return this.onTrackpadValuesChangedObservable;
  63708. },
  63709. enumerable: true,
  63710. configurable: true
  63711. });
  63712. /**
  63713. * Called once per frame by the engine.
  63714. */
  63715. WindowsMotionController.prototype.update = function () {
  63716. _super.prototype.update.call(this);
  63717. // Only need to animate axes if there is a loaded mesh
  63718. if (this._loadedMeshInfo) {
  63719. if (this.browserGamepad.axes) {
  63720. if (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y) {
  63721. this.trackpad.x = this.browserGamepad["axes"][2];
  63722. this.trackpad.y = this.browserGamepad["axes"][3];
  63723. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  63724. }
  63725. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  63726. this.lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  63727. }
  63728. }
  63729. }
  63730. };
  63731. /**
  63732. * Called once for each button that changed state since the last frame
  63733. * @param buttonIdx Which button index changed
  63734. * @param state New state of the button
  63735. * @param changes Which properties on the state changed since last frame
  63736. */
  63737. WindowsMotionController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  63738. var buttonName = this._mapping.buttons[buttonIdx];
  63739. if (!buttonName) {
  63740. return;
  63741. }
  63742. // Only emit events for buttons that we know how to map from index to name
  63743. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  63744. if (observable) {
  63745. observable.notifyObservers(state);
  63746. }
  63747. this.lerpButtonTransform(buttonName, state.value);
  63748. };
  63749. WindowsMotionController.prototype.lerpButtonTransform = function (buttonName, buttonValue) {
  63750. // If there is no loaded mesh, there is nothing to transform.
  63751. if (!this._loadedMeshInfo) {
  63752. return;
  63753. }
  63754. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  63755. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  63756. return;
  63757. }
  63758. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  63759. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  63760. };
  63761. WindowsMotionController.prototype.lerpAxisTransform = function (axis, axisValue) {
  63762. if (!this._loadedMeshInfo) {
  63763. return;
  63764. }
  63765. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  63766. if (!meshInfo) {
  63767. return;
  63768. }
  63769. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  63770. return;
  63771. }
  63772. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  63773. var lerpValue = axisValue * 0.5 + 0.5;
  63774. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  63775. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  63776. };
  63777. /**
  63778. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  63779. * @param scene scene in which to add meshes
  63780. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  63781. */
  63782. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  63783. var _this = this;
  63784. if (forceDefault === void 0) { forceDefault = false; }
  63785. var path;
  63786. var filename;
  63787. // Checking if GLB loader is present
  63788. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  63789. // Determine the device specific folder based on the ID suffix
  63790. var device = 'default';
  63791. if (this.id && !forceDefault) {
  63792. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  63793. device = ((match && match[0]) || device);
  63794. }
  63795. // Hand
  63796. if (this.hand === 'left') {
  63797. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  63798. }
  63799. else {
  63800. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  63801. }
  63802. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  63803. }
  63804. else {
  63805. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  63806. path = BABYLON.GenericController.MODEL_BASE_URL;
  63807. filename = BABYLON.GenericController.MODEL_FILENAME;
  63808. }
  63809. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  63810. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  63811. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  63812. if (!_this._loadedMeshInfo) {
  63813. return;
  63814. }
  63815. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  63816. _this.attachToMesh(_this._defaultModel);
  63817. if (meshLoaded) {
  63818. meshLoaded(_this._defaultModel);
  63819. }
  63820. }, null, function (scene, message) {
  63821. BABYLON.Tools.Log(message);
  63822. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  63823. if (!forceDefault) {
  63824. _this.initControllerMesh(scene, meshLoaded, true);
  63825. }
  63826. });
  63827. };
  63828. /**
  63829. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  63830. * can be transformed by button presses and axes values, based on this._mapping.
  63831. *
  63832. * @param scene scene in which the meshes exist
  63833. * @param meshes list of meshes that make up the controller model to process
  63834. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  63835. */
  63836. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  63837. var loadedMeshInfo = null;
  63838. // Create a new mesh to contain the glTF hierarchy
  63839. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  63840. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  63841. var childMesh = null;
  63842. for (var i = 0; i < meshes.length; i++) {
  63843. var mesh = meshes[i];
  63844. if (!mesh.parent) {
  63845. // Exclude controller meshes from picking results
  63846. mesh.isPickable = false;
  63847. // Handle root node, attach to the new parentMesh
  63848. childMesh = mesh;
  63849. break;
  63850. }
  63851. }
  63852. if (childMesh) {
  63853. childMesh.setParent(parentMesh);
  63854. // Create our mesh info. Note that this method will always return non-null.
  63855. loadedMeshInfo = this.createMeshInfo(parentMesh);
  63856. }
  63857. else {
  63858. BABYLON.Tools.Warn('Could not find root node in model file.');
  63859. }
  63860. return loadedMeshInfo;
  63861. };
  63862. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  63863. var loadedMeshInfo = new LoadedMeshInfo();
  63864. var i;
  63865. loadedMeshInfo.rootNode = rootNode;
  63866. // Reset the caches
  63867. loadedMeshInfo.buttonMeshes = {};
  63868. loadedMeshInfo.axisMeshes = {};
  63869. // Button Meshes
  63870. for (i = 0; i < this._mapping.buttons.length; i++) {
  63871. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  63872. if (!buttonMeshName) {
  63873. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  63874. continue;
  63875. }
  63876. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  63877. if (!buttonMesh) {
  63878. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  63879. continue;
  63880. }
  63881. var buttonMeshInfo = {
  63882. index: i,
  63883. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  63884. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  63885. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  63886. };
  63887. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  63888. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  63889. }
  63890. else {
  63891. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  63892. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  63893. '(VALUE: ' + !!buttonMeshInfo.value +
  63894. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  63895. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  63896. ')');
  63897. }
  63898. }
  63899. // Axis Meshes
  63900. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  63901. var axisMeshName = this._mapping.axisMeshNames[i];
  63902. if (!axisMeshName) {
  63903. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  63904. continue;
  63905. }
  63906. var axisMesh = getChildByName(rootNode, axisMeshName);
  63907. if (!axisMesh) {
  63908. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  63909. continue;
  63910. }
  63911. var axisMeshInfo = {
  63912. index: i,
  63913. value: getImmediateChildByName(axisMesh, 'VALUE'),
  63914. min: getImmediateChildByName(axisMesh, 'MIN'),
  63915. max: getImmediateChildByName(axisMesh, 'MAX')
  63916. };
  63917. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  63918. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  63919. }
  63920. else {
  63921. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  63922. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  63923. '(VALUE: ' + !!axisMeshInfo.value +
  63924. ', MIN: ' + !!axisMeshInfo.min +
  63925. ', MAX:' + !!axisMeshInfo.max +
  63926. ')');
  63927. }
  63928. }
  63929. // Pointing Ray
  63930. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  63931. if (!loadedMeshInfo.pointingPoseNode) {
  63932. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  63933. }
  63934. return loadedMeshInfo;
  63935. // Look through all children recursively. This will return null if no mesh exists with the given name.
  63936. function getChildByName(node, name) {
  63937. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  63938. }
  63939. // Look through only immediate children. This will return null if no mesh exists with the given name.
  63940. function getImmediateChildByName(node, name) {
  63941. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  63942. }
  63943. };
  63944. WindowsMotionController.prototype.getForwardRay = function (length) {
  63945. if (length === void 0) { length = 100; }
  63946. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  63947. return _super.prototype.getForwardRay.call(this, length);
  63948. }
  63949. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  63950. var origin = m.getTranslation();
  63951. var forward = new BABYLON.Vector3(0, 0, -1);
  63952. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  63953. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  63954. return new BABYLON.Ray(origin, direction, length);
  63955. };
  63956. WindowsMotionController.prototype.dispose = function () {
  63957. _super.prototype.dispose.call(this);
  63958. this.onTrackpadChangedObservable.clear();
  63959. };
  63960. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  63961. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  63962. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  63963. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  63964. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  63965. return WindowsMotionController;
  63966. }(BABYLON.WebVRController));
  63967. BABYLON.WindowsMotionController = WindowsMotionController;
  63968. })(BABYLON || (BABYLON = {}));
  63969. //# sourceMappingURL=babylon.windowsMotionController.js.map
  63970. var BABYLON;
  63971. (function (BABYLON) {
  63972. var GearVRController = /** @class */ (function (_super) {
  63973. __extends(GearVRController, _super);
  63974. function GearVRController(vrGamepad) {
  63975. var _this = _super.call(this, vrGamepad) || this;
  63976. _this._buttonIndexToObservableNameMap = [
  63977. 'onTrackpadChangedObservable',
  63978. 'onTriggerStateChangedObservable' // Trigger
  63979. ];
  63980. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  63981. return _this;
  63982. }
  63983. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  63984. var _this = this;
  63985. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  63986. _this._defaultModel = newMeshes[1];
  63987. _this.attachToMesh(_this._defaultModel);
  63988. if (meshLoaded) {
  63989. meshLoaded(_this._defaultModel);
  63990. }
  63991. });
  63992. };
  63993. GearVRController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  63994. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  63995. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  63996. // Only emit events for buttons that we know how to map from index to observable
  63997. var observable = this[observableName];
  63998. if (observable) {
  63999. observable.notifyObservers(state);
  64000. }
  64001. }
  64002. };
  64003. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  64004. GearVRController.MODEL_FILENAME = 'generic.babylon';
  64005. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  64006. return GearVRController;
  64007. }(BABYLON.WebVRController));
  64008. BABYLON.GearVRController = GearVRController;
  64009. })(BABYLON || (BABYLON = {}));
  64010. //# sourceMappingURL=babylon.gearVRController.js.map
  64011. var BABYLON;
  64012. (function (BABYLON) {
  64013. var FollowCamera = /** @class */ (function (_super) {
  64014. __extends(FollowCamera, _super);
  64015. function FollowCamera(name, position, scene, lockedTarget) {
  64016. if (lockedTarget === void 0) { lockedTarget = null; }
  64017. var _this = _super.call(this, name, position, scene) || this;
  64018. _this.radius = 12;
  64019. _this.rotationOffset = 0;
  64020. _this.heightOffset = 4;
  64021. _this.cameraAcceleration = 0.05;
  64022. _this.maxCameraSpeed = 20;
  64023. _this.lockedTarget = lockedTarget;
  64024. return _this;
  64025. }
  64026. FollowCamera.prototype.getRadians = function (degrees) {
  64027. return degrees * Math.PI / 180;
  64028. };
  64029. FollowCamera.prototype.follow = function (cameraTarget) {
  64030. if (!cameraTarget)
  64031. return;
  64032. var yRotation;
  64033. if (cameraTarget.rotationQuaternion) {
  64034. var rotMatrix = new BABYLON.Matrix();
  64035. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  64036. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  64037. }
  64038. else {
  64039. yRotation = cameraTarget.rotation.y;
  64040. }
  64041. var radians = this.getRadians(this.rotationOffset) + yRotation;
  64042. var targetPosition = cameraTarget.getAbsolutePosition();
  64043. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  64044. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  64045. var dx = targetX - this.position.x;
  64046. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  64047. var dz = (targetZ) - this.position.z;
  64048. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  64049. var vy = dy * this.cameraAcceleration;
  64050. var vz = dz * this.cameraAcceleration * 2;
  64051. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  64052. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  64053. }
  64054. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  64055. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  64056. }
  64057. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  64058. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  64059. }
  64060. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  64061. this.setTarget(targetPosition);
  64062. };
  64063. FollowCamera.prototype._checkInputs = function () {
  64064. _super.prototype._checkInputs.call(this);
  64065. if (this.lockedTarget) {
  64066. this.follow(this.lockedTarget);
  64067. }
  64068. };
  64069. FollowCamera.prototype.getClassName = function () {
  64070. return "FollowCamera";
  64071. };
  64072. __decorate([
  64073. BABYLON.serialize()
  64074. ], FollowCamera.prototype, "radius", void 0);
  64075. __decorate([
  64076. BABYLON.serialize()
  64077. ], FollowCamera.prototype, "rotationOffset", void 0);
  64078. __decorate([
  64079. BABYLON.serialize()
  64080. ], FollowCamera.prototype, "heightOffset", void 0);
  64081. __decorate([
  64082. BABYLON.serialize()
  64083. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  64084. __decorate([
  64085. BABYLON.serialize()
  64086. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  64087. __decorate([
  64088. BABYLON.serializeAsMeshReference("lockedTargetId")
  64089. ], FollowCamera.prototype, "lockedTarget", void 0);
  64090. return FollowCamera;
  64091. }(BABYLON.TargetCamera));
  64092. BABYLON.FollowCamera = FollowCamera;
  64093. var ArcFollowCamera = /** @class */ (function (_super) {
  64094. __extends(ArcFollowCamera, _super);
  64095. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  64096. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  64097. _this.alpha = alpha;
  64098. _this.beta = beta;
  64099. _this.radius = radius;
  64100. _this.target = target;
  64101. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  64102. _this.follow();
  64103. return _this;
  64104. }
  64105. ArcFollowCamera.prototype.follow = function () {
  64106. if (!this.target) {
  64107. return;
  64108. }
  64109. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  64110. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  64111. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  64112. var targetPosition = this.target.getAbsolutePosition();
  64113. this.position = targetPosition.add(this._cartesianCoordinates);
  64114. this.setTarget(targetPosition);
  64115. };
  64116. ArcFollowCamera.prototype._checkInputs = function () {
  64117. _super.prototype._checkInputs.call(this);
  64118. this.follow();
  64119. };
  64120. ArcFollowCamera.prototype.getClassName = function () {
  64121. return "ArcFollowCamera";
  64122. };
  64123. return ArcFollowCamera;
  64124. }(BABYLON.TargetCamera));
  64125. BABYLON.ArcFollowCamera = ArcFollowCamera;
  64126. })(BABYLON || (BABYLON = {}));
  64127. //# sourceMappingURL=babylon.followCamera.js.map
  64128. var BABYLON;
  64129. (function (BABYLON) {
  64130. // We're mainly based on the logic defined into the FreeCamera code
  64131. var UniversalCamera = /** @class */ (function (_super) {
  64132. __extends(UniversalCamera, _super);
  64133. //-- end properties for backward compatibility for inputs
  64134. function UniversalCamera(name, position, scene) {
  64135. var _this = _super.call(this, name, position, scene) || this;
  64136. _this.inputs.addGamepad();
  64137. return _this;
  64138. }
  64139. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  64140. //-- Begin properties for backward compatibility for inputs
  64141. get: function () {
  64142. var gamepad = this.inputs.attached["gamepad"];
  64143. if (gamepad)
  64144. return gamepad.gamepadAngularSensibility;
  64145. return 0;
  64146. },
  64147. set: function (value) {
  64148. var gamepad = this.inputs.attached["gamepad"];
  64149. if (gamepad)
  64150. gamepad.gamepadAngularSensibility = value;
  64151. },
  64152. enumerable: true,
  64153. configurable: true
  64154. });
  64155. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  64156. get: function () {
  64157. var gamepad = this.inputs.attached["gamepad"];
  64158. if (gamepad)
  64159. return gamepad.gamepadMoveSensibility;
  64160. return 0;
  64161. },
  64162. set: function (value) {
  64163. var gamepad = this.inputs.attached["gamepad"];
  64164. if (gamepad)
  64165. gamepad.gamepadMoveSensibility = value;
  64166. },
  64167. enumerable: true,
  64168. configurable: true
  64169. });
  64170. UniversalCamera.prototype.getClassName = function () {
  64171. return "UniversalCamera";
  64172. };
  64173. return UniversalCamera;
  64174. }(BABYLON.TouchCamera));
  64175. BABYLON.UniversalCamera = UniversalCamera;
  64176. })(BABYLON || (BABYLON = {}));
  64177. //# sourceMappingURL=babylon.universalCamera.js.map
  64178. var BABYLON;
  64179. (function (BABYLON) {
  64180. // We're mainly based on the logic defined into the FreeCamera code
  64181. var GamepadCamera = /** @class */ (function (_super) {
  64182. __extends(GamepadCamera, _super);
  64183. //-- end properties for backward compatibility for inputs
  64184. function GamepadCamera(name, position, scene) {
  64185. return _super.call(this, name, position, scene) || this;
  64186. }
  64187. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  64188. //-- Begin properties for backward compatibility for inputs
  64189. get: function () {
  64190. var gamepad = this.inputs.attached["gamepad"];
  64191. if (gamepad)
  64192. return gamepad.gamepadAngularSensibility;
  64193. return 0;
  64194. },
  64195. set: function (value) {
  64196. var gamepad = this.inputs.attached["gamepad"];
  64197. if (gamepad)
  64198. gamepad.gamepadAngularSensibility = value;
  64199. },
  64200. enumerable: true,
  64201. configurable: true
  64202. });
  64203. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  64204. get: function () {
  64205. var gamepad = this.inputs.attached["gamepad"];
  64206. if (gamepad)
  64207. return gamepad.gamepadMoveSensibility;
  64208. return 0;
  64209. },
  64210. set: function (value) {
  64211. var gamepad = this.inputs.attached["gamepad"];
  64212. if (gamepad)
  64213. gamepad.gamepadMoveSensibility = value;
  64214. },
  64215. enumerable: true,
  64216. configurable: true
  64217. });
  64218. GamepadCamera.prototype.getClassName = function () {
  64219. return "GamepadCamera";
  64220. };
  64221. return GamepadCamera;
  64222. }(BABYLON.UniversalCamera));
  64223. BABYLON.GamepadCamera = GamepadCamera;
  64224. })(BABYLON || (BABYLON = {}));
  64225. //# sourceMappingURL=babylon.gamepadCamera.js.map
  64226. var BABYLON;
  64227. (function (BABYLON) {
  64228. var PostProcessRenderPipelineManager = /** @class */ (function () {
  64229. function PostProcessRenderPipelineManager() {
  64230. this._renderPipelines = {};
  64231. }
  64232. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  64233. this._renderPipelines[renderPipeline._name] = renderPipeline;
  64234. };
  64235. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  64236. if (unique === void 0) { unique = false; }
  64237. var renderPipeline = this._renderPipelines[renderPipelineName];
  64238. if (!renderPipeline) {
  64239. return;
  64240. }
  64241. renderPipeline._attachCameras(cameras, unique);
  64242. };
  64243. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  64244. var renderPipeline = this._renderPipelines[renderPipelineName];
  64245. if (!renderPipeline) {
  64246. return;
  64247. }
  64248. renderPipeline._detachCameras(cameras);
  64249. };
  64250. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  64251. var renderPipeline = this._renderPipelines[renderPipelineName];
  64252. if (!renderPipeline) {
  64253. return;
  64254. }
  64255. renderPipeline._enableEffect(renderEffectName, cameras);
  64256. };
  64257. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  64258. var renderPipeline = this._renderPipelines[renderPipelineName];
  64259. if (!renderPipeline) {
  64260. return;
  64261. }
  64262. renderPipeline._disableEffect(renderEffectName, cameras);
  64263. };
  64264. PostProcessRenderPipelineManager.prototype.update = function () {
  64265. for (var renderPipelineName in this._renderPipelines) {
  64266. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  64267. var pipeline = this._renderPipelines[renderPipelineName];
  64268. if (!pipeline.isSupported) {
  64269. pipeline.dispose();
  64270. delete this._renderPipelines[renderPipelineName];
  64271. }
  64272. else {
  64273. pipeline._update();
  64274. }
  64275. }
  64276. }
  64277. };
  64278. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  64279. for (var renderPipelineName in this._renderPipelines) {
  64280. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  64281. var pipeline = this._renderPipelines[renderPipelineName];
  64282. pipeline._rebuild();
  64283. }
  64284. }
  64285. };
  64286. PostProcessRenderPipelineManager.prototype.dispose = function () {
  64287. for (var renderPipelineName in this._renderPipelines) {
  64288. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  64289. var pipeline = this._renderPipelines[renderPipelineName];
  64290. pipeline.dispose();
  64291. }
  64292. }
  64293. };
  64294. return PostProcessRenderPipelineManager;
  64295. }());
  64296. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  64297. })(BABYLON || (BABYLON = {}));
  64298. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  64299. var BABYLON;
  64300. (function (BABYLON) {
  64301. /**
  64302. * This represents a set of one or more post processes in Babylon.
  64303. * A post process can be used to apply a shader to a texture after it is rendered.
  64304. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  64305. */
  64306. var PostProcessRenderEffect = /** @class */ (function () {
  64307. /**
  64308. * Instantiates a post process render effect.
  64309. * A post process can be used to apply a shader to a texture after it is rendered.
  64310. * @param engine The engine the effect is tied to
  64311. * @param name The name of the effect
  64312. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  64313. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  64314. */
  64315. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  64316. this._name = name;
  64317. this._singleInstance = singleInstance || true;
  64318. this._getPostProcesses = getPostProcesses;
  64319. this._cameras = {};
  64320. this._indicesForCamera = {};
  64321. this._postProcesses = {};
  64322. }
  64323. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  64324. /**
  64325. * Checks if all the post processes in the effect are supported.
  64326. */
  64327. get: function () {
  64328. for (var index in this._postProcesses) {
  64329. for (var ppIndex in this._postProcesses[index]) {
  64330. if (!this._postProcesses[index][ppIndex].isSupported) {
  64331. return false;
  64332. }
  64333. }
  64334. }
  64335. return true;
  64336. },
  64337. enumerable: true,
  64338. configurable: true
  64339. });
  64340. /**
  64341. * Updates the current state of the effect
  64342. */
  64343. PostProcessRenderEffect.prototype._update = function () {
  64344. };
  64345. /**
  64346. * Attaches the effect on cameras
  64347. * @param cameras The camera to attach to.
  64348. */
  64349. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  64350. var _this = this;
  64351. var cameraKey;
  64352. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  64353. if (!cams) {
  64354. return;
  64355. }
  64356. for (var i = 0; i < cams.length; i++) {
  64357. var camera = cams[i];
  64358. var cameraName = camera.name;
  64359. if (this._singleInstance) {
  64360. cameraKey = 0;
  64361. }
  64362. else {
  64363. cameraKey = cameraName;
  64364. }
  64365. if (!this._postProcesses[cameraKey]) {
  64366. var postProcess = this._getPostProcesses();
  64367. if (postProcess) {
  64368. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  64369. }
  64370. }
  64371. if (!this._indicesForCamera[cameraName]) {
  64372. this._indicesForCamera[cameraName] = [];
  64373. }
  64374. this._postProcesses[cameraKey].forEach(function (postProcess) {
  64375. var index = camera.attachPostProcess(postProcess);
  64376. _this._indicesForCamera[cameraName].push(index);
  64377. });
  64378. if (!this._cameras[cameraName]) {
  64379. this._cameras[cameraName] = camera;
  64380. }
  64381. }
  64382. };
  64383. /**
  64384. * Detatches the effect on cameras
  64385. * @param cameras The camera to detatch from.
  64386. */
  64387. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  64388. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  64389. if (!cams) {
  64390. return;
  64391. }
  64392. for (var i = 0; i < cams.length; i++) {
  64393. var camera = cams[i];
  64394. var cameraName = camera.name;
  64395. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  64396. camera.detachPostProcess(postProcess);
  64397. });
  64398. if (this._cameras[cameraName]) {
  64399. //this._indicesForCamera.splice(index, 1);
  64400. this._cameras[cameraName] = null;
  64401. }
  64402. }
  64403. };
  64404. /**
  64405. * Enables the effect on given cameras
  64406. * @param cameras The camera to enable.
  64407. */
  64408. PostProcessRenderEffect.prototype._enable = function (cameras) {
  64409. var _this = this;
  64410. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  64411. if (!cams) {
  64412. return;
  64413. }
  64414. for (var i = 0; i < cams.length; i++) {
  64415. var camera = cams[i];
  64416. var cameraName = camera.name;
  64417. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  64418. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  64419. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  64420. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  64421. });
  64422. }
  64423. }
  64424. }
  64425. };
  64426. /**
  64427. * Disables the effect on the given cameras
  64428. * @param cameras The camera to disable.
  64429. */
  64430. PostProcessRenderEffect.prototype._disable = function (cameras) {
  64431. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  64432. if (!cams) {
  64433. return;
  64434. }
  64435. for (var i = 0; i < cams.length; i++) {
  64436. var camera = cams[i];
  64437. var cameraName = camera.name;
  64438. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  64439. camera.detachPostProcess(postProcess);
  64440. });
  64441. }
  64442. };
  64443. /**
  64444. * Gets a list of the post processes contained in the effect.
  64445. * @param camera The camera to get the post processes on.
  64446. * @returns The list of the post processes in the effect.
  64447. */
  64448. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  64449. if (this._singleInstance) {
  64450. return this._postProcesses[0];
  64451. }
  64452. else {
  64453. if (!camera) {
  64454. return null;
  64455. }
  64456. return this._postProcesses[camera.name];
  64457. }
  64458. };
  64459. return PostProcessRenderEffect;
  64460. }());
  64461. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  64462. })(BABYLON || (BABYLON = {}));
  64463. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  64464. var BABYLON;
  64465. (function (BABYLON) {
  64466. var PostProcessRenderPipeline = /** @class */ (function () {
  64467. function PostProcessRenderPipeline(engine, name) {
  64468. this._name = name;
  64469. this._renderEffects = {};
  64470. this._renderEffectsForIsolatedPass = new Array();
  64471. this._cameras = [];
  64472. }
  64473. PostProcessRenderPipeline.prototype.getClassName = function () {
  64474. return "PostProcessRenderPipeline";
  64475. };
  64476. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  64477. get: function () {
  64478. for (var renderEffectName in this._renderEffects) {
  64479. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  64480. if (!this._renderEffects[renderEffectName].isSupported) {
  64481. return false;
  64482. }
  64483. }
  64484. }
  64485. return true;
  64486. },
  64487. enumerable: true,
  64488. configurable: true
  64489. });
  64490. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  64491. this._renderEffects[renderEffect._name] = renderEffect;
  64492. };
  64493. // private
  64494. PostProcessRenderPipeline.prototype._rebuild = function () {
  64495. };
  64496. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  64497. var renderEffects = this._renderEffects[renderEffectName];
  64498. if (!renderEffects) {
  64499. return;
  64500. }
  64501. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  64502. };
  64503. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  64504. var renderEffects = this._renderEffects[renderEffectName];
  64505. if (!renderEffects) {
  64506. return;
  64507. }
  64508. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  64509. };
  64510. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  64511. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  64512. if (!cams) {
  64513. return;
  64514. }
  64515. var indicesToDelete = [];
  64516. var i;
  64517. for (i = 0; i < cams.length; i++) {
  64518. var camera = cams[i];
  64519. var cameraName = camera.name;
  64520. if (this._cameras.indexOf(camera) === -1) {
  64521. this._cameras[cameraName] = camera;
  64522. }
  64523. else if (unique) {
  64524. indicesToDelete.push(i);
  64525. }
  64526. }
  64527. for (i = 0; i < indicesToDelete.length; i++) {
  64528. cameras.splice(indicesToDelete[i], 1);
  64529. }
  64530. for (var renderEffectName in this._renderEffects) {
  64531. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  64532. this._renderEffects[renderEffectName]._attachCameras(cams);
  64533. }
  64534. }
  64535. };
  64536. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  64537. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  64538. if (!cams) {
  64539. return;
  64540. }
  64541. for (var renderEffectName in this._renderEffects) {
  64542. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  64543. this._renderEffects[renderEffectName]._detachCameras(cams);
  64544. }
  64545. }
  64546. for (var i = 0; i < cams.length; i++) {
  64547. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  64548. }
  64549. };
  64550. PostProcessRenderPipeline.prototype._update = function () {
  64551. for (var renderEffectName in this._renderEffects) {
  64552. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  64553. this._renderEffects[renderEffectName]._update();
  64554. }
  64555. }
  64556. for (var i = 0; i < this._cameras.length; i++) {
  64557. var cameraName = this._cameras[i].name;
  64558. if (this._renderEffectsForIsolatedPass[cameraName]) {
  64559. this._renderEffectsForIsolatedPass[cameraName]._update();
  64560. }
  64561. }
  64562. };
  64563. PostProcessRenderPipeline.prototype._reset = function () {
  64564. this._renderEffects = {};
  64565. this._renderEffectsForIsolatedPass = new Array();
  64566. };
  64567. PostProcessRenderPipeline.prototype.dispose = function () {
  64568. // Must be implemented by children
  64569. };
  64570. __decorate([
  64571. BABYLON.serialize()
  64572. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  64573. return PostProcessRenderPipeline;
  64574. }());
  64575. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  64576. })(BABYLON || (BABYLON = {}));
  64577. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  64578. var BABYLON;
  64579. (function (BABYLON) {
  64580. var DepthRenderer = /** @class */ (function () {
  64581. function DepthRenderer(scene, type) {
  64582. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  64583. var _this = this;
  64584. this._scene = scene;
  64585. var engine = scene.getEngine();
  64586. // Render target
  64587. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  64588. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64589. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64590. this._depthMap.refreshRate = 1;
  64591. this._depthMap.renderParticles = false;
  64592. this._depthMap.renderList = null;
  64593. // set default depth value to 1.0 (far away)
  64594. this._depthMap.onClearObservable.add(function (engine) {
  64595. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  64596. });
  64597. // Custom render function
  64598. var renderSubMesh = function (subMesh) {
  64599. var mesh = subMesh.getRenderingMesh();
  64600. var scene = _this._scene;
  64601. var engine = scene.getEngine();
  64602. var material = subMesh.getMaterial();
  64603. if (!material) {
  64604. return;
  64605. }
  64606. // Culling and reverse (right handed system)
  64607. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  64608. // Managing instances
  64609. var batch = mesh._getInstancesRenderList(subMesh._id);
  64610. if (batch.mustReturn) {
  64611. return;
  64612. }
  64613. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  64614. if (_this.isReady(subMesh, hardwareInstancedRendering) && scene.activeCamera) {
  64615. engine.enableEffect(_this._effect);
  64616. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  64617. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  64618. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.minZ + scene.activeCamera.maxZ);
  64619. // Alpha test
  64620. if (material && material.needAlphaTesting()) {
  64621. var alphaTexture = material.getAlphaTestTexture();
  64622. if (alphaTexture) {
  64623. _this._effect.setTexture("diffuseSampler", alphaTexture);
  64624. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  64625. }
  64626. }
  64627. // Bones
  64628. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  64629. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  64630. }
  64631. // Draw
  64632. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  64633. }
  64634. };
  64635. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  64636. var index;
  64637. if (depthOnlySubMeshes.length) {
  64638. engine.setColorWrite(false);
  64639. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  64640. renderSubMesh(depthOnlySubMeshes.data[index]);
  64641. }
  64642. engine.setColorWrite(true);
  64643. }
  64644. for (index = 0; index < opaqueSubMeshes.length; index++) {
  64645. renderSubMesh(opaqueSubMeshes.data[index]);
  64646. }
  64647. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  64648. renderSubMesh(alphaTestSubMeshes.data[index]);
  64649. }
  64650. };
  64651. }
  64652. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  64653. var material = subMesh.getMaterial();
  64654. if (material.disableDepthWrite) {
  64655. return false;
  64656. }
  64657. var defines = [];
  64658. var attribs = [BABYLON.VertexBuffer.PositionKind];
  64659. var mesh = subMesh.getMesh();
  64660. // Alpha test
  64661. if (material && material.needAlphaTesting()) {
  64662. defines.push("#define ALPHATEST");
  64663. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  64664. attribs.push(BABYLON.VertexBuffer.UVKind);
  64665. defines.push("#define UV1");
  64666. }
  64667. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  64668. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  64669. defines.push("#define UV2");
  64670. }
  64671. }
  64672. // Bones
  64673. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  64674. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  64675. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  64676. if (mesh.numBoneInfluencers > 4) {
  64677. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  64678. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  64679. }
  64680. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  64681. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  64682. }
  64683. else {
  64684. defines.push("#define NUM_BONE_INFLUENCERS 0");
  64685. }
  64686. // Instances
  64687. if (useInstances) {
  64688. defines.push("#define INSTANCES");
  64689. attribs.push("world0");
  64690. attribs.push("world1");
  64691. attribs.push("world2");
  64692. attribs.push("world3");
  64693. }
  64694. // Get correct effect
  64695. var join = defines.join("\n");
  64696. if (this._cachedDefines !== join) {
  64697. this._cachedDefines = join;
  64698. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  64699. }
  64700. return this._effect.isReady();
  64701. };
  64702. DepthRenderer.prototype.getDepthMap = function () {
  64703. return this._depthMap;
  64704. };
  64705. // Methods
  64706. DepthRenderer.prototype.dispose = function () {
  64707. this._depthMap.dispose();
  64708. };
  64709. return DepthRenderer;
  64710. }());
  64711. BABYLON.DepthRenderer = DepthRenderer;
  64712. })(BABYLON || (BABYLON = {}));
  64713. //# sourceMappingURL=babylon.depthRenderer.js.map
  64714. var BABYLON;
  64715. (function (BABYLON) {
  64716. var SSAORenderingPipeline = /** @class */ (function (_super) {
  64717. __extends(SSAORenderingPipeline, _super);
  64718. /**
  64719. * @constructor
  64720. * @param {string} name - The rendering pipeline name
  64721. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  64722. * @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 }
  64723. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  64724. */
  64725. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  64726. var _this = _super.call(this, scene.getEngine(), name) || this;
  64727. // Members
  64728. /**
  64729. * The PassPostProcess id in the pipeline that contains the original scene color
  64730. * @type {string}
  64731. */
  64732. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  64733. /**
  64734. * The SSAO PostProcess id in the pipeline
  64735. * @type {string}
  64736. */
  64737. _this.SSAORenderEffect = "SSAORenderEffect";
  64738. /**
  64739. * The horizontal blur PostProcess id in the pipeline
  64740. * @type {string}
  64741. */
  64742. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  64743. /**
  64744. * The vertical blur PostProcess id in the pipeline
  64745. * @type {string}
  64746. */
  64747. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  64748. /**
  64749. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  64750. * @type {string}
  64751. */
  64752. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  64753. /**
  64754. * The output strength of the SSAO post-process. Default value is 1.0.
  64755. * @type {number}
  64756. */
  64757. _this.totalStrength = 1.0;
  64758. /**
  64759. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  64760. * @type {number}
  64761. */
  64762. _this.radius = 0.0001;
  64763. /**
  64764. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  64765. * Must not be equal to fallOff and superior to fallOff.
  64766. * Default value is 0.975
  64767. * @type {number}
  64768. */
  64769. _this.area = 0.0075;
  64770. /**
  64771. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  64772. * Must not be equal to area and inferior to area.
  64773. * Default value is 0.0
  64774. * @type {number}
  64775. */
  64776. _this.fallOff = 0.000001;
  64777. /**
  64778. * The base color of the SSAO post-process
  64779. * The final result is "base + ssao" between [0, 1]
  64780. * @type {number}
  64781. */
  64782. _this.base = 0.5;
  64783. _this._firstUpdate = true;
  64784. _this._scene = scene;
  64785. // Set up assets
  64786. _this._createRandomTexture();
  64787. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  64788. var ssaoRatio = ratio.ssaoRatio || ratio;
  64789. var combineRatio = ratio.combineRatio || ratio;
  64790. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  64791. _this._createSSAOPostProcess(ssaoRatio);
  64792. _this._createBlurPostProcess(ssaoRatio);
  64793. _this._createSSAOCombinePostProcess(combineRatio);
  64794. // Set up pipeline
  64795. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  64796. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  64797. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  64798. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  64799. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  64800. // Finish
  64801. scene.postProcessRenderPipelineManager.addPipeline(_this);
  64802. if (cameras)
  64803. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  64804. return _this;
  64805. }
  64806. // Public Methods
  64807. /**
  64808. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  64809. */
  64810. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  64811. if (disableDepthRender === void 0) { disableDepthRender = false; }
  64812. for (var i = 0; i < this._scene.cameras.length; i++) {
  64813. var camera = this._scene.cameras[i];
  64814. this._originalColorPostProcess.dispose(camera);
  64815. this._ssaoPostProcess.dispose(camera);
  64816. this._blurHPostProcess.dispose(camera);
  64817. this._blurVPostProcess.dispose(camera);
  64818. this._ssaoCombinePostProcess.dispose(camera);
  64819. }
  64820. this._randomTexture.dispose();
  64821. if (disableDepthRender)
  64822. this._scene.disableDepthRenderer();
  64823. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  64824. _super.prototype.dispose.call(this);
  64825. };
  64826. // Private Methods
  64827. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  64828. var _this = this;
  64829. var size = 16;
  64830. 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);
  64831. 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);
  64832. this._blurHPostProcess.onActivateObservable.add(function () {
  64833. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  64834. _this._blurHPostProcess.kernel = size * dw;
  64835. });
  64836. this._blurVPostProcess.onActivateObservable.add(function () {
  64837. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  64838. _this._blurVPostProcess.kernel = size * dw;
  64839. });
  64840. };
  64841. SSAORenderingPipeline.prototype._rebuild = function () {
  64842. this._firstUpdate = true;
  64843. _super.prototype._rebuild.call(this);
  64844. };
  64845. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  64846. var _this = this;
  64847. var numSamples = 16;
  64848. var sampleSphere = [
  64849. 0.5381, 0.1856, -0.4319,
  64850. 0.1379, 0.2486, 0.4430,
  64851. 0.3371, 0.5679, -0.0057,
  64852. -0.6999, -0.0451, -0.0019,
  64853. 0.0689, -0.1598, -0.8547,
  64854. 0.0560, 0.0069, -0.1843,
  64855. -0.0146, 0.1402, 0.0762,
  64856. 0.0100, -0.1924, -0.0344,
  64857. -0.3577, -0.5301, -0.4358,
  64858. -0.3169, 0.1063, 0.0158,
  64859. 0.0103, -0.5869, 0.0046,
  64860. -0.0897, -0.4940, 0.3287,
  64861. 0.7119, -0.0154, -0.0918,
  64862. -0.0533, 0.0596, -0.5411,
  64863. 0.0352, -0.0631, 0.5460,
  64864. -0.4776, 0.2847, -0.0271
  64865. ];
  64866. var samplesFactor = 1.0 / numSamples;
  64867. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  64868. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  64869. "area", "fallOff", "base", "range", "viewport"
  64870. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  64871. this._ssaoPostProcess.onApply = function (effect) {
  64872. if (_this._firstUpdate) {
  64873. effect.setArray3("sampleSphere", sampleSphere);
  64874. effect.setFloat("samplesFactor", samplesFactor);
  64875. effect.setFloat("randTextureTiles", 4.0);
  64876. }
  64877. effect.setFloat("totalStrength", _this.totalStrength);
  64878. effect.setFloat("radius", _this.radius);
  64879. effect.setFloat("area", _this.area);
  64880. effect.setFloat("fallOff", _this.fallOff);
  64881. effect.setFloat("base", _this.base);
  64882. effect.setTexture("textureSampler", _this._depthTexture);
  64883. effect.setTexture("randomSampler", _this._randomTexture);
  64884. };
  64885. };
  64886. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  64887. var _this = this;
  64888. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  64889. this._ssaoCombinePostProcess.onApply = function (effect) {
  64890. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  64891. };
  64892. };
  64893. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  64894. var size = 512;
  64895. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  64896. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  64897. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  64898. var context = this._randomTexture.getContext();
  64899. var rand = function (min, max) {
  64900. return Math.random() * (max - min) + min;
  64901. };
  64902. var randVector = BABYLON.Vector3.Zero();
  64903. for (var x = 0; x < size; x++) {
  64904. for (var y = 0; y < size; y++) {
  64905. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  64906. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  64907. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  64908. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  64909. context.fillRect(x, y, 1, 1);
  64910. }
  64911. }
  64912. this._randomTexture.update(false);
  64913. };
  64914. __decorate([
  64915. BABYLON.serialize()
  64916. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  64917. __decorate([
  64918. BABYLON.serialize()
  64919. ], SSAORenderingPipeline.prototype, "radius", void 0);
  64920. __decorate([
  64921. BABYLON.serialize()
  64922. ], SSAORenderingPipeline.prototype, "area", void 0);
  64923. __decorate([
  64924. BABYLON.serialize()
  64925. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  64926. __decorate([
  64927. BABYLON.serialize()
  64928. ], SSAORenderingPipeline.prototype, "base", void 0);
  64929. return SSAORenderingPipeline;
  64930. }(BABYLON.PostProcessRenderPipeline));
  64931. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  64932. })(BABYLON || (BABYLON = {}));
  64933. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  64934. var BABYLON;
  64935. (function (BABYLON) {
  64936. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  64937. __extends(SSAO2RenderingPipeline, _super);
  64938. /**
  64939. * @constructor
  64940. * @param {string} name - The rendering pipeline name
  64941. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  64942. * @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 }
  64943. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  64944. */
  64945. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  64946. var _this = _super.call(this, scene.getEngine(), name) || this;
  64947. // Members
  64948. /**
  64949. * The PassPostProcess id in the pipeline that contains the original scene color
  64950. * @type {string}
  64951. */
  64952. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  64953. /**
  64954. * The SSAO PostProcess id in the pipeline
  64955. * @type {string}
  64956. */
  64957. _this.SSAORenderEffect = "SSAORenderEffect";
  64958. /**
  64959. * The horizontal blur PostProcess id in the pipeline
  64960. * @type {string}
  64961. */
  64962. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  64963. /**
  64964. * The vertical blur PostProcess id in the pipeline
  64965. * @type {string}
  64966. */
  64967. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  64968. /**
  64969. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  64970. * @type {string}
  64971. */
  64972. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  64973. /**
  64974. * The output strength of the SSAO post-process. Default value is 1.0.
  64975. * @type {number}
  64976. */
  64977. _this.totalStrength = 1.0;
  64978. /**
  64979. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  64980. * @type {number}
  64981. */
  64982. _this.maxZ = 100.0;
  64983. /**
  64984. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  64985. * @type {number}
  64986. */
  64987. _this.minZAspect = 0.2;
  64988. /**
  64989. * Number of samples used for the SSAO calculations. Default value is 8
  64990. * @type {number}
  64991. */
  64992. _this._samples = 8;
  64993. /**
  64994. * Are we using bilateral blur ?
  64995. * @type {boolean}
  64996. */
  64997. _this._expensiveBlur = true;
  64998. /**
  64999. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  65000. * @type {number}
  65001. */
  65002. _this.radius = 2.0;
  65003. /**
  65004. * The base color of the SSAO post-process
  65005. * The final result is "base + ssao" between [0, 1]
  65006. * @type {number}
  65007. */
  65008. _this.base = 0.1;
  65009. _this._firstUpdate = true;
  65010. _this._scene = scene;
  65011. if (!_this.isSupported) {
  65012. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  65013. return _this;
  65014. }
  65015. var ssaoRatio = ratio.ssaoRatio || ratio;
  65016. var blurRatio = ratio.blurRatio || ratio;
  65017. // Set up assets
  65018. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  65019. _this._createRandomTexture();
  65020. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  65021. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  65022. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  65023. _this._createSSAOPostProcess(1.0);
  65024. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  65025. _this._createSSAOCombinePostProcess(blurRatio);
  65026. // Set up pipeline
  65027. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  65028. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  65029. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  65030. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  65031. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  65032. // Finish
  65033. scene.postProcessRenderPipelineManager.addPipeline(_this);
  65034. if (cameras)
  65035. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  65036. return _this;
  65037. }
  65038. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  65039. get: function () {
  65040. return this._samples;
  65041. },
  65042. set: function (n) {
  65043. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  65044. this._samples = n;
  65045. this._sampleSphere = this._generateHemisphere();
  65046. this._firstUpdate = true;
  65047. },
  65048. enumerable: true,
  65049. configurable: true
  65050. });
  65051. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  65052. get: function () {
  65053. return this._expensiveBlur;
  65054. },
  65055. set: function (b) {
  65056. 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"]);
  65057. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  65058. this._expensiveBlur = b;
  65059. this._firstUpdate = true;
  65060. },
  65061. enumerable: true,
  65062. configurable: true
  65063. });
  65064. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  65065. /**
  65066. * Support test.
  65067. * @type {boolean}
  65068. */
  65069. get: function () {
  65070. var engine = BABYLON.Engine.LastCreatedEngine;
  65071. if (!engine) {
  65072. return false;
  65073. }
  65074. return engine.getCaps().drawBuffersExtension;
  65075. },
  65076. enumerable: true,
  65077. configurable: true
  65078. });
  65079. // Public Methods
  65080. /**
  65081. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  65082. */
  65083. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  65084. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  65085. for (var i = 0; i < this._scene.cameras.length; i++) {
  65086. var camera = this._scene.cameras[i];
  65087. this._originalColorPostProcess.dispose(camera);
  65088. this._ssaoPostProcess.dispose(camera);
  65089. this._blurHPostProcess.dispose(camera);
  65090. this._blurVPostProcess.dispose(camera);
  65091. this._ssaoCombinePostProcess.dispose(camera);
  65092. }
  65093. this._randomTexture.dispose();
  65094. if (disableGeometryBufferRenderer)
  65095. this._scene.disableGeometryBufferRenderer();
  65096. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  65097. _super.prototype.dispose.call(this);
  65098. };
  65099. // Private Methods
  65100. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  65101. var _this = this;
  65102. this._samplerOffsets = [];
  65103. var expensive = this.expensiveBlur;
  65104. for (var i = -8; i < 8; i++) {
  65105. this._samplerOffsets.push(i * 2 + 0.5);
  65106. }
  65107. 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");
  65108. this._blurHPostProcess.onApply = function (effect) {
  65109. if (!_this._scene.activeCamera) {
  65110. return;
  65111. }
  65112. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  65113. effect.setFloat("near", _this._scene.activeCamera.minZ);
  65114. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  65115. effect.setFloat("radius", _this.radius);
  65116. effect.setTexture("depthSampler", _this._depthTexture);
  65117. if (_this._firstUpdate) {
  65118. effect.setArray("samplerOffsets", _this._samplerOffsets);
  65119. }
  65120. };
  65121. 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");
  65122. this._blurVPostProcess.onApply = function (effect) {
  65123. if (!_this._scene.activeCamera) {
  65124. return;
  65125. }
  65126. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  65127. effect.setFloat("near", _this._scene.activeCamera.minZ);
  65128. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  65129. effect.setFloat("radius", _this.radius);
  65130. effect.setTexture("depthSampler", _this._depthTexture);
  65131. if (_this._firstUpdate) {
  65132. effect.setArray("samplerOffsets", _this._samplerOffsets);
  65133. _this._firstUpdate = false;
  65134. }
  65135. };
  65136. };
  65137. SSAO2RenderingPipeline.prototype._rebuild = function () {
  65138. this._firstUpdate = true;
  65139. _super.prototype._rebuild.call(this);
  65140. };
  65141. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  65142. var numSamples = this.samples;
  65143. var result = [];
  65144. var vector, scale;
  65145. var rand = function (min, max) {
  65146. return Math.random() * (max - min) + min;
  65147. };
  65148. var i = 0;
  65149. while (i < numSamples) {
  65150. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  65151. vector.normalize();
  65152. scale = i / numSamples;
  65153. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  65154. vector.scaleInPlace(scale);
  65155. result.push(vector.x, vector.y, vector.z);
  65156. i++;
  65157. }
  65158. return result;
  65159. };
  65160. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  65161. var _this = this;
  65162. var numSamples = this.samples;
  65163. this._sampleSphere = this._generateHemisphere();
  65164. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  65165. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  65166. "base", "range", "projection", "near", "far", "texelSize",
  65167. "xViewport", "yViewport", "maxZ", "minZAspect"
  65168. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  65169. this._ssaoPostProcess.onApply = function (effect) {
  65170. if (_this._firstUpdate) {
  65171. effect.setArray3("sampleSphere", _this._sampleSphere);
  65172. effect.setFloat("randTextureTiles", 4.0);
  65173. }
  65174. if (!_this._scene.activeCamera) {
  65175. return;
  65176. }
  65177. effect.setFloat("samplesFactor", 1 / _this.samples);
  65178. effect.setFloat("totalStrength", _this.totalStrength);
  65179. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  65180. effect.setFloat("radius", _this.radius);
  65181. effect.setFloat("maxZ", _this.maxZ);
  65182. effect.setFloat("minZAspect", _this.minZAspect);
  65183. effect.setFloat("base", _this.base);
  65184. effect.setFloat("near", _this._scene.activeCamera.minZ);
  65185. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  65186. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  65187. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  65188. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  65189. effect.setTexture("textureSampler", _this._depthTexture);
  65190. effect.setTexture("normalSampler", _this._normalTexture);
  65191. effect.setTexture("randomSampler", _this._randomTexture);
  65192. };
  65193. };
  65194. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  65195. var _this = this;
  65196. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  65197. this._ssaoCombinePostProcess.onApply = function (effect) {
  65198. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  65199. };
  65200. };
  65201. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  65202. var size = 512;
  65203. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  65204. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  65205. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  65206. var context = this._randomTexture.getContext();
  65207. var rand = function (min, max) {
  65208. return Math.random() * (max - min) + min;
  65209. };
  65210. var randVector = BABYLON.Vector3.Zero();
  65211. for (var x = 0; x < size; x++) {
  65212. for (var y = 0; y < size; y++) {
  65213. randVector.x = rand(0.0, 1.0);
  65214. randVector.y = rand(0.0, 1.0);
  65215. randVector.z = 0.0;
  65216. randVector.normalize();
  65217. randVector.scaleInPlace(255);
  65218. randVector.x = Math.floor(randVector.x);
  65219. randVector.y = Math.floor(randVector.y);
  65220. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  65221. context.fillRect(x, y, 1, 1);
  65222. }
  65223. }
  65224. this._randomTexture.update(false);
  65225. };
  65226. __decorate([
  65227. BABYLON.serialize()
  65228. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  65229. __decorate([
  65230. BABYLON.serialize()
  65231. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  65232. __decorate([
  65233. BABYLON.serialize()
  65234. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  65235. __decorate([
  65236. BABYLON.serialize("samples")
  65237. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  65238. __decorate([
  65239. BABYLON.serialize("expensiveBlur")
  65240. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  65241. __decorate([
  65242. BABYLON.serialize()
  65243. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  65244. __decorate([
  65245. BABYLON.serialize()
  65246. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  65247. return SSAO2RenderingPipeline;
  65248. }(BABYLON.PostProcessRenderPipeline));
  65249. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  65250. })(BABYLON || (BABYLON = {}));
  65251. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  65252. // BABYLON.JS Chromatic Aberration GLSL Shader
  65253. // Author: Olivier Guyot
  65254. // Separates very slightly R, G and B colors on the edges of the screen
  65255. // Inspired by Francois Tarlier & Martins Upitis
  65256. var BABYLON;
  65257. (function (BABYLON) {
  65258. var LensRenderingPipeline = /** @class */ (function (_super) {
  65259. __extends(LensRenderingPipeline, _super);
  65260. /**
  65261. * @constructor
  65262. *
  65263. * Effect parameters are as follow:
  65264. * {
  65265. * chromatic_aberration: number; // from 0 to x (1 for realism)
  65266. * edge_blur: number; // from 0 to x (1 for realism)
  65267. * distortion: number; // from 0 to x (1 for realism)
  65268. * grain_amount: number; // from 0 to 1
  65269. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  65270. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  65271. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  65272. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  65273. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  65274. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  65275. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  65276. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  65277. * }
  65278. * Note: if an effect parameter is unset, effect is disabled
  65279. *
  65280. * @param {string} name - The rendering pipeline name
  65281. * @param {object} parameters - An object containing all parameters (see above)
  65282. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  65283. * @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)
  65284. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  65285. */
  65286. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  65287. if (ratio === void 0) { ratio = 1.0; }
  65288. var _this = _super.call(this, scene.getEngine(), name) || this;
  65289. // Lens effects can be of the following:
  65290. // - chromatic aberration (slight shift of RGB colors)
  65291. // - blur on the edge of the lens
  65292. // - lens distortion
  65293. // - depth-of-field blur & highlights enhancing
  65294. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  65295. // - grain effect (noise or custom texture)
  65296. // Two additional texture samplers are needed:
  65297. // - depth map (for depth-of-field)
  65298. // - grain texture
  65299. /**
  65300. * The chromatic aberration PostProcess id in the pipeline
  65301. * @type {string}
  65302. */
  65303. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  65304. /**
  65305. * The highlights enhancing PostProcess id in the pipeline
  65306. * @type {string}
  65307. */
  65308. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  65309. /**
  65310. * The depth-of-field PostProcess id in the pipeline
  65311. * @type {string}
  65312. */
  65313. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  65314. _this._scene = scene;
  65315. // Fetch texture samplers
  65316. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  65317. if (parameters.grain_texture) {
  65318. _this._grainTexture = parameters.grain_texture;
  65319. }
  65320. else {
  65321. _this._createGrainTexture();
  65322. }
  65323. // save parameters
  65324. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  65325. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  65326. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  65327. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  65328. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  65329. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  65330. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  65331. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  65332. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  65333. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  65334. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  65335. // Create effects
  65336. _this._createChromaticAberrationPostProcess(ratio);
  65337. _this._createHighlightsPostProcess(ratio);
  65338. _this._createDepthOfFieldPostProcess(ratio / 4);
  65339. // Set up pipeline
  65340. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  65341. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  65342. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  65343. if (_this._highlightsGain === -1) {
  65344. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  65345. }
  65346. // Finish
  65347. scene.postProcessRenderPipelineManager.addPipeline(_this);
  65348. if (cameras) {
  65349. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  65350. }
  65351. return _this;
  65352. }
  65353. // public methods (self explanatory)
  65354. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  65355. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  65356. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  65357. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  65358. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  65359. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  65360. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  65361. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  65362. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  65363. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  65364. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  65365. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  65366. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  65367. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  65368. };
  65369. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  65370. this._highlightsPostProcess.updateEffect();
  65371. };
  65372. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  65373. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  65374. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  65375. this._highlightsGain = amount;
  65376. };
  65377. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  65378. if (this._highlightsGain === -1) {
  65379. this._highlightsGain = 1.0;
  65380. }
  65381. this._highlightsThreshold = amount;
  65382. };
  65383. LensRenderingPipeline.prototype.disableHighlights = function () {
  65384. this._highlightsGain = -1;
  65385. };
  65386. /**
  65387. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  65388. */
  65389. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  65390. if (disableDepthRender === void 0) { disableDepthRender = false; }
  65391. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  65392. this._chromaticAberrationPostProcess = null;
  65393. this._highlightsPostProcess = null;
  65394. this._depthOfFieldPostProcess = null;
  65395. this._grainTexture.dispose();
  65396. if (disableDepthRender)
  65397. this._scene.disableDepthRenderer();
  65398. };
  65399. // colors shifting and distortion
  65400. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  65401. var _this = this;
  65402. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  65403. [], // samplers
  65404. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  65405. this._chromaticAberrationPostProcess.onApply = function (effect) {
  65406. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  65407. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  65408. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  65409. };
  65410. };
  65411. // highlights enhancing
  65412. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  65413. var _this = this;
  65414. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  65415. [], // samplers
  65416. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  65417. this._highlightsPostProcess.onApply = function (effect) {
  65418. effect.setFloat('gain', _this._highlightsGain);
  65419. effect.setFloat('threshold', _this._highlightsThreshold);
  65420. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  65421. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  65422. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  65423. };
  65424. };
  65425. // colors shifting and distortion
  65426. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  65427. var _this = this;
  65428. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  65429. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  65430. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  65431. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  65432. this._depthOfFieldPostProcess.onApply = function (effect) {
  65433. effect.setTexture("depthSampler", _this._depthTexture);
  65434. effect.setTexture("grainSampler", _this._grainTexture);
  65435. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  65436. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  65437. effect.setFloat('grain_amount', _this._grainAmount);
  65438. effect.setBool('blur_noise', _this._blurNoise);
  65439. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  65440. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  65441. effect.setFloat('distortion', _this._distortion);
  65442. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  65443. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  65444. effect.setFloat('aperture', _this._dofAperture);
  65445. effect.setFloat('darken', _this._dofDarken);
  65446. effect.setFloat('edge_blur', _this._edgeBlur);
  65447. effect.setBool('highlights', (_this._highlightsGain !== -1));
  65448. if (_this._scene.activeCamera) {
  65449. effect.setFloat('near', _this._scene.activeCamera.minZ);
  65450. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  65451. }
  65452. };
  65453. };
  65454. // creates a black and white random noise texture, 512x512
  65455. LensRenderingPipeline.prototype._createGrainTexture = function () {
  65456. var size = 512;
  65457. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  65458. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  65459. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  65460. var context = this._grainTexture.getContext();
  65461. var rand = function (min, max) {
  65462. return Math.random() * (max - min) + min;
  65463. };
  65464. var value;
  65465. for (var x = 0; x < size; x++) {
  65466. for (var y = 0; y < size; y++) {
  65467. value = Math.floor(rand(0.42, 0.58) * 255);
  65468. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  65469. context.fillRect(x, y, 1, 1);
  65470. }
  65471. }
  65472. this._grainTexture.update(false);
  65473. };
  65474. return LensRenderingPipeline;
  65475. }(BABYLON.PostProcessRenderPipeline));
  65476. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  65477. })(BABYLON || (BABYLON = {}));
  65478. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  65479. var BABYLON;
  65480. (function (BABYLON) {
  65481. var StandardRenderingPipeline = /** @class */ (function (_super) {
  65482. __extends(StandardRenderingPipeline, _super);
  65483. /**
  65484. * @constructor
  65485. * @param {string} name - The rendering pipeline name
  65486. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  65487. * @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)
  65488. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  65489. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  65490. */
  65491. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  65492. if (originalPostProcess === void 0) { originalPostProcess = null; }
  65493. var _this = _super.call(this, scene.getEngine(), name) || this;
  65494. _this.downSampleX4PostProcess = null;
  65495. _this.brightPassPostProcess = null;
  65496. _this.blurHPostProcesses = [];
  65497. _this.blurVPostProcesses = [];
  65498. _this.textureAdderPostProcess = null;
  65499. _this.volumetricLightPostProcess = null;
  65500. _this.volumetricLightSmoothXPostProcess = null;
  65501. _this.volumetricLightSmoothYPostProcess = null;
  65502. _this.volumetricLightMergePostProces = null;
  65503. _this.volumetricLightFinalPostProcess = null;
  65504. _this.luminancePostProcess = null;
  65505. _this.luminanceDownSamplePostProcesses = [];
  65506. _this.hdrPostProcess = null;
  65507. _this.textureAdderFinalPostProcess = null;
  65508. _this.lensFlareFinalPostProcess = null;
  65509. _this.hdrFinalPostProcess = null;
  65510. _this.lensFlarePostProcess = null;
  65511. _this.lensFlareComposePostProcess = null;
  65512. _this.motionBlurPostProcess = null;
  65513. _this.depthOfFieldPostProcess = null;
  65514. // Values
  65515. _this.brightThreshold = 1.0;
  65516. _this.blurWidth = 512.0;
  65517. _this.horizontalBlur = false;
  65518. _this.exposure = 1.0;
  65519. _this.lensTexture = null;
  65520. _this.volumetricLightCoefficient = 0.2;
  65521. _this.volumetricLightPower = 4.0;
  65522. _this.volumetricLightBlurScale = 64.0;
  65523. _this.sourceLight = null;
  65524. _this.hdrMinimumLuminance = 1.0;
  65525. _this.hdrDecreaseRate = 0.5;
  65526. _this.hdrIncreaseRate = 0.5;
  65527. _this.lensColorTexture = null;
  65528. _this.lensFlareStrength = 20.0;
  65529. _this.lensFlareGhostDispersal = 1.4;
  65530. _this.lensFlareHaloWidth = 0.7;
  65531. _this.lensFlareDistortionStrength = 16.0;
  65532. _this.lensStarTexture = null;
  65533. _this.lensFlareDirtTexture = null;
  65534. _this.depthOfFieldDistance = 10.0;
  65535. _this.depthOfFieldBlurWidth = 64.0;
  65536. _this.motionStrength = 1.0;
  65537. // IAnimatable
  65538. _this.animations = [];
  65539. _this._currentDepthOfFieldSource = null;
  65540. _this._hdrCurrentLuminance = 1.0;
  65541. // Getters and setters
  65542. _this._bloomEnabled = true;
  65543. _this._depthOfFieldEnabled = false;
  65544. _this._vlsEnabled = false;
  65545. _this._lensFlareEnabled = false;
  65546. _this._hdrEnabled = false;
  65547. _this._motionBlurEnabled = false;
  65548. _this._motionBlurSamples = 64.0;
  65549. _this._volumetricLightStepsCount = 50.0;
  65550. _this._cameras = cameras || [];
  65551. // Initialize
  65552. _this._scene = scene;
  65553. _this._basePostProcess = originalPostProcess;
  65554. _this._ratio = ratio;
  65555. // Misc
  65556. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  65557. // Finish
  65558. scene.postProcessRenderPipelineManager.addPipeline(_this);
  65559. _this._buildPipeline();
  65560. return _this;
  65561. }
  65562. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  65563. get: function () {
  65564. return this._bloomEnabled;
  65565. },
  65566. set: function (enabled) {
  65567. if (this._bloomEnabled === enabled) {
  65568. return;
  65569. }
  65570. this._bloomEnabled = enabled;
  65571. this._buildPipeline();
  65572. },
  65573. enumerable: true,
  65574. configurable: true
  65575. });
  65576. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  65577. get: function () {
  65578. return this._depthOfFieldEnabled;
  65579. },
  65580. set: function (enabled) {
  65581. if (this._depthOfFieldEnabled === enabled) {
  65582. return;
  65583. }
  65584. this._depthOfFieldEnabled = enabled;
  65585. this._buildPipeline();
  65586. },
  65587. enumerable: true,
  65588. configurable: true
  65589. });
  65590. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  65591. get: function () {
  65592. return this._lensFlareEnabled;
  65593. },
  65594. set: function (enabled) {
  65595. if (this._lensFlareEnabled === enabled) {
  65596. return;
  65597. }
  65598. this._lensFlareEnabled = enabled;
  65599. this._buildPipeline();
  65600. },
  65601. enumerable: true,
  65602. configurable: true
  65603. });
  65604. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  65605. get: function () {
  65606. return this._hdrEnabled;
  65607. },
  65608. set: function (enabled) {
  65609. if (this._hdrEnabled === enabled) {
  65610. return;
  65611. }
  65612. this._hdrEnabled = enabled;
  65613. this._buildPipeline();
  65614. },
  65615. enumerable: true,
  65616. configurable: true
  65617. });
  65618. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  65619. get: function () {
  65620. return this._vlsEnabled;
  65621. },
  65622. set: function (enabled) {
  65623. if (this._vlsEnabled === enabled) {
  65624. return;
  65625. }
  65626. if (enabled) {
  65627. var geometry = this._scene.enableGeometryBufferRenderer();
  65628. if (!geometry) {
  65629. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  65630. return;
  65631. }
  65632. }
  65633. this._vlsEnabled = enabled;
  65634. this._buildPipeline();
  65635. },
  65636. enumerable: true,
  65637. configurable: true
  65638. });
  65639. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  65640. get: function () {
  65641. return this._motionBlurEnabled;
  65642. },
  65643. set: function (enabled) {
  65644. if (this._motionBlurEnabled === enabled) {
  65645. return;
  65646. }
  65647. this._motionBlurEnabled = enabled;
  65648. this._buildPipeline();
  65649. },
  65650. enumerable: true,
  65651. configurable: true
  65652. });
  65653. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  65654. get: function () {
  65655. return this._volumetricLightStepsCount;
  65656. },
  65657. set: function (count) {
  65658. if (this.volumetricLightPostProcess) {
  65659. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  65660. }
  65661. this._volumetricLightStepsCount = count;
  65662. },
  65663. enumerable: true,
  65664. configurable: true
  65665. });
  65666. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  65667. get: function () {
  65668. return this._motionBlurSamples;
  65669. },
  65670. set: function (samples) {
  65671. if (this.motionBlurPostProcess) {
  65672. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  65673. }
  65674. this._motionBlurSamples = samples;
  65675. },
  65676. enumerable: true,
  65677. configurable: true
  65678. });
  65679. StandardRenderingPipeline.prototype._buildPipeline = function () {
  65680. var _this = this;
  65681. var ratio = this._ratio;
  65682. var scene = this._scene;
  65683. this._disposePostProcesses();
  65684. this._reset();
  65685. // Create pass post-process
  65686. if (!this._basePostProcess) {
  65687. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  65688. this.originalPostProcess.onApply = function (effect) {
  65689. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  65690. };
  65691. }
  65692. else {
  65693. this.originalPostProcess = this._basePostProcess;
  65694. }
  65695. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  65696. this._currentDepthOfFieldSource = this.originalPostProcess;
  65697. if (this._vlsEnabled) {
  65698. // Create volumetric light
  65699. this._createVolumetricLightPostProcess(scene, ratio);
  65700. // Create volumetric light final post-process
  65701. 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);
  65702. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  65703. }
  65704. if (this._bloomEnabled) {
  65705. // Create down sample X4 post-process
  65706. this._createDownSampleX4PostProcess(scene, ratio / 2);
  65707. // Create bright pass post-process
  65708. this._createBrightPassPostProcess(scene, ratio / 2);
  65709. // Create gaussian blur post-processes (down sampling blurs)
  65710. this._createBlurPostProcesses(scene, ratio / 4, 1);
  65711. // Create texture adder post-process
  65712. this._createTextureAdderPostProcess(scene, ratio);
  65713. // Create depth-of-field source post-process
  65714. 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);
  65715. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  65716. }
  65717. if (this._lensFlareEnabled) {
  65718. // Create lens flare post-process
  65719. this._createLensFlarePostProcess(scene, ratio);
  65720. // Create depth-of-field source post-process post lens-flare and disable it now
  65721. 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);
  65722. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  65723. }
  65724. if (this._hdrEnabled) {
  65725. // Create luminance
  65726. this._createLuminancePostProcesses(scene, this._floatTextureType);
  65727. // Create HDR
  65728. this._createHdrPostProcess(scene, ratio);
  65729. // Create depth-of-field source post-process post hdr and disable it now
  65730. 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);
  65731. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  65732. }
  65733. if (this._depthOfFieldEnabled) {
  65734. // Create gaussian blur used by depth-of-field
  65735. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  65736. // Create depth-of-field post-process
  65737. this._createDepthOfFieldPostProcess(scene, ratio);
  65738. }
  65739. if (this._motionBlurEnabled) {
  65740. // Create motion blur post-process
  65741. this._createMotionBlurPostProcess(scene, ratio);
  65742. }
  65743. if (this._cameras !== null) {
  65744. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  65745. }
  65746. };
  65747. // Down Sample X4 Post-Processs
  65748. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  65749. var _this = this;
  65750. var downSampleX4Offsets = new Array(32);
  65751. 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);
  65752. this.downSampleX4PostProcess.onApply = function (effect) {
  65753. var id = 0;
  65754. var width = _this.downSampleX4PostProcess.width;
  65755. var height = _this.downSampleX4PostProcess.height;
  65756. for (var i = -2; i < 2; i++) {
  65757. for (var j = -2; j < 2; j++) {
  65758. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  65759. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  65760. id += 2;
  65761. }
  65762. }
  65763. effect.setArray2("dsOffsets", downSampleX4Offsets);
  65764. };
  65765. // Add to pipeline
  65766. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  65767. };
  65768. // Brightpass Post-Process
  65769. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  65770. var _this = this;
  65771. var brightOffsets = new Array(8);
  65772. 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);
  65773. this.brightPassPostProcess.onApply = function (effect) {
  65774. var sU = (1.0 / _this.brightPassPostProcess.width);
  65775. var sV = (1.0 / _this.brightPassPostProcess.height);
  65776. brightOffsets[0] = -0.5 * sU;
  65777. brightOffsets[1] = 0.5 * sV;
  65778. brightOffsets[2] = 0.5 * sU;
  65779. brightOffsets[3] = 0.5 * sV;
  65780. brightOffsets[4] = -0.5 * sU;
  65781. brightOffsets[5] = -0.5 * sV;
  65782. brightOffsets[6] = 0.5 * sU;
  65783. brightOffsets[7] = -0.5 * sV;
  65784. effect.setArray2("dsOffsets", brightOffsets);
  65785. effect.setFloat("brightThreshold", _this.brightThreshold);
  65786. };
  65787. // Add to pipeline
  65788. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  65789. };
  65790. // Create blur H&V post-processes
  65791. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  65792. var _this = this;
  65793. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  65794. var engine = scene.getEngine();
  65795. 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);
  65796. 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);
  65797. blurX.onActivateObservable.add(function () {
  65798. var dw = blurX.width / engine.getRenderWidth();
  65799. blurX.kernel = _this[blurWidthKey] * dw;
  65800. });
  65801. blurY.onActivateObservable.add(function () {
  65802. var dw = blurY.height / engine.getRenderHeight();
  65803. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  65804. });
  65805. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  65806. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  65807. this.blurHPostProcesses.push(blurX);
  65808. this.blurVPostProcesses.push(blurY);
  65809. };
  65810. // Create texture adder post-process
  65811. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  65812. var _this = this;
  65813. 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);
  65814. this.textureAdderPostProcess.onApply = function (effect) {
  65815. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  65816. effect.setTexture("lensSampler", _this.lensTexture);
  65817. effect.setFloat("exposure", _this.exposure);
  65818. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  65819. };
  65820. // Add to pipeline
  65821. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  65822. };
  65823. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  65824. var _this = this;
  65825. var geometryRenderer = scene.enableGeometryBufferRenderer();
  65826. geometryRenderer.enablePosition = true;
  65827. var geometry = geometryRenderer.getGBuffer();
  65828. // Base post-process
  65829. 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));
  65830. var depthValues = BABYLON.Vector2.Zero();
  65831. this.volumetricLightPostProcess.onApply = function (effect) {
  65832. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  65833. var generator = _this.sourceLight.getShadowGenerator();
  65834. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  65835. effect.setTexture("positionSampler", geometry.textures[2]);
  65836. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  65837. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  65838. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  65839. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  65840. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  65841. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  65842. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  65843. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  65844. effect.setVector2("depthValues", depthValues);
  65845. }
  65846. };
  65847. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  65848. // Smooth
  65849. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  65850. // Merge
  65851. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  65852. this.volumetricLightMergePostProces.onApply = function (effect) {
  65853. effect.setTextureFromPostProcess("originalSampler", _this.originalPostProcess);
  65854. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  65855. };
  65856. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  65857. };
  65858. // Create luminance
  65859. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  65860. var _this = this;
  65861. // Create luminance
  65862. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  65863. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  65864. var offsets = [];
  65865. this.luminancePostProcess.onApply = function (effect) {
  65866. var sU = (1.0 / _this.luminancePostProcess.width);
  65867. var sV = (1.0 / _this.luminancePostProcess.height);
  65868. offsets[0] = -0.5 * sU;
  65869. offsets[1] = 0.5 * sV;
  65870. offsets[2] = 0.5 * sU;
  65871. offsets[3] = 0.5 * sV;
  65872. offsets[4] = -0.5 * sU;
  65873. offsets[5] = -0.5 * sV;
  65874. offsets[6] = 0.5 * sU;
  65875. offsets[7] = -0.5 * sV;
  65876. effect.setArray2("lumOffsets", offsets);
  65877. };
  65878. // Add to pipeline
  65879. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  65880. // Create down sample luminance
  65881. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  65882. var size = Math.pow(3, i);
  65883. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  65884. if (i === 0) {
  65885. defines += "#define FINAL_DOWN_SAMPLER";
  65886. }
  65887. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  65888. this.luminanceDownSamplePostProcesses.push(postProcess);
  65889. }
  65890. // Create callbacks and add effects
  65891. var lastLuminance = this.luminancePostProcess;
  65892. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  65893. var downSampleOffsets = new Array(18);
  65894. pp.onApply = function (effect) {
  65895. if (!lastLuminance) {
  65896. return;
  65897. }
  65898. var id = 0;
  65899. for (var x = -1; x < 2; x++) {
  65900. for (var y = -1; y < 2; y++) {
  65901. downSampleOffsets[id] = x / lastLuminance.width;
  65902. downSampleOffsets[id + 1] = y / lastLuminance.height;
  65903. id += 2;
  65904. }
  65905. }
  65906. effect.setArray2("dsOffsets", downSampleOffsets);
  65907. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  65908. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  65909. lastLuminance = _this.luminancePostProcess;
  65910. }
  65911. else {
  65912. lastLuminance = pp;
  65913. }
  65914. };
  65915. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  65916. pp.onAfterRender = function (effect) {
  65917. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  65918. 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);
  65919. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  65920. };
  65921. }
  65922. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  65923. });
  65924. };
  65925. // Create HDR post-process
  65926. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  65927. var _this = this;
  65928. 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);
  65929. var outputLiminance = 1;
  65930. var time = 0;
  65931. var lastTime = 0;
  65932. this.hdrPostProcess.onApply = function (effect) {
  65933. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  65934. time += scene.getEngine().getDeltaTime();
  65935. if (outputLiminance < 0) {
  65936. outputLiminance = _this._hdrCurrentLuminance;
  65937. }
  65938. else {
  65939. var dt = (lastTime - time) / 1000.0;
  65940. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  65941. outputLiminance += _this.hdrDecreaseRate * dt;
  65942. }
  65943. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  65944. outputLiminance -= _this.hdrIncreaseRate * dt;
  65945. }
  65946. else {
  65947. outputLiminance = _this._hdrCurrentLuminance;
  65948. }
  65949. }
  65950. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  65951. effect.setFloat("averageLuminance", outputLiminance);
  65952. lastTime = time;
  65953. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  65954. };
  65955. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  65956. };
  65957. // Create lens flare post-process
  65958. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  65959. var _this = this;
  65960. 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);
  65961. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  65962. this._createBlurPostProcesses(scene, ratio / 4, 2);
  65963. 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);
  65964. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  65965. var resolution = new BABYLON.Vector2(0, 0);
  65966. // Lens flare
  65967. this.lensFlarePostProcess.onApply = function (effect) {
  65968. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  65969. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  65970. effect.setFloat("strength", _this.lensFlareStrength);
  65971. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  65972. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  65973. // Shift
  65974. resolution.x = _this.lensFlarePostProcess.width;
  65975. resolution.y = _this.lensFlarePostProcess.height;
  65976. effect.setVector2("resolution", resolution);
  65977. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  65978. };
  65979. // Compose
  65980. 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);
  65981. 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);
  65982. this.lensFlareComposePostProcess.onApply = function (effect) {
  65983. if (!_this._scene.activeCamera) {
  65984. return;
  65985. }
  65986. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  65987. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  65988. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  65989. // Lens start rotation matrix
  65990. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  65991. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  65992. 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));
  65993. camRot *= 4.0;
  65994. 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);
  65995. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  65996. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  65997. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  65998. };
  65999. };
  66000. // Create depth-of-field post-process
  66001. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  66002. var _this = this;
  66003. 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);
  66004. this.depthOfFieldPostProcess.onApply = function (effect) {
  66005. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  66006. effect.setTexture("depthSampler", _this._getDepthTexture());
  66007. effect.setFloat("distance", _this.depthOfFieldDistance);
  66008. };
  66009. // Add to pipeline
  66010. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  66011. };
  66012. // Create motion blur post-process
  66013. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  66014. var _this = this;
  66015. 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);
  66016. var motionScale = 0;
  66017. var prevViewProjection = BABYLON.Matrix.Identity();
  66018. var invViewProjection = BABYLON.Matrix.Identity();
  66019. var viewProjection = BABYLON.Matrix.Identity();
  66020. var screenSize = BABYLON.Vector2.Zero();
  66021. this.motionBlurPostProcess.onApply = function (effect) {
  66022. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  66023. viewProjection.invertToRef(invViewProjection);
  66024. effect.setMatrix("inverseViewProjection", invViewProjection);
  66025. effect.setMatrix("prevViewProjection", prevViewProjection);
  66026. prevViewProjection = viewProjection;
  66027. screenSize.x = _this.motionBlurPostProcess.width;
  66028. screenSize.y = _this.motionBlurPostProcess.height;
  66029. effect.setVector2("screenSize", screenSize);
  66030. motionScale = scene.getEngine().getFps() / 60.0;
  66031. effect.setFloat("motionScale", motionScale);
  66032. effect.setFloat("motionStrength", _this.motionStrength);
  66033. effect.setTexture("depthSampler", _this._getDepthTexture());
  66034. };
  66035. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  66036. };
  66037. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  66038. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  66039. var renderer = this._scene.enableGeometryBufferRenderer();
  66040. return renderer.getGBuffer().textures[0];
  66041. }
  66042. return this._scene.enableDepthRenderer().getDepthMap();
  66043. };
  66044. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  66045. for (var i = 0; i < this._cameras.length; i++) {
  66046. var camera = this._cameras[i];
  66047. if (this.originalPostProcess) {
  66048. this.originalPostProcess.dispose(camera);
  66049. }
  66050. if (this.downSampleX4PostProcess) {
  66051. this.downSampleX4PostProcess.dispose(camera);
  66052. }
  66053. if (this.brightPassPostProcess) {
  66054. this.brightPassPostProcess.dispose(camera);
  66055. }
  66056. if (this.textureAdderPostProcess) {
  66057. this.textureAdderPostProcess.dispose(camera);
  66058. }
  66059. if (this.textureAdderFinalPostProcess) {
  66060. this.textureAdderFinalPostProcess.dispose(camera);
  66061. }
  66062. if (this.volumetricLightPostProcess) {
  66063. this.volumetricLightPostProcess.dispose(camera);
  66064. }
  66065. if (this.volumetricLightSmoothXPostProcess) {
  66066. this.volumetricLightSmoothXPostProcess.dispose(camera);
  66067. }
  66068. if (this.volumetricLightSmoothYPostProcess) {
  66069. this.volumetricLightSmoothYPostProcess.dispose(camera);
  66070. }
  66071. if (this.volumetricLightMergePostProces) {
  66072. this.volumetricLightMergePostProces.dispose(camera);
  66073. }
  66074. if (this.volumetricLightFinalPostProcess) {
  66075. this.volumetricLightFinalPostProcess.dispose(camera);
  66076. }
  66077. if (this.lensFlarePostProcess) {
  66078. this.lensFlarePostProcess.dispose(camera);
  66079. }
  66080. if (this.lensFlareComposePostProcess) {
  66081. this.lensFlareComposePostProcess.dispose(camera);
  66082. }
  66083. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  66084. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  66085. }
  66086. if (this.luminancePostProcess) {
  66087. this.luminancePostProcess.dispose(camera);
  66088. }
  66089. if (this.hdrPostProcess) {
  66090. this.hdrPostProcess.dispose(camera);
  66091. }
  66092. if (this.hdrFinalPostProcess) {
  66093. this.hdrFinalPostProcess.dispose(camera);
  66094. }
  66095. if (this.depthOfFieldPostProcess) {
  66096. this.depthOfFieldPostProcess.dispose(camera);
  66097. }
  66098. if (this.motionBlurPostProcess) {
  66099. this.motionBlurPostProcess.dispose(camera);
  66100. }
  66101. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  66102. this.blurHPostProcesses[j].dispose(camera);
  66103. }
  66104. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  66105. this.blurVPostProcesses[j].dispose(camera);
  66106. }
  66107. }
  66108. this.originalPostProcess = null;
  66109. this.downSampleX4PostProcess = null;
  66110. this.brightPassPostProcess = null;
  66111. this.textureAdderPostProcess = null;
  66112. this.textureAdderFinalPostProcess = null;
  66113. this.volumetricLightPostProcess = null;
  66114. this.volumetricLightSmoothXPostProcess = null;
  66115. this.volumetricLightSmoothYPostProcess = null;
  66116. this.volumetricLightMergePostProces = null;
  66117. this.volumetricLightFinalPostProcess = null;
  66118. this.lensFlarePostProcess = null;
  66119. this.lensFlareComposePostProcess = null;
  66120. this.luminancePostProcess = null;
  66121. this.hdrPostProcess = null;
  66122. this.hdrFinalPostProcess = null;
  66123. this.depthOfFieldPostProcess = null;
  66124. this.motionBlurPostProcess = null;
  66125. this.luminanceDownSamplePostProcesses = [];
  66126. this.blurHPostProcesses = [];
  66127. this.blurVPostProcesses = [];
  66128. };
  66129. // Dispose
  66130. StandardRenderingPipeline.prototype.dispose = function () {
  66131. this._disposePostProcesses();
  66132. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  66133. _super.prototype.dispose.call(this);
  66134. };
  66135. // Serialize rendering pipeline
  66136. StandardRenderingPipeline.prototype.serialize = function () {
  66137. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  66138. serializationObject.customType = "StandardRenderingPipeline";
  66139. return serializationObject;
  66140. };
  66141. /**
  66142. * Static members
  66143. */
  66144. // Parse serialized pipeline
  66145. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  66146. return BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  66147. };
  66148. // Luminance steps
  66149. StandardRenderingPipeline.LuminanceSteps = 6;
  66150. __decorate([
  66151. BABYLON.serialize()
  66152. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  66153. __decorate([
  66154. BABYLON.serialize()
  66155. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  66156. __decorate([
  66157. BABYLON.serialize()
  66158. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  66159. __decorate([
  66160. BABYLON.serialize()
  66161. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  66162. __decorate([
  66163. BABYLON.serializeAsTexture("lensTexture")
  66164. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  66165. __decorate([
  66166. BABYLON.serialize()
  66167. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  66168. __decorate([
  66169. BABYLON.serialize()
  66170. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  66171. __decorate([
  66172. BABYLON.serialize()
  66173. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  66174. __decorate([
  66175. BABYLON.serialize()
  66176. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  66177. __decorate([
  66178. BABYLON.serialize()
  66179. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  66180. __decorate([
  66181. BABYLON.serialize()
  66182. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  66183. __decorate([
  66184. BABYLON.serializeAsTexture("lensColorTexture")
  66185. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  66186. __decorate([
  66187. BABYLON.serialize()
  66188. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  66189. __decorate([
  66190. BABYLON.serialize()
  66191. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  66192. __decorate([
  66193. BABYLON.serialize()
  66194. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  66195. __decorate([
  66196. BABYLON.serialize()
  66197. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  66198. __decorate([
  66199. BABYLON.serializeAsTexture("lensStarTexture")
  66200. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  66201. __decorate([
  66202. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  66203. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  66204. __decorate([
  66205. BABYLON.serialize()
  66206. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  66207. __decorate([
  66208. BABYLON.serialize()
  66209. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  66210. __decorate([
  66211. BABYLON.serialize()
  66212. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  66213. __decorate([
  66214. BABYLON.serialize()
  66215. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  66216. __decorate([
  66217. BABYLON.serialize()
  66218. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  66219. __decorate([
  66220. BABYLON.serialize()
  66221. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  66222. __decorate([
  66223. BABYLON.serialize()
  66224. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  66225. __decorate([
  66226. BABYLON.serialize()
  66227. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  66228. __decorate([
  66229. BABYLON.serialize()
  66230. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  66231. __decorate([
  66232. BABYLON.serialize()
  66233. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  66234. __decorate([
  66235. BABYLON.serialize()
  66236. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  66237. __decorate([
  66238. BABYLON.serialize()
  66239. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  66240. return StandardRenderingPipeline;
  66241. }(BABYLON.PostProcessRenderPipeline));
  66242. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  66243. })(BABYLON || (BABYLON = {}));
  66244. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  66245. var BABYLON;
  66246. (function (BABYLON) {
  66247. var FxaaPostProcess = /** @class */ (function (_super) {
  66248. __extends(FxaaPostProcess, _super);
  66249. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  66250. if (camera === void 0) { camera = null; }
  66251. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  66252. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa") || this;
  66253. _this.onApplyObservable.add(function (effect) {
  66254. var texelSize = _this.texelSize;
  66255. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  66256. });
  66257. return _this;
  66258. }
  66259. return FxaaPostProcess;
  66260. }(BABYLON.PostProcess));
  66261. BABYLON.FxaaPostProcess = FxaaPostProcess;
  66262. })(BABYLON || (BABYLON = {}));
  66263. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  66264. var BABYLON;
  66265. (function (BABYLON) {
  66266. /**
  66267. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  66268. */
  66269. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  66270. __extends(CircleOfConfusionPostProcess, _super);
  66271. /**
  66272. * Creates a new instance of @see CircleOfConfusionPostProcess
  66273. * @param name The name of the effect.
  66274. * @param scene The scene the effect belongs to.
  66275. * @param depthTexture The depth texture of the scene to compute the circle of confusion.
  66276. * @param options The required width/height ratio to downsize to before computing the render pass.
  66277. * @param camera The camera to apply the render pass to.
  66278. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  66279. * @param engine The engine which the post process will be applied. (default: current engine)
  66280. * @param reusable If the post process can be reused on the same frame. (default: false)
  66281. * @param textureType Type of textures used when performing the post process. (default: 0)
  66282. */
  66283. function CircleOfConfusionPostProcess(name, scene, depthTexture, options, camera, samplingMode, engine, reusable, textureType) {
  66284. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  66285. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType) || this;
  66286. /**
  66287. * 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.
  66288. */
  66289. _this.lensSize = 50;
  66290. /**
  66291. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  66292. */
  66293. _this.fStop = 1.4;
  66294. /**
  66295. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  66296. */
  66297. _this.focusDistance = 2000;
  66298. /**
  66299. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  66300. */
  66301. _this.focalLength = 50;
  66302. _this.onApplyObservable.add(function (effect) {
  66303. effect.setTexture("depthSampler", depthTexture);
  66304. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  66305. var aperture = _this.lensSize / _this.fStop;
  66306. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  66307. effect.setFloat('focusDistance', _this.focusDistance);
  66308. effect.setFloat('cocPrecalculation', cocPrecalculation);
  66309. if (scene.activeCamera) {
  66310. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  66311. }
  66312. });
  66313. return _this;
  66314. }
  66315. return CircleOfConfusionPostProcess;
  66316. }(BABYLON.PostProcess));
  66317. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  66318. })(BABYLON || (BABYLON = {}));
  66319. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  66320. var BABYLON;
  66321. (function (BABYLON) {
  66322. /**
  66323. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  66324. */
  66325. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  66326. __extends(DepthOfFieldMergePostProcess, _super);
  66327. /**
  66328. * Creates a new instance of @see CircleOfConfusionPostProcess
  66329. * @param name The name of the effect.
  66330. * @param original The non-blurred image to be modified
  66331. * @param circleOfConfusion The circle of confusion post process that will determine how blurred each pixel should become.
  66332. * @param blurSteps Incrimental bluring post processes.
  66333. * @param options The required width/height ratio to downsize to before computing the render pass.
  66334. * @param camera The camera to apply the render pass to.
  66335. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  66336. * @param engine The engine which the post process will be applied. (default: current engine)
  66337. * @param reusable If the post process can be reused on the same frame. (default: false)
  66338. * @param textureType Type of textures used when performing the post process. (default: 0)
  66339. */
  66340. function DepthOfFieldMergePostProcess(name, original, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType) {
  66341. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  66342. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "originalSampler", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, "#define BLUR_LEVEL " + blurSteps.length + "\n", textureType) || this;
  66343. _this.onApplyObservable.add(function (effect) {
  66344. effect.setTextureFromPostProcess("circleOfConfusionSampler", circleOfConfusion);
  66345. effect.setTextureFromPostProcess("originalSampler", original);
  66346. blurSteps.forEach(function (step, index) {
  66347. effect.setTextureFromPostProcess("blurStep" + (index + 1), step);
  66348. });
  66349. });
  66350. return _this;
  66351. }
  66352. return DepthOfFieldMergePostProcess;
  66353. }(BABYLON.PostProcess));
  66354. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  66355. })(BABYLON || (BABYLON = {}));
  66356. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  66357. var BABYLON;
  66358. (function (BABYLON) {
  66359. /**
  66360. * Specifies the level of max blur that should be applied when using the depth of field effect
  66361. */
  66362. var DepthOfFieldEffectBlurLevel;
  66363. (function (DepthOfFieldEffectBlurLevel) {
  66364. /**
  66365. * Subtle blur
  66366. */
  66367. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  66368. /**
  66369. * Medium blur
  66370. */
  66371. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  66372. /**
  66373. * Large blur
  66374. */
  66375. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  66376. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  66377. ;
  66378. /**
  66379. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  66380. */
  66381. var DepthOfFieldEffect = /** @class */ (function (_super) {
  66382. __extends(DepthOfFieldEffect, _super);
  66383. /**
  66384. * Creates a new instance of @see DepthOfFieldEffect
  66385. * @param scene The scene the effect belongs to.
  66386. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  66387. */
  66388. function DepthOfFieldEffect(scene, blurLevel, pipelineTextureType) {
  66389. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  66390. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  66391. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  66392. // Enable and get current depth map
  66393. var depthMap = scene.enableDepthRenderer().getDepthMap();
  66394. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  66395. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", scene, depthMap, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType);
  66396. // Capture circle of confusion texture
  66397. _this._depthOfFieldPass = new BABYLON.PassPostProcess("depthOfFieldPass", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType);
  66398. _this._depthOfFieldPass.autoClear = false;
  66399. // 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)
  66400. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  66401. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  66402. _this._depthOfFieldBlurY = [];
  66403. _this._depthOfFieldBlurX = [];
  66404. var blurCount = 1;
  66405. var kernelSize = 15;
  66406. switch (blurLevel) {
  66407. case DepthOfFieldEffectBlurLevel.High: {
  66408. blurCount = 3;
  66409. kernelSize = 51;
  66410. break;
  66411. }
  66412. case DepthOfFieldEffectBlurLevel.Medium: {
  66413. blurCount = 2;
  66414. kernelSize = 31;
  66415. break;
  66416. }
  66417. default: {
  66418. kernelSize = 15;
  66419. blurCount = 1;
  66420. break;
  66421. }
  66422. }
  66423. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  66424. for (var i = 0; i < blurCount; i++) {
  66425. 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);
  66426. blurY.autoClear = false;
  66427. 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);
  66428. blurX.autoClear = false;
  66429. _this._depthOfFieldBlurY.push(blurY);
  66430. _this._depthOfFieldBlurX.push(blurX);
  66431. }
  66432. // Merge blurred images with original image based on circleOfConfusion
  66433. _this._depthOfFieldMerge = new BABYLON.DepthOfFieldMergePostProcess("depthOfFieldMerge", _this._circleOfConfusion, _this._depthOfFieldPass, _this._depthOfFieldBlurY.slice(1), 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType);
  66434. _this._depthOfFieldMerge.autoClear = false;
  66435. // Set all post processes on the effect.
  66436. var effects = [_this._circleOfConfusion, _this._depthOfFieldPass];
  66437. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  66438. effects.push(_this._depthOfFieldBlurY[i]);
  66439. effects.push(_this._depthOfFieldBlurX[i]);
  66440. }
  66441. effects.push(_this._depthOfFieldMerge);
  66442. return effects;
  66443. }, true) || this;
  66444. return _this;
  66445. }
  66446. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  66447. get: function () {
  66448. return this._circleOfConfusion.focalLength;
  66449. },
  66450. /**
  66451. * The focal the length of the camera used in the effect
  66452. */
  66453. set: function (value) {
  66454. this._circleOfConfusion.focalLength = value;
  66455. },
  66456. enumerable: true,
  66457. configurable: true
  66458. });
  66459. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  66460. get: function () {
  66461. return this._circleOfConfusion.fStop;
  66462. },
  66463. /**
  66464. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  66465. */
  66466. set: function (value) {
  66467. this._circleOfConfusion.fStop = value;
  66468. },
  66469. enumerable: true,
  66470. configurable: true
  66471. });
  66472. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  66473. get: function () {
  66474. return this._circleOfConfusion.focusDistance;
  66475. },
  66476. /**
  66477. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  66478. */
  66479. set: function (value) {
  66480. this._circleOfConfusion.focusDistance = value;
  66481. },
  66482. enumerable: true,
  66483. configurable: true
  66484. });
  66485. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  66486. get: function () {
  66487. return this._circleOfConfusion.lensSize;
  66488. },
  66489. /**
  66490. * 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.
  66491. */
  66492. set: function (value) {
  66493. this._circleOfConfusion.lensSize = value;
  66494. },
  66495. enumerable: true,
  66496. configurable: true
  66497. });
  66498. /**
  66499. * Disposes each of the internal effects for a given camera.
  66500. * @param camera The camera to dispose the effect on.
  66501. */
  66502. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  66503. this._depthOfFieldPass.dispose(camera);
  66504. this._circleOfConfusion.dispose(camera);
  66505. this._depthOfFieldBlurX.forEach(function (element) {
  66506. element.dispose(camera);
  66507. });
  66508. this._depthOfFieldBlurY.forEach(function (element) {
  66509. element.dispose(camera);
  66510. });
  66511. this._depthOfFieldMerge.dispose(camera);
  66512. };
  66513. return DepthOfFieldEffect;
  66514. }(BABYLON.PostProcessRenderEffect));
  66515. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  66516. })(BABYLON || (BABYLON = {}));
  66517. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  66518. var BABYLON;
  66519. (function (BABYLON) {
  66520. /**
  66521. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  66522. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  66523. */
  66524. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  66525. __extends(DefaultRenderingPipeline, _super);
  66526. /**
  66527. * @constructor
  66528. * @param {string} name - The rendering pipeline name
  66529. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  66530. * @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)
  66531. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  66532. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline
  66533. */
  66534. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  66535. if (automaticBuild === void 0) { automaticBuild = true; }
  66536. var _this = _super.call(this, scene.getEngine(), name) || this;
  66537. /**
  66538. * ID of the pass post process used for bloom,
  66539. */
  66540. _this.PassPostProcessId = "PassPostProcessEffect";
  66541. /**
  66542. * ID of the highlight post process used for bloom,
  66543. */
  66544. _this.HighLightsPostProcessId = "HighLightsPostProcessEffect";
  66545. /**
  66546. * ID of the blurX post process used for bloom,
  66547. */
  66548. _this.BlurXPostProcessId = "BlurXPostProcessEffect";
  66549. /**
  66550. * ID of the blurY post process used for bloom,
  66551. */
  66552. _this.BlurYPostProcessId = "BlurYPostProcessEffect";
  66553. /**
  66554. * ID of the copy back post process used for bloom,
  66555. */
  66556. _this.CopyBackPostProcessId = "CopyBackPostProcessEffect";
  66557. /**
  66558. * ID of the image processing post process;
  66559. */
  66560. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  66561. /**
  66562. * ID of the Fast Approximate Anti-Aliasing post process;
  66563. */
  66564. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  66565. /**
  66566. * ID of the final merge post process;
  66567. */
  66568. _this.FinalMergePostProcessId = "FinalMergePostProcessEffect";
  66569. /**
  66570. * Animations which can be used to tweak settings over a period of time
  66571. */
  66572. _this.animations = [];
  66573. // Values
  66574. _this._bloomEnabled = false;
  66575. _this._depthOfFieldEnabled = false;
  66576. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  66577. _this._fxaaEnabled = false;
  66578. _this._imageProcessingEnabled = true;
  66579. _this._bloomScale = 0.6;
  66580. _this._buildAllowed = true;
  66581. /**
  66582. * Specifies the size of the bloom blur kernel, relative to the final output size
  66583. */
  66584. _this.bloomKernel = 64;
  66585. /**
  66586. * Specifies the weight of the bloom in the final rendering
  66587. */
  66588. _this._bloomWeight = 0.15;
  66589. _this._cameras = cameras || [];
  66590. _this._buildAllowed = automaticBuild;
  66591. // Initialize
  66592. _this._scene = scene;
  66593. var caps = _this._scene.getEngine().getCaps();
  66594. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  66595. // Misc
  66596. if (_this._hdr) {
  66597. if (caps.textureHalfFloatRender) {
  66598. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  66599. }
  66600. else if (caps.textureFloatRender) {
  66601. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  66602. }
  66603. }
  66604. else {
  66605. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  66606. }
  66607. // Attach
  66608. scene.postProcessRenderPipelineManager.addPipeline(_this);
  66609. _this._buildPipeline();
  66610. return _this;
  66611. }
  66612. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  66613. get: function () {
  66614. return this._bloomWeight;
  66615. },
  66616. /**
  66617. * The strength of the bloom.
  66618. */
  66619. set: function (value) {
  66620. if (this._bloomWeight === value) {
  66621. return;
  66622. }
  66623. this._bloomWeight = value;
  66624. if (this._hdr && this.copyBack) {
  66625. this.copyBack.alphaConstants = new BABYLON.Color4(value, value, value, value);
  66626. }
  66627. },
  66628. enumerable: true,
  66629. configurable: true
  66630. });
  66631. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  66632. get: function () {
  66633. return this._bloomScale;
  66634. },
  66635. /**
  66636. * The scale of the bloom, lower value will provide better performance.
  66637. */
  66638. set: function (value) {
  66639. if (this._bloomScale === value) {
  66640. return;
  66641. }
  66642. this._bloomScale = value;
  66643. this._buildPipeline();
  66644. },
  66645. enumerable: true,
  66646. configurable: true
  66647. });
  66648. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  66649. get: function () {
  66650. return this._bloomEnabled;
  66651. },
  66652. /**
  66653. * Enable or disable the bloom from the pipeline
  66654. */
  66655. set: function (enabled) {
  66656. if (this._bloomEnabled === enabled) {
  66657. return;
  66658. }
  66659. this._bloomEnabled = enabled;
  66660. this._buildPipeline();
  66661. },
  66662. enumerable: true,
  66663. configurable: true
  66664. });
  66665. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  66666. /**
  66667. * If the depth of field is enabled.
  66668. */
  66669. get: function () {
  66670. return this._depthOfFieldEnabled;
  66671. },
  66672. set: function (enabled) {
  66673. if (this._depthOfFieldEnabled === enabled) {
  66674. return;
  66675. }
  66676. this._depthOfFieldEnabled = enabled;
  66677. this._buildPipeline();
  66678. },
  66679. enumerable: true,
  66680. configurable: true
  66681. });
  66682. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  66683. /**
  66684. * Blur level of the depth of field effect. (Higher blur will effect performance)
  66685. */
  66686. get: function () {
  66687. return this._depthOfFieldBlurLevel;
  66688. },
  66689. set: function (value) {
  66690. if (this._depthOfFieldBlurLevel === value) {
  66691. return;
  66692. }
  66693. this._depthOfFieldBlurLevel = value;
  66694. this._buildPipeline();
  66695. },
  66696. enumerable: true,
  66697. configurable: true
  66698. });
  66699. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  66700. get: function () {
  66701. return this._fxaaEnabled;
  66702. },
  66703. /**
  66704. * If the anti aliasing is enabled.
  66705. */
  66706. set: function (enabled) {
  66707. if (this._fxaaEnabled === enabled) {
  66708. return;
  66709. }
  66710. this._fxaaEnabled = enabled;
  66711. this._buildPipeline();
  66712. },
  66713. enumerable: true,
  66714. configurable: true
  66715. });
  66716. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  66717. get: function () {
  66718. return this._imageProcessingEnabled;
  66719. },
  66720. /**
  66721. * If image processing is enabled.
  66722. */
  66723. set: function (enabled) {
  66724. if (this._imageProcessingEnabled === enabled) {
  66725. return;
  66726. }
  66727. this._imageProcessingEnabled = enabled;
  66728. this._buildPipeline();
  66729. },
  66730. enumerable: true,
  66731. configurable: true
  66732. });
  66733. /**
  66734. * Force the compilation of the entire pipeline.
  66735. */
  66736. DefaultRenderingPipeline.prototype.prepare = function () {
  66737. var previousState = this._buildAllowed;
  66738. this._buildAllowed = true;
  66739. this._buildPipeline();
  66740. this._buildAllowed = previousState;
  66741. };
  66742. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  66743. var _this = this;
  66744. if (!this._buildAllowed) {
  66745. return;
  66746. }
  66747. var engine = this._scene.getEngine();
  66748. this._disposePostProcesses();
  66749. this._reset();
  66750. if (this.depthOfFieldEnabled) {
  66751. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType);
  66752. this.addEffect(this.depthOfField);
  66753. }
  66754. if (this.bloomEnabled) {
  66755. this.pass = new BABYLON.PassPostProcess("sceneRenderTarget", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  66756. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.PassPostProcessId, function () { return _this.pass; }, true));
  66757. if (!this._hdr) {
  66758. this.highlights = new BABYLON.HighlightsPostProcess("highlights", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  66759. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.HighLightsPostProcessId, function () { return _this.highlights; }, true));
  66760. this.highlights.autoClear = false;
  66761. this.highlights.alwaysForcePOT = true;
  66762. }
  66763. 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);
  66764. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurXPostProcessId, function () { return _this.blurX; }, true));
  66765. this.blurX.alwaysForcePOT = true;
  66766. this.blurX.autoClear = false;
  66767. this.blurX.onActivateObservable.add(function () {
  66768. var dw = _this.blurX.width / engine.getRenderWidth(true);
  66769. _this.blurX.kernel = _this.bloomKernel * dw;
  66770. });
  66771. 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);
  66772. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurYPostProcessId, function () { return _this.blurY; }, true));
  66773. this.blurY.alwaysForcePOT = true;
  66774. this.blurY.autoClear = false;
  66775. this.blurY.onActivateObservable.add(function () {
  66776. var dh = _this.blurY.height / engine.getRenderHeight(true);
  66777. _this.blurY.kernel = _this.bloomKernel * dh;
  66778. });
  66779. this.copyBack = new BABYLON.PassPostProcess("bloomBlendBlit", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  66780. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.CopyBackPostProcessId, function () { return _this.copyBack; }, true));
  66781. this.copyBack.alwaysForcePOT = true;
  66782. if (this._hdr) {
  66783. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_INTERPOLATE;
  66784. var w = this.bloomWeight;
  66785. this.copyBack.alphaConstants = new BABYLON.Color4(w, w, w, w);
  66786. }
  66787. else {
  66788. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_SCREENMODE;
  66789. }
  66790. this.copyBack.autoClear = false;
  66791. }
  66792. if (this._imageProcessingEnabled) {
  66793. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  66794. if (this._hdr) {
  66795. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  66796. }
  66797. else {
  66798. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  66799. }
  66800. }
  66801. if (this.fxaaEnabled) {
  66802. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  66803. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  66804. this.fxaa.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  66805. }
  66806. else if (this._hdr && this.imageProcessing) {
  66807. this.finalMerge = this.imageProcessing;
  66808. }
  66809. else {
  66810. this.finalMerge = new BABYLON.PassPostProcess("finalMerge", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  66811. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FinalMergePostProcessId, function () { return _this.finalMerge; }, true));
  66812. this.finalMerge.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  66813. }
  66814. if (this.bloomEnabled) {
  66815. if (this._hdr) {
  66816. this.copyBack.shareOutputWith(this.blurX);
  66817. if (this.imageProcessing) {
  66818. this.imageProcessing.shareOutputWith(this.pass);
  66819. this.imageProcessing.autoClear = false;
  66820. }
  66821. else if (this.fxaa) {
  66822. this.fxaa.shareOutputWith(this.pass);
  66823. }
  66824. else {
  66825. this.finalMerge.shareOutputWith(this.pass);
  66826. }
  66827. }
  66828. else {
  66829. if (this.fxaa) {
  66830. this.fxaa.shareOutputWith(this.pass);
  66831. }
  66832. else {
  66833. this.finalMerge.shareOutputWith(this.pass);
  66834. }
  66835. }
  66836. }
  66837. if (this._cameras !== null) {
  66838. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  66839. }
  66840. };
  66841. DefaultRenderingPipeline.prototype._disposePostProcesses = function () {
  66842. for (var i = 0; i < this._cameras.length; i++) {
  66843. var camera = this._cameras[i];
  66844. if (this.pass) {
  66845. this.pass.dispose(camera);
  66846. }
  66847. if (this.highlights) {
  66848. this.highlights.dispose(camera);
  66849. }
  66850. if (this.blurX) {
  66851. this.blurX.dispose(camera);
  66852. }
  66853. if (this.blurY) {
  66854. this.blurY.dispose(camera);
  66855. }
  66856. if (this.copyBack) {
  66857. this.copyBack.dispose(camera);
  66858. }
  66859. if (this.imageProcessing) {
  66860. this.imageProcessing.dispose(camera);
  66861. }
  66862. if (this.fxaa) {
  66863. this.fxaa.dispose(camera);
  66864. }
  66865. if (this.finalMerge) {
  66866. this.finalMerge.dispose(camera);
  66867. }
  66868. if (this.depthOfField) {
  66869. this.depthOfField.disposeEffects(camera);
  66870. }
  66871. }
  66872. this.pass = null;
  66873. this.highlights = null;
  66874. this.blurX = null;
  66875. this.blurY = null;
  66876. this.copyBack = null;
  66877. this.imageProcessing = null;
  66878. this.fxaa = null;
  66879. this.finalMerge = null;
  66880. this.depthOfField = null;
  66881. };
  66882. /**
  66883. * Dispose of the pipeline and stop all post processes
  66884. */
  66885. DefaultRenderingPipeline.prototype.dispose = function () {
  66886. this._disposePostProcesses();
  66887. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  66888. _super.prototype.dispose.call(this);
  66889. };
  66890. /**
  66891. * Serialize the rendering pipeline (Used when exporting)
  66892. * @returns the serialized object
  66893. */
  66894. DefaultRenderingPipeline.prototype.serialize = function () {
  66895. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  66896. serializationObject.customType = "DefaultRenderingPipeline";
  66897. return serializationObject;
  66898. };
  66899. /**
  66900. * Parse the serialized pipeline
  66901. * @param source Source pipeline.
  66902. * @param scene The scene to load the pipeline to.
  66903. * @param rootUrl The URL of the serialized pipeline.
  66904. * @returns An instantiated pipeline from the serialized object.
  66905. */
  66906. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  66907. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  66908. };
  66909. __decorate([
  66910. BABYLON.serialize()
  66911. ], DefaultRenderingPipeline.prototype, "bloomKernel", void 0);
  66912. __decorate([
  66913. BABYLON.serialize()
  66914. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  66915. __decorate([
  66916. BABYLON.serialize()
  66917. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  66918. __decorate([
  66919. BABYLON.serialize()
  66920. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  66921. __decorate([
  66922. BABYLON.serialize()
  66923. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  66924. __decorate([
  66925. BABYLON.serialize()
  66926. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  66927. __decorate([
  66928. BABYLON.serialize()
  66929. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  66930. __decorate([
  66931. BABYLON.serialize()
  66932. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  66933. __decorate([
  66934. BABYLON.serialize()
  66935. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  66936. __decorate([
  66937. BABYLON.serialize()
  66938. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  66939. return DefaultRenderingPipeline;
  66940. }(BABYLON.PostProcessRenderPipeline));
  66941. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  66942. })(BABYLON || (BABYLON = {}));
  66943. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  66944. var BABYLON;
  66945. (function (BABYLON) {
  66946. /**
  66947. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  66948. */
  66949. var GeometryBufferRenderer = /** @class */ (function () {
  66950. /**
  66951. * Creates a new G Buffer for the scene. @see GeometryBufferRenderer
  66952. * @param scene The scene the buffer belongs to
  66953. * @param ratio How big is the buffer related to the main canvas.
  66954. */
  66955. function GeometryBufferRenderer(scene, ratio) {
  66956. if (ratio === void 0) { ratio = 1; }
  66957. this._enablePosition = false;
  66958. this._scene = scene;
  66959. this._ratio = ratio;
  66960. // Render target
  66961. this._createRenderTargets();
  66962. }
  66963. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  66964. /**
  66965. * Set the render list (meshes to be rendered) used in the G buffer.
  66966. */
  66967. set: function (meshes) {
  66968. this._multiRenderTarget.renderList = meshes;
  66969. },
  66970. enumerable: true,
  66971. configurable: true
  66972. });
  66973. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  66974. /**
  66975. * Gets wether or not G buffer are supported by the running hardware.
  66976. * This requires draw buffer supports
  66977. */
  66978. get: function () {
  66979. return this._multiRenderTarget.isSupported;
  66980. },
  66981. enumerable: true,
  66982. configurable: true
  66983. });
  66984. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  66985. /**
  66986. * Gets wether or not position are enabled for the G buffer.
  66987. */
  66988. get: function () {
  66989. return this._enablePosition;
  66990. },
  66991. /**
  66992. * Sets wether or not position are enabled for the G buffer.
  66993. */
  66994. set: function (enable) {
  66995. this._enablePosition = enable;
  66996. this.dispose();
  66997. this._createRenderTargets();
  66998. },
  66999. enumerable: true,
  67000. configurable: true
  67001. });
  67002. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  67003. /**
  67004. * Gets the scene associated with the buffer.
  67005. */
  67006. get: function () {
  67007. return this._scene;
  67008. },
  67009. enumerable: true,
  67010. configurable: true
  67011. });
  67012. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  67013. /**
  67014. * Gets the ratio used by the buffer during its creation.
  67015. * How big is the buffer related to the main canvas.
  67016. */
  67017. get: function () {
  67018. return this._ratio;
  67019. },
  67020. enumerable: true,
  67021. configurable: true
  67022. });
  67023. /**
  67024. * Checks wether everything is ready to render a submesh to the G buffer.
  67025. * @param subMesh the submesh to check readiness for
  67026. * @param useInstances is the mesh drawn using instance or not
  67027. * @returns true if ready otherwise false
  67028. */
  67029. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  67030. var material = subMesh.getMaterial();
  67031. if (material && material.disableDepthWrite) {
  67032. return false;
  67033. }
  67034. var defines = [];
  67035. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  67036. var mesh = subMesh.getMesh();
  67037. // Alpha test
  67038. if (material && material.needAlphaTesting()) {
  67039. defines.push("#define ALPHATEST");
  67040. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  67041. attribs.push(BABYLON.VertexBuffer.UVKind);
  67042. defines.push("#define UV1");
  67043. }
  67044. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  67045. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  67046. defines.push("#define UV2");
  67047. }
  67048. }
  67049. // Buffers
  67050. if (this._enablePosition) {
  67051. defines.push("#define POSITION");
  67052. }
  67053. // Bones
  67054. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  67055. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  67056. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  67057. if (mesh.numBoneInfluencers > 4) {
  67058. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  67059. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  67060. }
  67061. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  67062. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  67063. }
  67064. else {
  67065. defines.push("#define NUM_BONE_INFLUENCERS 0");
  67066. }
  67067. // Instances
  67068. if (useInstances) {
  67069. defines.push("#define INSTANCES");
  67070. attribs.push("world0");
  67071. attribs.push("world1");
  67072. attribs.push("world2");
  67073. attribs.push("world3");
  67074. }
  67075. // Get correct effect
  67076. var join = defines.join("\n");
  67077. if (this._cachedDefines !== join) {
  67078. this._cachedDefines = join;
  67079. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  67080. }
  67081. return this._effect.isReady();
  67082. };
  67083. /**
  67084. * Gets the current underlying G Buffer.
  67085. * @returns the buffer
  67086. */
  67087. GeometryBufferRenderer.prototype.getGBuffer = function () {
  67088. return this._multiRenderTarget;
  67089. };
  67090. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  67091. /**
  67092. * Gets the number of samples used to render the buffer (anti aliasing).
  67093. */
  67094. get: function () {
  67095. return this._multiRenderTarget.samples;
  67096. },
  67097. /**
  67098. * Sets the number of samples used to render the buffer (anti aliasing).
  67099. */
  67100. set: function (value) {
  67101. this._multiRenderTarget.samples = value;
  67102. },
  67103. enumerable: true,
  67104. configurable: true
  67105. });
  67106. /**
  67107. * Disposes the renderer and frees up associated resources.
  67108. */
  67109. GeometryBufferRenderer.prototype.dispose = function () {
  67110. this.getGBuffer().dispose();
  67111. };
  67112. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  67113. var _this = this;
  67114. var engine = this._scene.getEngine();
  67115. var count = this._enablePosition ? 3 : 2;
  67116. 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 });
  67117. if (!this.isSupported) {
  67118. return;
  67119. }
  67120. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67121. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67122. this._multiRenderTarget.refreshRate = 1;
  67123. this._multiRenderTarget.renderParticles = false;
  67124. this._multiRenderTarget.renderList = null;
  67125. // set default depth value to 1.0 (far away)
  67126. this._multiRenderTarget.onClearObservable.add(function (engine) {
  67127. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  67128. });
  67129. // Custom render function
  67130. var renderSubMesh = function (subMesh) {
  67131. var mesh = subMesh.getRenderingMesh();
  67132. var scene = _this._scene;
  67133. var engine = scene.getEngine();
  67134. var material = subMesh.getMaterial();
  67135. if (!material) {
  67136. return;
  67137. }
  67138. // Culling
  67139. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  67140. // Managing instances
  67141. var batch = mesh._getInstancesRenderList(subMesh._id);
  67142. if (batch.mustReturn) {
  67143. return;
  67144. }
  67145. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  67146. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  67147. engine.enableEffect(_this._effect);
  67148. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  67149. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  67150. _this._effect.setMatrix("view", scene.getViewMatrix());
  67151. // Alpha test
  67152. if (material && material.needAlphaTesting()) {
  67153. var alphaTexture = material.getAlphaTestTexture();
  67154. if (alphaTexture) {
  67155. _this._effect.setTexture("diffuseSampler", alphaTexture);
  67156. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  67157. }
  67158. }
  67159. // Bones
  67160. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  67161. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  67162. }
  67163. // Draw
  67164. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  67165. }
  67166. };
  67167. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  67168. var index;
  67169. if (depthOnlySubMeshes.length) {
  67170. engine.setColorWrite(false);
  67171. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  67172. renderSubMesh(depthOnlySubMeshes.data[index]);
  67173. }
  67174. engine.setColorWrite(true);
  67175. }
  67176. for (index = 0; index < opaqueSubMeshes.length; index++) {
  67177. renderSubMesh(opaqueSubMeshes.data[index]);
  67178. }
  67179. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  67180. renderSubMesh(alphaTestSubMeshes.data[index]);
  67181. }
  67182. };
  67183. };
  67184. return GeometryBufferRenderer;
  67185. }());
  67186. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  67187. })(BABYLON || (BABYLON = {}));
  67188. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  67189. var BABYLON;
  67190. (function (BABYLON) {
  67191. var RefractionPostProcess = /** @class */ (function (_super) {
  67192. __extends(RefractionPostProcess, _super);
  67193. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  67194. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  67195. _this.color = color;
  67196. _this.depth = depth;
  67197. _this.colorLevel = colorLevel;
  67198. _this.onActivateObservable.add(function (cam) {
  67199. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  67200. });
  67201. _this.onApplyObservable.add(function (effect) {
  67202. effect.setColor3("baseColor", _this.color);
  67203. effect.setFloat("depth", _this.depth);
  67204. effect.setFloat("colorLevel", _this.colorLevel);
  67205. effect.setTexture("refractionSampler", _this._refRexture);
  67206. });
  67207. return _this;
  67208. }
  67209. // Methods
  67210. RefractionPostProcess.prototype.dispose = function (camera) {
  67211. if (this._refRexture) {
  67212. this._refRexture.dispose();
  67213. }
  67214. _super.prototype.dispose.call(this, camera);
  67215. };
  67216. return RefractionPostProcess;
  67217. }(BABYLON.PostProcess));
  67218. BABYLON.RefractionPostProcess = RefractionPostProcess;
  67219. })(BABYLON || (BABYLON = {}));
  67220. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  67221. var BABYLON;
  67222. (function (BABYLON) {
  67223. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  67224. __extends(BlackAndWhitePostProcess, _super);
  67225. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  67226. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  67227. _this.degree = 1;
  67228. _this.onApplyObservable.add(function (effect) {
  67229. effect.setFloat("degree", _this.degree);
  67230. });
  67231. return _this;
  67232. }
  67233. return BlackAndWhitePostProcess;
  67234. }(BABYLON.PostProcess));
  67235. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  67236. })(BABYLON || (BABYLON = {}));
  67237. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  67238. var BABYLON;
  67239. (function (BABYLON) {
  67240. var ConvolutionPostProcess = /** @class */ (function (_super) {
  67241. __extends(ConvolutionPostProcess, _super);
  67242. function ConvolutionPostProcess(name, kernel, options, camera, samplingMode, engine, reusable) {
  67243. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable) || this;
  67244. _this.kernel = kernel;
  67245. _this.onApply = function (effect) {
  67246. effect.setFloat2("screenSize", _this.width, _this.height);
  67247. effect.setArray("kernel", _this.kernel);
  67248. };
  67249. return _this;
  67250. }
  67251. // Statics
  67252. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  67253. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  67254. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  67255. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  67256. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  67257. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  67258. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  67259. return ConvolutionPostProcess;
  67260. }(BABYLON.PostProcess));
  67261. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  67262. })(BABYLON || (BABYLON = {}));
  67263. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  67264. var BABYLON;
  67265. (function (BABYLON) {
  67266. var FilterPostProcess = /** @class */ (function (_super) {
  67267. __extends(FilterPostProcess, _super);
  67268. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  67269. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  67270. _this.kernelMatrix = kernelMatrix;
  67271. _this.onApply = function (effect) {
  67272. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  67273. };
  67274. return _this;
  67275. }
  67276. return FilterPostProcess;
  67277. }(BABYLON.PostProcess));
  67278. BABYLON.FilterPostProcess = FilterPostProcess;
  67279. })(BABYLON || (BABYLON = {}));
  67280. //# sourceMappingURL=babylon.filterPostProcess.js.map
  67281. var BABYLON;
  67282. (function (BABYLON) {
  67283. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  67284. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  67285. __extends(VolumetricLightScatteringPostProcess, _super);
  67286. /**
  67287. * @constructor
  67288. * @param {string} name - The post-process name
  67289. * @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)
  67290. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  67291. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  67292. * @param {number} samples - The post-process quality, default 100
  67293. * @param {number} samplingMode - The post-process filtering mode
  67294. * @param {BABYLON.Engine} engine - The babylon engine
  67295. * @param {boolean} reusable - If the post-process is reusable
  67296. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  67297. */
  67298. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  67299. if (samples === void 0) { samples = 100; }
  67300. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  67301. 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;
  67302. _this._screenCoordinates = BABYLON.Vector2.Zero();
  67303. /**
  67304. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  67305. * @type {Vector3}
  67306. */
  67307. _this.customMeshPosition = BABYLON.Vector3.Zero();
  67308. /**
  67309. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  67310. * @type {boolean}
  67311. */
  67312. _this.useCustomMeshPosition = false;
  67313. /**
  67314. * If the post-process should inverse the light scattering direction
  67315. * @type {boolean}
  67316. */
  67317. _this.invert = true;
  67318. /**
  67319. * Array containing the excluded meshes not rendered in the internal pass
  67320. */
  67321. _this.excludedMeshes = new Array();
  67322. /**
  67323. * Controls the overall intensity of the post-process
  67324. * @type {number}
  67325. */
  67326. _this.exposure = 0.3;
  67327. /**
  67328. * Dissipates each sample's contribution in range [0, 1]
  67329. * @type {number}
  67330. */
  67331. _this.decay = 0.96815;
  67332. /**
  67333. * Controls the overall intensity of each sample
  67334. * @type {number}
  67335. */
  67336. _this.weight = 0.58767;
  67337. /**
  67338. * Controls the density of each sample
  67339. * @type {number}
  67340. */
  67341. _this.density = 0.926;
  67342. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  67343. engine = scene.getEngine();
  67344. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  67345. // Configure mesh
  67346. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  67347. // Configure
  67348. _this._createPass(scene, ratio.passRatio || ratio);
  67349. _this.onActivate = function (camera) {
  67350. if (!_this.isSupported) {
  67351. _this.dispose(camera);
  67352. }
  67353. _this.onActivate = null;
  67354. };
  67355. _this.onApplyObservable.add(function (effect) {
  67356. _this._updateMeshScreenCoordinates(scene);
  67357. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  67358. effect.setFloat("exposure", _this.exposure);
  67359. effect.setFloat("decay", _this.decay);
  67360. effect.setFloat("weight", _this.weight);
  67361. effect.setFloat("density", _this.density);
  67362. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  67363. });
  67364. return _this;
  67365. }
  67366. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  67367. get: function () {
  67368. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  67369. return false;
  67370. },
  67371. set: function (useDiffuseColor) {
  67372. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  67373. },
  67374. enumerable: true,
  67375. configurable: true
  67376. });
  67377. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  67378. return "VolumetricLightScatteringPostProcess";
  67379. };
  67380. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  67381. var mesh = subMesh.getMesh();
  67382. // Render this.mesh as default
  67383. if (mesh === this.mesh && mesh.material) {
  67384. return mesh.material.isReady(mesh);
  67385. }
  67386. var defines = [];
  67387. var attribs = [BABYLON.VertexBuffer.PositionKind];
  67388. var material = subMesh.getMaterial();
  67389. // Alpha test
  67390. if (material) {
  67391. if (material.needAlphaTesting()) {
  67392. defines.push("#define ALPHATEST");
  67393. }
  67394. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  67395. attribs.push(BABYLON.VertexBuffer.UVKind);
  67396. defines.push("#define UV1");
  67397. }
  67398. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  67399. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  67400. defines.push("#define UV2");
  67401. }
  67402. }
  67403. // Bones
  67404. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  67405. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  67406. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  67407. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  67408. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  67409. }
  67410. else {
  67411. defines.push("#define NUM_BONE_INFLUENCERS 0");
  67412. }
  67413. // Instances
  67414. if (useInstances) {
  67415. defines.push("#define INSTANCES");
  67416. attribs.push("world0");
  67417. attribs.push("world1");
  67418. attribs.push("world2");
  67419. attribs.push("world3");
  67420. }
  67421. // Get correct effect
  67422. var join = defines.join("\n");
  67423. if (this._cachedDefines !== join) {
  67424. this._cachedDefines = join;
  67425. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  67426. }
  67427. return this._volumetricLightScatteringPass.isReady();
  67428. };
  67429. /**
  67430. * Sets the new light position for light scattering effect
  67431. * @param {BABYLON.Vector3} The new custom light position
  67432. */
  67433. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  67434. this.customMeshPosition = position;
  67435. };
  67436. /**
  67437. * Returns the light position for light scattering effect
  67438. * @return {BABYLON.Vector3} The custom light position
  67439. */
  67440. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  67441. return this.customMeshPosition;
  67442. };
  67443. /**
  67444. * Disposes the internal assets and detaches the post-process from the camera
  67445. */
  67446. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  67447. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  67448. if (rttIndex !== -1) {
  67449. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  67450. }
  67451. this._volumetricLightScatteringRTT.dispose();
  67452. _super.prototype.dispose.call(this, camera);
  67453. };
  67454. /**
  67455. * Returns the render target texture used by the post-process
  67456. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  67457. */
  67458. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  67459. return this._volumetricLightScatteringRTT;
  67460. };
  67461. // Private methods
  67462. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  67463. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  67464. return true;
  67465. }
  67466. return false;
  67467. };
  67468. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  67469. var _this = this;
  67470. var engine = scene.getEngine();
  67471. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  67472. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67473. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67474. this._volumetricLightScatteringRTT.renderList = null;
  67475. this._volumetricLightScatteringRTT.renderParticles = false;
  67476. var camera = this.getCamera();
  67477. if (camera) {
  67478. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  67479. }
  67480. else {
  67481. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  67482. }
  67483. // Custom render function for submeshes
  67484. var renderSubMesh = function (subMesh) {
  67485. var mesh = subMesh.getRenderingMesh();
  67486. if (_this._meshExcluded(mesh)) {
  67487. return;
  67488. }
  67489. var material = subMesh.getMaterial();
  67490. if (!material) {
  67491. return;
  67492. }
  67493. var scene = mesh.getScene();
  67494. var engine = scene.getEngine();
  67495. // Culling
  67496. engine.setState(material.backFaceCulling);
  67497. // Managing instances
  67498. var batch = mesh._getInstancesRenderList(subMesh._id);
  67499. if (batch.mustReturn) {
  67500. return;
  67501. }
  67502. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  67503. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  67504. var effect = _this._volumetricLightScatteringPass;
  67505. if (mesh === _this.mesh) {
  67506. if (subMesh.effect) {
  67507. effect = subMesh.effect;
  67508. }
  67509. else {
  67510. effect = material.getEffect();
  67511. }
  67512. }
  67513. engine.enableEffect(effect);
  67514. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  67515. if (mesh === _this.mesh) {
  67516. material.bind(mesh.getWorldMatrix(), mesh);
  67517. }
  67518. else {
  67519. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  67520. // Alpha test
  67521. if (material && material.needAlphaTesting()) {
  67522. var alphaTexture = material.getAlphaTestTexture();
  67523. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  67524. if (alphaTexture) {
  67525. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  67526. }
  67527. }
  67528. // Bones
  67529. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  67530. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  67531. }
  67532. }
  67533. // Draw
  67534. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  67535. }
  67536. };
  67537. // Render target texture callbacks
  67538. var savedSceneClearColor;
  67539. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  67540. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  67541. savedSceneClearColor = scene.clearColor;
  67542. scene.clearColor = sceneClearColor;
  67543. });
  67544. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  67545. scene.clearColor = savedSceneClearColor;
  67546. });
  67547. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  67548. var engine = scene.getEngine();
  67549. var index;
  67550. if (depthOnlySubMeshes.length) {
  67551. engine.setColorWrite(false);
  67552. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  67553. renderSubMesh(depthOnlySubMeshes.data[index]);
  67554. }
  67555. engine.setColorWrite(true);
  67556. }
  67557. for (index = 0; index < opaqueSubMeshes.length; index++) {
  67558. renderSubMesh(opaqueSubMeshes.data[index]);
  67559. }
  67560. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  67561. renderSubMesh(alphaTestSubMeshes.data[index]);
  67562. }
  67563. if (transparentSubMeshes.length) {
  67564. // Sort sub meshes
  67565. for (index = 0; index < transparentSubMeshes.length; index++) {
  67566. var submesh = transparentSubMeshes.data[index];
  67567. var boundingInfo = submesh.getBoundingInfo();
  67568. if (boundingInfo && scene.activeCamera) {
  67569. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  67570. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  67571. }
  67572. }
  67573. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  67574. sortedArray.sort(function (a, b) {
  67575. // Alpha index first
  67576. if (a._alphaIndex > b._alphaIndex) {
  67577. return 1;
  67578. }
  67579. if (a._alphaIndex < b._alphaIndex) {
  67580. return -1;
  67581. }
  67582. // Then distance to camera
  67583. if (a._distanceToCamera < b._distanceToCamera) {
  67584. return 1;
  67585. }
  67586. if (a._distanceToCamera > b._distanceToCamera) {
  67587. return -1;
  67588. }
  67589. return 0;
  67590. });
  67591. // Render sub meshes
  67592. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  67593. for (index = 0; index < sortedArray.length; index++) {
  67594. renderSubMesh(sortedArray[index]);
  67595. }
  67596. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  67597. }
  67598. };
  67599. };
  67600. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  67601. var transform = scene.getTransformMatrix();
  67602. var meshPosition;
  67603. if (this.useCustomMeshPosition) {
  67604. meshPosition = this.customMeshPosition;
  67605. }
  67606. else if (this.attachedNode) {
  67607. meshPosition = this.attachedNode.position;
  67608. }
  67609. else {
  67610. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  67611. }
  67612. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  67613. this._screenCoordinates.x = pos.x / this._viewPort.width;
  67614. this._screenCoordinates.y = pos.y / this._viewPort.height;
  67615. if (this.invert)
  67616. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  67617. };
  67618. // Static methods
  67619. /**
  67620. * Creates a default mesh for the Volumeric Light Scattering post-process
  67621. * @param {string} The mesh name
  67622. * @param {BABYLON.Scene} The scene where to create the mesh
  67623. * @return {BABYLON.Mesh} the default mesh
  67624. */
  67625. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  67626. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  67627. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  67628. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  67629. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  67630. mesh.material = material;
  67631. return mesh;
  67632. };
  67633. __decorate([
  67634. BABYLON.serializeAsVector3()
  67635. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  67636. __decorate([
  67637. BABYLON.serialize()
  67638. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  67639. __decorate([
  67640. BABYLON.serialize()
  67641. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  67642. __decorate([
  67643. BABYLON.serializeAsMeshReference()
  67644. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  67645. __decorate([
  67646. BABYLON.serialize()
  67647. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  67648. __decorate([
  67649. BABYLON.serialize()
  67650. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  67651. __decorate([
  67652. BABYLON.serialize()
  67653. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  67654. __decorate([
  67655. BABYLON.serialize()
  67656. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  67657. __decorate([
  67658. BABYLON.serialize()
  67659. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  67660. return VolumetricLightScatteringPostProcess;
  67661. }(BABYLON.PostProcess));
  67662. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  67663. })(BABYLON || (BABYLON = {}));
  67664. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  67665. //
  67666. // This post-process allows the modification of rendered colors by using
  67667. // a 'look-up table' (LUT). This effect is also called Color Grading.
  67668. //
  67669. // The object needs to be provided an url to a texture containing the color
  67670. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  67671. // Use an image editing software to tweak the LUT to match your needs.
  67672. //
  67673. // For an example of a color LUT, see here:
  67674. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  67675. // For explanations on color grading, see here:
  67676. // http://udn.epicgames.com/Three/ColorGrading.html
  67677. //
  67678. var BABYLON;
  67679. (function (BABYLON) {
  67680. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  67681. __extends(ColorCorrectionPostProcess, _super);
  67682. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  67683. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  67684. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  67685. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  67686. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67687. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67688. _this.onApply = function (effect) {
  67689. effect.setTexture("colorTable", _this._colorTableTexture);
  67690. };
  67691. return _this;
  67692. }
  67693. return ColorCorrectionPostProcess;
  67694. }(BABYLON.PostProcess));
  67695. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  67696. })(BABYLON || (BABYLON = {}));
  67697. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  67698. var BABYLON;
  67699. (function (BABYLON) {
  67700. var TonemappingOperator;
  67701. (function (TonemappingOperator) {
  67702. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  67703. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  67704. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  67705. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  67706. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  67707. ;
  67708. var TonemapPostProcess = /** @class */ (function (_super) {
  67709. __extends(TonemapPostProcess, _super);
  67710. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  67711. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  67712. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  67713. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  67714. _this._operator = _operator;
  67715. _this.exposureAdjustment = exposureAdjustment;
  67716. var defines = "#define ";
  67717. if (_this._operator === TonemappingOperator.Hable)
  67718. defines += "HABLE_TONEMAPPING";
  67719. else if (_this._operator === TonemappingOperator.Reinhard)
  67720. defines += "REINHARD_TONEMAPPING";
  67721. else if (_this._operator === TonemappingOperator.HejiDawson)
  67722. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  67723. else if (_this._operator === TonemappingOperator.Photographic)
  67724. defines += "PHOTOGRAPHIC_TONEMAPPING";
  67725. //sadly a second call to create the effect.
  67726. _this.updateEffect(defines);
  67727. _this.onApply = function (effect) {
  67728. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  67729. };
  67730. return _this;
  67731. }
  67732. return TonemapPostProcess;
  67733. }(BABYLON.PostProcess));
  67734. BABYLON.TonemapPostProcess = TonemapPostProcess;
  67735. })(BABYLON || (BABYLON = {}));
  67736. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  67737. var BABYLON;
  67738. (function (BABYLON) {
  67739. var DisplayPassPostProcess = /** @class */ (function (_super) {
  67740. __extends(DisplayPassPostProcess, _super);
  67741. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  67742. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  67743. }
  67744. return DisplayPassPostProcess;
  67745. }(BABYLON.PostProcess));
  67746. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  67747. })(BABYLON || (BABYLON = {}));
  67748. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  67749. var BABYLON;
  67750. (function (BABYLON) {
  67751. var HighlightsPostProcess = /** @class */ (function (_super) {
  67752. __extends(HighlightsPostProcess, _super);
  67753. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  67754. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  67755. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  67756. }
  67757. return HighlightsPostProcess;
  67758. }(BABYLON.PostProcess));
  67759. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  67760. })(BABYLON || (BABYLON = {}));
  67761. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  67762. var BABYLON;
  67763. (function (BABYLON) {
  67764. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  67765. __extends(ImageProcessingPostProcess, _super);
  67766. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  67767. if (camera === void 0) { camera = null; }
  67768. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  67769. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  67770. _this._fromLinearSpace = true;
  67771. /**
  67772. * Defines cache preventing GC.
  67773. */
  67774. _this._defines = {
  67775. IMAGEPROCESSING: false,
  67776. VIGNETTE: false,
  67777. VIGNETTEBLENDMODEMULTIPLY: false,
  67778. VIGNETTEBLENDMODEOPAQUE: false,
  67779. TONEMAPPING: false,
  67780. CONTRAST: false,
  67781. COLORCURVES: false,
  67782. COLORGRADING: false,
  67783. COLORGRADING3D: false,
  67784. FROMLINEARSPACE: false,
  67785. SAMPLER3DGREENDEPTH: false,
  67786. SAMPLER3DBGRMAP: false,
  67787. IMAGEPROCESSINGPOSTPROCESS: false,
  67788. EXPOSURE: false,
  67789. };
  67790. // Setup the configuration as forced by the constructor. This would then not force the
  67791. // scene materials output in linear space and let untouched the default forward pass.
  67792. if (imageProcessingConfiguration) {
  67793. imageProcessingConfiguration.applyByPostProcess = true;
  67794. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  67795. // This will cause the shader to be compiled
  67796. _this.fromLinearSpace = false;
  67797. }
  67798. else {
  67799. _this._attachImageProcessingConfiguration(null, true);
  67800. _this.imageProcessingConfiguration.applyByPostProcess = true;
  67801. }
  67802. _this.onApply = function (effect) {
  67803. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  67804. };
  67805. return _this;
  67806. }
  67807. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  67808. /**
  67809. * Gets the image processing configuration used either in this material.
  67810. */
  67811. get: function () {
  67812. return this._imageProcessingConfiguration;
  67813. },
  67814. /**
  67815. * Sets the Default image processing configuration used either in the this material.
  67816. *
  67817. * If sets to null, the scene one is in use.
  67818. */
  67819. set: function (value) {
  67820. this._attachImageProcessingConfiguration(value);
  67821. },
  67822. enumerable: true,
  67823. configurable: true
  67824. });
  67825. /**
  67826. * Attaches a new image processing configuration to the PBR Material.
  67827. * @param configuration
  67828. */
  67829. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  67830. var _this = this;
  67831. if (doNotBuild === void 0) { doNotBuild = false; }
  67832. if (configuration === this._imageProcessingConfiguration) {
  67833. return;
  67834. }
  67835. // Detaches observer.
  67836. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  67837. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  67838. }
  67839. // Pick the scene configuration if needed.
  67840. if (!configuration) {
  67841. var scene = null;
  67842. var engine = this.getEngine();
  67843. var camera = this.getCamera();
  67844. if (camera) {
  67845. scene = camera.getScene();
  67846. }
  67847. else if (engine && engine.scenes) {
  67848. var scenes = engine.scenes;
  67849. scene = scenes[scenes.length - 1];
  67850. }
  67851. else {
  67852. scene = BABYLON.Engine.LastCreatedScene;
  67853. }
  67854. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  67855. }
  67856. else {
  67857. this._imageProcessingConfiguration = configuration;
  67858. }
  67859. // Attaches observer.
  67860. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  67861. _this._updateParameters();
  67862. });
  67863. // Ensure the effect will be rebuilt.
  67864. if (!doNotBuild) {
  67865. this._updateParameters();
  67866. }
  67867. };
  67868. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  67869. /**
  67870. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  67871. */
  67872. get: function () {
  67873. return this.imageProcessingConfiguration.colorCurves;
  67874. },
  67875. /**
  67876. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  67877. */
  67878. set: function (value) {
  67879. this.imageProcessingConfiguration.colorCurves = value;
  67880. },
  67881. enumerable: true,
  67882. configurable: true
  67883. });
  67884. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  67885. /**
  67886. * Gets wether the color curves effect is enabled.
  67887. */
  67888. get: function () {
  67889. return this.imageProcessingConfiguration.colorCurvesEnabled;
  67890. },
  67891. /**
  67892. * Sets wether the color curves effect is enabled.
  67893. */
  67894. set: function (value) {
  67895. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  67896. },
  67897. enumerable: true,
  67898. configurable: true
  67899. });
  67900. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  67901. /**
  67902. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  67903. */
  67904. get: function () {
  67905. return this.imageProcessingConfiguration.colorGradingTexture;
  67906. },
  67907. /**
  67908. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  67909. */
  67910. set: function (value) {
  67911. this.imageProcessingConfiguration.colorGradingTexture = value;
  67912. },
  67913. enumerable: true,
  67914. configurable: true
  67915. });
  67916. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  67917. /**
  67918. * Gets wether the color grading effect is enabled.
  67919. */
  67920. get: function () {
  67921. return this.imageProcessingConfiguration.colorGradingEnabled;
  67922. },
  67923. /**
  67924. * Gets wether the color grading effect is enabled.
  67925. */
  67926. set: function (value) {
  67927. this.imageProcessingConfiguration.colorGradingEnabled = value;
  67928. },
  67929. enumerable: true,
  67930. configurable: true
  67931. });
  67932. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  67933. /**
  67934. * Gets exposure used in the effect.
  67935. */
  67936. get: function () {
  67937. return this.imageProcessingConfiguration.exposure;
  67938. },
  67939. /**
  67940. * Sets exposure used in the effect.
  67941. */
  67942. set: function (value) {
  67943. this.imageProcessingConfiguration.exposure = value;
  67944. },
  67945. enumerable: true,
  67946. configurable: true
  67947. });
  67948. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  67949. /**
  67950. * Gets wether tonemapping is enabled or not.
  67951. */
  67952. get: function () {
  67953. return this._imageProcessingConfiguration.toneMappingEnabled;
  67954. },
  67955. /**
  67956. * Sets wether tonemapping is enabled or not
  67957. */
  67958. set: function (value) {
  67959. this._imageProcessingConfiguration.toneMappingEnabled = value;
  67960. },
  67961. enumerable: true,
  67962. configurable: true
  67963. });
  67964. ;
  67965. ;
  67966. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  67967. /**
  67968. * Gets contrast used in the effect.
  67969. */
  67970. get: function () {
  67971. return this.imageProcessingConfiguration.contrast;
  67972. },
  67973. /**
  67974. * Sets contrast used in the effect.
  67975. */
  67976. set: function (value) {
  67977. this.imageProcessingConfiguration.contrast = value;
  67978. },
  67979. enumerable: true,
  67980. configurable: true
  67981. });
  67982. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  67983. /**
  67984. * Gets Vignette stretch size.
  67985. */
  67986. get: function () {
  67987. return this.imageProcessingConfiguration.vignetteStretch;
  67988. },
  67989. /**
  67990. * Sets Vignette stretch size.
  67991. */
  67992. set: function (value) {
  67993. this.imageProcessingConfiguration.vignetteStretch = value;
  67994. },
  67995. enumerable: true,
  67996. configurable: true
  67997. });
  67998. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  67999. /**
  68000. * Gets Vignette centre X Offset.
  68001. */
  68002. get: function () {
  68003. return this.imageProcessingConfiguration.vignetteCentreX;
  68004. },
  68005. /**
  68006. * Sets Vignette centre X Offset.
  68007. */
  68008. set: function (value) {
  68009. this.imageProcessingConfiguration.vignetteCentreX = value;
  68010. },
  68011. enumerable: true,
  68012. configurable: true
  68013. });
  68014. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  68015. /**
  68016. * Gets Vignette centre Y Offset.
  68017. */
  68018. get: function () {
  68019. return this.imageProcessingConfiguration.vignetteCentreY;
  68020. },
  68021. /**
  68022. * Sets Vignette centre Y Offset.
  68023. */
  68024. set: function (value) {
  68025. this.imageProcessingConfiguration.vignetteCentreY = value;
  68026. },
  68027. enumerable: true,
  68028. configurable: true
  68029. });
  68030. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  68031. /**
  68032. * Gets Vignette weight or intensity of the vignette effect.
  68033. */
  68034. get: function () {
  68035. return this.imageProcessingConfiguration.vignetteWeight;
  68036. },
  68037. /**
  68038. * Sets Vignette weight or intensity of the vignette effect.
  68039. */
  68040. set: function (value) {
  68041. this.imageProcessingConfiguration.vignetteWeight = value;
  68042. },
  68043. enumerable: true,
  68044. configurable: true
  68045. });
  68046. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  68047. /**
  68048. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  68049. * if vignetteEnabled is set to true.
  68050. */
  68051. get: function () {
  68052. return this.imageProcessingConfiguration.vignetteColor;
  68053. },
  68054. /**
  68055. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  68056. * if vignetteEnabled is set to true.
  68057. */
  68058. set: function (value) {
  68059. this.imageProcessingConfiguration.vignetteColor = value;
  68060. },
  68061. enumerable: true,
  68062. configurable: true
  68063. });
  68064. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  68065. /**
  68066. * Gets Camera field of view used by the Vignette effect.
  68067. */
  68068. get: function () {
  68069. return this.imageProcessingConfiguration.vignetteCameraFov;
  68070. },
  68071. /**
  68072. * Sets Camera field of view used by the Vignette effect.
  68073. */
  68074. set: function (value) {
  68075. this.imageProcessingConfiguration.vignetteCameraFov = value;
  68076. },
  68077. enumerable: true,
  68078. configurable: true
  68079. });
  68080. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  68081. /**
  68082. * Gets the vignette blend mode allowing different kind of effect.
  68083. */
  68084. get: function () {
  68085. return this.imageProcessingConfiguration.vignetteBlendMode;
  68086. },
  68087. /**
  68088. * Sets the vignette blend mode allowing different kind of effect.
  68089. */
  68090. set: function (value) {
  68091. this.imageProcessingConfiguration.vignetteBlendMode = value;
  68092. },
  68093. enumerable: true,
  68094. configurable: true
  68095. });
  68096. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  68097. /**
  68098. * Gets wether the vignette effect is enabled.
  68099. */
  68100. get: function () {
  68101. return this.imageProcessingConfiguration.vignetteEnabled;
  68102. },
  68103. /**
  68104. * Sets wether the vignette effect is enabled.
  68105. */
  68106. set: function (value) {
  68107. this.imageProcessingConfiguration.vignetteEnabled = value;
  68108. },
  68109. enumerable: true,
  68110. configurable: true
  68111. });
  68112. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  68113. /**
  68114. * Gets wether the input of the processing is in Gamma or Linear Space.
  68115. */
  68116. get: function () {
  68117. return this._fromLinearSpace;
  68118. },
  68119. /**
  68120. * Sets wether the input of the processing is in Gamma or Linear Space.
  68121. */
  68122. set: function (value) {
  68123. if (this._fromLinearSpace === value) {
  68124. return;
  68125. }
  68126. this._fromLinearSpace = value;
  68127. this._updateParameters();
  68128. },
  68129. enumerable: true,
  68130. configurable: true
  68131. });
  68132. ImageProcessingPostProcess.prototype.getClassName = function () {
  68133. return "ImageProcessingPostProcess";
  68134. };
  68135. ImageProcessingPostProcess.prototype._updateParameters = function () {
  68136. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  68137. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  68138. var defines = "";
  68139. for (var define in this._defines) {
  68140. if (this._defines[define]) {
  68141. defines += "#define " + define + ";\r\n";
  68142. }
  68143. }
  68144. var samplers = ["textureSampler"];
  68145. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  68146. var uniforms = ["scale"];
  68147. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  68148. this.updateEffect(defines, uniforms, samplers);
  68149. };
  68150. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  68151. _super.prototype.dispose.call(this, camera);
  68152. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  68153. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  68154. }
  68155. this.imageProcessingConfiguration.applyByPostProcess = false;
  68156. };
  68157. __decorate([
  68158. BABYLON.serialize()
  68159. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  68160. return ImageProcessingPostProcess;
  68161. }(BABYLON.PostProcess));
  68162. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  68163. })(BABYLON || (BABYLON = {}));
  68164. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  68165. var BABYLON;
  68166. (function (BABYLON) {
  68167. /**
  68168. * The Blur Post Process which blurs an image based on a kernel and direction.
  68169. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  68170. */
  68171. var BlurPostProcess = /** @class */ (function (_super) {
  68172. __extends(BlurPostProcess, _super);
  68173. /**
  68174. * Creates a new instance of @see BlurPostProcess
  68175. * @param name The name of the effect.
  68176. * @param direction The direction in which to blur the image.
  68177. * @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.
  68178. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  68179. * @param camera The camera to apply the render pass to.
  68180. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  68181. * @param engine The engine which the post process will be applied. (default: current engine)
  68182. * @param reusable If the post process can be reused on the same frame. (default: false)
  68183. * @param textureType Type of textures used when performing the post process. (default: 0)
  68184. */
  68185. function BlurPostProcess(name, /** The direction in which to blur the image. */ direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines) {
  68186. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  68187. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68188. if (defines === void 0) { defines = ""; }
  68189. 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;
  68190. _this.direction = direction;
  68191. _this._packedFloat = false;
  68192. _this._staticDefines = "";
  68193. _this._staticDefines = defines;
  68194. _this.onApplyObservable.add(function (effect) {
  68195. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  68196. });
  68197. _this.kernel = kernel;
  68198. return _this;
  68199. }
  68200. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  68201. /**
  68202. * Gets the length in pixels of the blur sample region
  68203. */
  68204. get: function () {
  68205. return this._idealKernel;
  68206. },
  68207. /**
  68208. * Sets the length in pixels of the blur sample region
  68209. */
  68210. set: function (v) {
  68211. if (this._idealKernel === v) {
  68212. return;
  68213. }
  68214. v = Math.max(v, 1);
  68215. this._idealKernel = v;
  68216. this._kernel = this._nearestBestKernel(v);
  68217. this._updateParameters();
  68218. },
  68219. enumerable: true,
  68220. configurable: true
  68221. });
  68222. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  68223. /**
  68224. * Gets wether or not the blur is unpacking/repacking floats
  68225. */
  68226. get: function () {
  68227. return this._packedFloat;
  68228. },
  68229. /**
  68230. * Sets wether or not the blur needs to unpack/repack floats
  68231. */
  68232. set: function (v) {
  68233. if (this._packedFloat === v) {
  68234. return;
  68235. }
  68236. this._packedFloat = v;
  68237. this._updateParameters();
  68238. },
  68239. enumerable: true,
  68240. configurable: true
  68241. });
  68242. BlurPostProcess.prototype._updateParameters = function () {
  68243. // Generate sampling offsets and weights
  68244. var N = this._kernel;
  68245. var centerIndex = (N - 1) / 2;
  68246. // Generate Gaussian sampling weights over kernel
  68247. var offsets = [];
  68248. var weights = [];
  68249. var totalWeight = 0;
  68250. for (var i = 0; i < N; i++) {
  68251. var u = i / (N - 1);
  68252. var w = this._gaussianWeight(u * 2.0 - 1);
  68253. offsets[i] = (i - centerIndex);
  68254. weights[i] = w;
  68255. totalWeight += w;
  68256. }
  68257. // Normalize weights
  68258. for (var i = 0; i < weights.length; i++) {
  68259. weights[i] /= totalWeight;
  68260. }
  68261. // Optimize: combine samples to take advantage of hardware linear sampling
  68262. // Walk from left to center, combining pairs (symmetrically)
  68263. var linearSamplingWeights = [];
  68264. var linearSamplingOffsets = [];
  68265. var linearSamplingMap = [];
  68266. for (var i = 0; i <= centerIndex; i += 2) {
  68267. var j = Math.min(i + 1, Math.floor(centerIndex));
  68268. var singleCenterSample = i === j;
  68269. if (singleCenterSample) {
  68270. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  68271. }
  68272. else {
  68273. var sharedCell = j === centerIndex;
  68274. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  68275. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  68276. if (offsetLinear === 0) {
  68277. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  68278. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  68279. }
  68280. else {
  68281. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  68282. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  68283. }
  68284. }
  68285. }
  68286. for (var i = 0; i < linearSamplingMap.length; i++) {
  68287. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  68288. linearSamplingWeights[i] = linearSamplingMap[i].w;
  68289. }
  68290. // Replace with optimized
  68291. offsets = linearSamplingOffsets;
  68292. weights = linearSamplingWeights;
  68293. // Generate shaders
  68294. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  68295. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  68296. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  68297. var defines = "";
  68298. defines += this._staticDefines;
  68299. for (var i = 0; i < varyingCount; i++) {
  68300. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  68301. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  68302. }
  68303. var depCount = 0;
  68304. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  68305. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  68306. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  68307. depCount++;
  68308. }
  68309. if (this.packedFloat) {
  68310. defines += "#define PACKEDFLOAT 1";
  68311. }
  68312. this.updateEffect(defines, null, null, {
  68313. varyingCount: varyingCount,
  68314. depCount: depCount
  68315. });
  68316. };
  68317. /**
  68318. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  68319. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  68320. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  68321. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  68322. * The gaps between physical kernels are compensated for in the weighting of the samples
  68323. * @param idealKernel Ideal blur kernel.
  68324. * @return Nearest best kernel.
  68325. */
  68326. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  68327. var v = Math.round(idealKernel);
  68328. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  68329. var k = _a[_i];
  68330. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  68331. return Math.max(k, 3);
  68332. }
  68333. }
  68334. return Math.max(v, 3);
  68335. };
  68336. /**
  68337. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  68338. * @param x The point on the Gaussian distribution to sample.
  68339. * @return the value of the Gaussian function at x.
  68340. */
  68341. BlurPostProcess.prototype._gaussianWeight = function (x) {
  68342. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  68343. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  68344. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  68345. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  68346. // truncated at around 1.3% of peak strength.
  68347. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  68348. var sigma = (1 / 3);
  68349. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  68350. var exponent = -((x * x) / (2.0 * sigma * sigma));
  68351. var weight = (1.0 / denominator) * Math.exp(exponent);
  68352. return weight;
  68353. };
  68354. /**
  68355. * Generates a string that can be used as a floating point number in GLSL.
  68356. * @param x Value to print.
  68357. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  68358. * @return GLSL float string.
  68359. */
  68360. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  68361. if (decimalFigures === void 0) { decimalFigures = 8; }
  68362. return x.toFixed(decimalFigures).replace(/0+$/, '');
  68363. };
  68364. return BlurPostProcess;
  68365. }(BABYLON.PostProcess));
  68366. BABYLON.BlurPostProcess = BlurPostProcess;
  68367. })(BABYLON || (BABYLON = {}));
  68368. //# sourceMappingURL=babylon.blurPostProcess.js.map
  68369. var BABYLON;
  68370. (function (BABYLON) {
  68371. var Bone = /** @class */ (function (_super) {
  68372. __extends(Bone, _super);
  68373. function Bone(name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  68374. if (parentBone === void 0) { parentBone = null; }
  68375. if (localMatrix === void 0) { localMatrix = null; }
  68376. if (restPose === void 0) { restPose = null; }
  68377. if (baseMatrix === void 0) { baseMatrix = null; }
  68378. if (index === void 0) { index = null; }
  68379. var _this = _super.call(this, name, skeleton.getScene()) || this;
  68380. _this.name = name;
  68381. _this.children = new Array();
  68382. _this.animations = new Array();
  68383. // Set this value to map this bone to a different index in the transform matrices.
  68384. // Set this value to -1 to exclude the bone from the transform matrices.
  68385. _this._index = null;
  68386. _this._worldTransform = new BABYLON.Matrix();
  68387. _this._absoluteTransform = new BABYLON.Matrix();
  68388. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  68389. _this._scaleMatrix = BABYLON.Matrix.Identity();
  68390. _this._scaleVector = BABYLON.Vector3.One();
  68391. _this._negateScaleChildren = BABYLON.Vector3.One();
  68392. _this._scalingDeterminant = 1;
  68393. _this._skeleton = skeleton;
  68394. _this._localMatrix = localMatrix ? localMatrix : BABYLON.Matrix.Identity();
  68395. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  68396. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  68397. _this._index = index;
  68398. skeleton.bones.push(_this);
  68399. _this.setParent(parentBone, false);
  68400. _this._updateDifferenceMatrix();
  68401. return _this;
  68402. }
  68403. Object.defineProperty(Bone.prototype, "_matrix", {
  68404. get: function () {
  68405. return this._localMatrix;
  68406. },
  68407. set: function (val) {
  68408. if (this._localMatrix) {
  68409. this._localMatrix.copyFrom(val);
  68410. }
  68411. else {
  68412. this._localMatrix = val;
  68413. }
  68414. },
  68415. enumerable: true,
  68416. configurable: true
  68417. });
  68418. // Members
  68419. Bone.prototype.getSkeleton = function () {
  68420. return this._skeleton;
  68421. };
  68422. Bone.prototype.getParent = function () {
  68423. return this._parent;
  68424. };
  68425. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  68426. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  68427. if (this._parent === parent) {
  68428. return;
  68429. }
  68430. if (this._parent) {
  68431. var index = this._parent.children.indexOf(this);
  68432. if (index !== -1) {
  68433. this._parent.children.splice(index, 1);
  68434. }
  68435. }
  68436. this._parent = parent;
  68437. if (this._parent) {
  68438. this._parent.children.push(this);
  68439. }
  68440. if (updateDifferenceMatrix) {
  68441. this._updateDifferenceMatrix();
  68442. }
  68443. };
  68444. Bone.prototype.getLocalMatrix = function () {
  68445. return this._localMatrix;
  68446. };
  68447. Bone.prototype.getBaseMatrix = function () {
  68448. return this._baseMatrix;
  68449. };
  68450. Bone.prototype.getRestPose = function () {
  68451. return this._restPose;
  68452. };
  68453. Bone.prototype.returnToRest = function () {
  68454. this.updateMatrix(this._restPose.clone());
  68455. };
  68456. Bone.prototype.getWorldMatrix = function () {
  68457. return this._worldTransform;
  68458. };
  68459. Bone.prototype.getInvertedAbsoluteTransform = function () {
  68460. return this._invertedAbsoluteTransform;
  68461. };
  68462. Bone.prototype.getAbsoluteTransform = function () {
  68463. return this._absoluteTransform;
  68464. };
  68465. Object.defineProperty(Bone.prototype, "position", {
  68466. // Properties (matches AbstractMesh properties)
  68467. get: function () {
  68468. return this.getPosition();
  68469. },
  68470. set: function (newPosition) {
  68471. this.setPosition(newPosition);
  68472. },
  68473. enumerable: true,
  68474. configurable: true
  68475. });
  68476. Object.defineProperty(Bone.prototype, "rotation", {
  68477. get: function () {
  68478. return this.getRotation();
  68479. },
  68480. set: function (newRotation) {
  68481. this.setRotation(newRotation);
  68482. },
  68483. enumerable: true,
  68484. configurable: true
  68485. });
  68486. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  68487. get: function () {
  68488. return this.getRotationQuaternion();
  68489. },
  68490. set: function (newRotation) {
  68491. this.setRotationQuaternion(newRotation);
  68492. },
  68493. enumerable: true,
  68494. configurable: true
  68495. });
  68496. Object.defineProperty(Bone.prototype, "scaling", {
  68497. get: function () {
  68498. return this.getScale();
  68499. },
  68500. set: function (newScaling) {
  68501. this.setScale(newScaling.x, newScaling.y, newScaling.z);
  68502. },
  68503. enumerable: true,
  68504. configurable: true
  68505. });
  68506. // Methods
  68507. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  68508. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  68509. this._baseMatrix = matrix.clone();
  68510. this._localMatrix = matrix.clone();
  68511. this._skeleton._markAsDirty();
  68512. if (updateDifferenceMatrix) {
  68513. this._updateDifferenceMatrix();
  68514. }
  68515. };
  68516. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  68517. if (!rootMatrix) {
  68518. rootMatrix = this._baseMatrix;
  68519. }
  68520. if (this._parent) {
  68521. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  68522. }
  68523. else {
  68524. this._absoluteTransform.copyFrom(rootMatrix);
  68525. }
  68526. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  68527. for (var index = 0; index < this.children.length; index++) {
  68528. this.children[index]._updateDifferenceMatrix();
  68529. }
  68530. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  68531. };
  68532. Bone.prototype.markAsDirty = function () {
  68533. this._currentRenderId++;
  68534. this._skeleton._markAsDirty();
  68535. };
  68536. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  68537. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  68538. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  68539. // all animation may be coming from a library skeleton, so may need to create animation
  68540. if (this.animations.length === 0) {
  68541. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  68542. this.animations[0].setKeys([]);
  68543. }
  68544. // get animation info / verify there is such a range from the source bone
  68545. var sourceRange = source.animations[0].getRange(rangeName);
  68546. if (!sourceRange) {
  68547. return false;
  68548. }
  68549. var from = sourceRange.from;
  68550. var to = sourceRange.to;
  68551. var sourceKeys = source.animations[0].getKeys();
  68552. // rescaling prep
  68553. var sourceBoneLength = source.length;
  68554. var sourceParent = source.getParent();
  68555. var parent = this.getParent();
  68556. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  68557. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  68558. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  68559. var destKeys = this.animations[0].getKeys();
  68560. // loop vars declaration
  68561. var orig;
  68562. var origTranslation;
  68563. var mat;
  68564. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  68565. orig = sourceKeys[key];
  68566. if (orig.frame >= from && orig.frame <= to) {
  68567. if (rescaleAsRequired) {
  68568. mat = orig.value.clone();
  68569. // scale based on parent ratio, when bone has parent
  68570. if (parentScalingReqd) {
  68571. origTranslation = mat.getTranslation();
  68572. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  68573. // scale based on skeleton dimension ratio when root bone, and value is passed
  68574. }
  68575. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  68576. origTranslation = mat.getTranslation();
  68577. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  68578. // use original when root bone, and no data for skelDimensionsRatio
  68579. }
  68580. else {
  68581. mat = orig.value;
  68582. }
  68583. }
  68584. else {
  68585. mat = orig.value;
  68586. }
  68587. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  68588. }
  68589. }
  68590. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  68591. return true;
  68592. };
  68593. /**
  68594. * Translate the bone in local or world space.
  68595. * @param vec The amount to translate the bone.
  68596. * @param space The space that the translation is in.
  68597. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  68598. */
  68599. Bone.prototype.translate = function (vec, space, mesh) {
  68600. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  68601. var lm = this.getLocalMatrix();
  68602. if (space == BABYLON.Space.LOCAL) {
  68603. lm.m[12] += vec.x;
  68604. lm.m[13] += vec.y;
  68605. lm.m[14] += vec.z;
  68606. }
  68607. else {
  68608. var wm = null;
  68609. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  68610. if (mesh) {
  68611. wm = mesh.getWorldMatrix();
  68612. }
  68613. this._skeleton.computeAbsoluteTransforms();
  68614. var tmat = Bone._tmpMats[0];
  68615. var tvec = Bone._tmpVecs[0];
  68616. if (this._parent) {
  68617. if (mesh && wm) {
  68618. tmat.copyFrom(this._parent.getAbsoluteTransform());
  68619. tmat.multiplyToRef(wm, tmat);
  68620. }
  68621. else {
  68622. tmat.copyFrom(this._parent.getAbsoluteTransform());
  68623. }
  68624. }
  68625. tmat.m[12] = 0;
  68626. tmat.m[13] = 0;
  68627. tmat.m[14] = 0;
  68628. tmat.invert();
  68629. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  68630. lm.m[12] += tvec.x;
  68631. lm.m[13] += tvec.y;
  68632. lm.m[14] += tvec.z;
  68633. }
  68634. this.markAsDirty();
  68635. };
  68636. /**
  68637. * Set the postion of the bone in local or world space.
  68638. * @param position The position to set the bone.
  68639. * @param space The space that the position is in.
  68640. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  68641. */
  68642. Bone.prototype.setPosition = function (position, space, mesh) {
  68643. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  68644. var lm = this.getLocalMatrix();
  68645. if (space == BABYLON.Space.LOCAL) {
  68646. lm.m[12] = position.x;
  68647. lm.m[13] = position.y;
  68648. lm.m[14] = position.z;
  68649. }
  68650. else {
  68651. var wm = null;
  68652. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  68653. if (mesh) {
  68654. wm = mesh.getWorldMatrix();
  68655. }
  68656. this._skeleton.computeAbsoluteTransforms();
  68657. var tmat = Bone._tmpMats[0];
  68658. var vec = Bone._tmpVecs[0];
  68659. if (this._parent) {
  68660. if (mesh && wm) {
  68661. tmat.copyFrom(this._parent.getAbsoluteTransform());
  68662. tmat.multiplyToRef(wm, tmat);
  68663. }
  68664. else {
  68665. tmat.copyFrom(this._parent.getAbsoluteTransform());
  68666. }
  68667. }
  68668. tmat.invert();
  68669. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  68670. lm.m[12] = vec.x;
  68671. lm.m[13] = vec.y;
  68672. lm.m[14] = vec.z;
  68673. }
  68674. this.markAsDirty();
  68675. };
  68676. /**
  68677. * Set the absolute postion of the bone (world space).
  68678. * @param position The position to set the bone.
  68679. * @param mesh The mesh that this bone is attached to.
  68680. */
  68681. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  68682. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  68683. };
  68684. /**
  68685. * Set the scale of the bone on the x, y and z axes.
  68686. * @param x The scale of the bone on the x axis.
  68687. * @param x The scale of the bone on the y axis.
  68688. * @param z The scale of the bone on the z axis.
  68689. * @param scaleChildren Set this to true if children of the bone should be scaled.
  68690. */
  68691. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  68692. if (scaleChildren === void 0) { scaleChildren = false; }
  68693. if (this.animations[0] && !this.animations[0].hasRunningRuntimeAnimations) {
  68694. if (!scaleChildren) {
  68695. this._negateScaleChildren.x = 1 / x;
  68696. this._negateScaleChildren.y = 1 / y;
  68697. this._negateScaleChildren.z = 1 / z;
  68698. }
  68699. this._syncScaleVector();
  68700. }
  68701. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  68702. };
  68703. /**
  68704. * Scale the bone on the x, y and z axes.
  68705. * @param x The amount to scale the bone on the x axis.
  68706. * @param x The amount to scale the bone on the y axis.
  68707. * @param z The amount to scale the bone on the z axis.
  68708. * @param scaleChildren Set this to true if children of the bone should be scaled.
  68709. */
  68710. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  68711. if (scaleChildren === void 0) { scaleChildren = false; }
  68712. var locMat = this.getLocalMatrix();
  68713. var origLocMat = Bone._tmpMats[0];
  68714. origLocMat.copyFrom(locMat);
  68715. var origLocMatInv = Bone._tmpMats[1];
  68716. origLocMatInv.copyFrom(origLocMat);
  68717. origLocMatInv.invert();
  68718. var scaleMat = Bone._tmpMats[2];
  68719. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  68720. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  68721. this._scaleVector.x *= x;
  68722. this._scaleVector.y *= y;
  68723. this._scaleVector.z *= z;
  68724. locMat.multiplyToRef(origLocMatInv, locMat);
  68725. locMat.multiplyToRef(scaleMat, locMat);
  68726. locMat.multiplyToRef(origLocMat, locMat);
  68727. var parent = this.getParent();
  68728. if (parent) {
  68729. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  68730. }
  68731. else {
  68732. this.getAbsoluteTransform().copyFrom(locMat);
  68733. }
  68734. var len = this.children.length;
  68735. scaleMat.invert();
  68736. for (var i = 0; i < len; i++) {
  68737. var child = this.children[i];
  68738. var cm = child.getLocalMatrix();
  68739. cm.multiplyToRef(scaleMat, cm);
  68740. var lm = child.getLocalMatrix();
  68741. lm.m[12] *= x;
  68742. lm.m[13] *= y;
  68743. lm.m[14] *= z;
  68744. }
  68745. this.computeAbsoluteTransforms();
  68746. if (scaleChildren) {
  68747. for (var i = 0; i < len; i++) {
  68748. this.children[i].scale(x, y, z, scaleChildren);
  68749. }
  68750. }
  68751. this.markAsDirty();
  68752. };
  68753. /**
  68754. * Set the yaw, pitch, and roll of the bone in local or world space.
  68755. * @param yaw The rotation of the bone on the y axis.
  68756. * @param pitch The rotation of the bone on the x axis.
  68757. * @param roll The rotation of the bone on the z axis.
  68758. * @param space The space that the axes of rotation are in.
  68759. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  68760. */
  68761. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  68762. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  68763. var rotMat = Bone._tmpMats[0];
  68764. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  68765. var rotMatInv = Bone._tmpMats[1];
  68766. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  68767. rotMatInv.multiplyToRef(rotMat, rotMat);
  68768. this._rotateWithMatrix(rotMat, space, mesh);
  68769. };
  68770. /**
  68771. * Rotate the bone on an axis in local or world space.
  68772. * @param axis The axis to rotate the bone on.
  68773. * @param amount The amount to rotate the bone.
  68774. * @param space The space that the axis is in.
  68775. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  68776. */
  68777. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  68778. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  68779. var rmat = Bone._tmpMats[0];
  68780. rmat.m[12] = 0;
  68781. rmat.m[13] = 0;
  68782. rmat.m[14] = 0;
  68783. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  68784. this._rotateWithMatrix(rmat, space, mesh);
  68785. };
  68786. /**
  68787. * Set the rotation of the bone to a particular axis angle in local or world space.
  68788. * @param axis The axis to rotate the bone on.
  68789. * @param angle The angle that the bone should be rotated to.
  68790. * @param space The space that the axis is in.
  68791. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  68792. */
  68793. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  68794. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  68795. var rotMat = Bone._tmpMats[0];
  68796. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  68797. var rotMatInv = Bone._tmpMats[1];
  68798. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  68799. rotMatInv.multiplyToRef(rotMat, rotMat);
  68800. this._rotateWithMatrix(rotMat, space, mesh);
  68801. };
  68802. /**
  68803. * Set the euler rotation of the bone in local of world space.
  68804. * @param rotation The euler rotation that the bone should be set to.
  68805. * @param space The space that the rotation is in.
  68806. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  68807. */
  68808. Bone.prototype.setRotation = function (rotation, space, mesh) {
  68809. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  68810. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  68811. };
  68812. /**
  68813. * Set the quaternion rotation of the bone in local of world space.
  68814. * @param quat The quaternion rotation that the bone should be set to.
  68815. * @param space The space that the rotation is in.
  68816. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  68817. */
  68818. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  68819. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  68820. var rotMatInv = Bone._tmpMats[0];
  68821. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  68822. var rotMat = Bone._tmpMats[1];
  68823. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  68824. rotMatInv.multiplyToRef(rotMat, rotMat);
  68825. this._rotateWithMatrix(rotMat, space, mesh);
  68826. };
  68827. /**
  68828. * Set the rotation matrix of the bone in local of world space.
  68829. * @param rotMat The rotation matrix that the bone should be set to.
  68830. * @param space The space that the rotation is in.
  68831. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  68832. */
  68833. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  68834. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  68835. var rotMatInv = Bone._tmpMats[0];
  68836. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  68837. var rotMat2 = Bone._tmpMats[1];
  68838. rotMat2.copyFrom(rotMat);
  68839. rotMatInv.multiplyToRef(rotMat, rotMat2);
  68840. this._rotateWithMatrix(rotMat2, space, mesh);
  68841. };
  68842. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  68843. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  68844. var lmat = this.getLocalMatrix();
  68845. var lx = lmat.m[12];
  68846. var ly = lmat.m[13];
  68847. var lz = lmat.m[14];
  68848. var parent = this.getParent();
  68849. var parentScale = Bone._tmpMats[3];
  68850. var parentScaleInv = Bone._tmpMats[4];
  68851. if (parent) {
  68852. if (space == BABYLON.Space.WORLD) {
  68853. if (mesh) {
  68854. parentScale.copyFrom(mesh.getWorldMatrix());
  68855. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  68856. }
  68857. else {
  68858. parentScale.copyFrom(parent.getAbsoluteTransform());
  68859. }
  68860. }
  68861. else {
  68862. parentScale = parent._scaleMatrix;
  68863. }
  68864. parentScaleInv.copyFrom(parentScale);
  68865. parentScaleInv.invert();
  68866. lmat.multiplyToRef(parentScale, lmat);
  68867. lmat.multiplyToRef(rmat, lmat);
  68868. lmat.multiplyToRef(parentScaleInv, lmat);
  68869. }
  68870. else {
  68871. if (space == BABYLON.Space.WORLD && mesh) {
  68872. parentScale.copyFrom(mesh.getWorldMatrix());
  68873. parentScaleInv.copyFrom(parentScale);
  68874. parentScaleInv.invert();
  68875. lmat.multiplyToRef(parentScale, lmat);
  68876. lmat.multiplyToRef(rmat, lmat);
  68877. lmat.multiplyToRef(parentScaleInv, lmat);
  68878. }
  68879. else {
  68880. lmat.multiplyToRef(rmat, lmat);
  68881. }
  68882. }
  68883. lmat.m[12] = lx;
  68884. lmat.m[13] = ly;
  68885. lmat.m[14] = lz;
  68886. this.computeAbsoluteTransforms();
  68887. this.markAsDirty();
  68888. };
  68889. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  68890. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  68891. if (space == BABYLON.Space.WORLD) {
  68892. var scaleMatrix = Bone._tmpMats[2];
  68893. scaleMatrix.copyFrom(this._scaleMatrix);
  68894. rotMatInv.copyFrom(this.getAbsoluteTransform());
  68895. if (mesh) {
  68896. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  68897. var meshScale = Bone._tmpMats[3];
  68898. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  68899. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  68900. }
  68901. rotMatInv.invert();
  68902. scaleMatrix.m[0] *= this._scalingDeterminant;
  68903. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  68904. }
  68905. else {
  68906. rotMatInv.copyFrom(this.getLocalMatrix());
  68907. rotMatInv.invert();
  68908. var scaleMatrix = Bone._tmpMats[2];
  68909. scaleMatrix.copyFrom(this._scaleMatrix);
  68910. if (this._parent) {
  68911. var pscaleMatrix = Bone._tmpMats[3];
  68912. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  68913. pscaleMatrix.invert();
  68914. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  68915. }
  68916. else {
  68917. scaleMatrix.m[0] *= this._scalingDeterminant;
  68918. }
  68919. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  68920. }
  68921. };
  68922. /**
  68923. * Get the scale of the bone
  68924. * @returns the scale of the bone
  68925. */
  68926. Bone.prototype.getScale = function () {
  68927. return this._scaleVector.clone();
  68928. };
  68929. /**
  68930. * Copy the scale of the bone to a vector3.
  68931. * @param result The vector3 to copy the scale to
  68932. */
  68933. Bone.prototype.getScaleToRef = function (result) {
  68934. result.copyFrom(this._scaleVector);
  68935. };
  68936. /**
  68937. * Get the position of the bone in local or world space.
  68938. * @param space The space that the returned position is in.
  68939. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  68940. * @returns The position of the bone
  68941. */
  68942. Bone.prototype.getPosition = function (space, mesh) {
  68943. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  68944. if (mesh === void 0) { mesh = null; }
  68945. var pos = BABYLON.Vector3.Zero();
  68946. this.getPositionToRef(space, mesh, pos);
  68947. return pos;
  68948. };
  68949. /**
  68950. * Copy the position of the bone to a vector3 in local or world space.
  68951. * @param space The space that the returned position is in.
  68952. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  68953. * @param result The vector3 to copy the position to.
  68954. */
  68955. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  68956. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  68957. if (space == BABYLON.Space.LOCAL) {
  68958. var lm = this.getLocalMatrix();
  68959. result.x = lm.m[12];
  68960. result.y = lm.m[13];
  68961. result.z = lm.m[14];
  68962. }
  68963. else {
  68964. var wm = null;
  68965. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  68966. if (mesh) {
  68967. wm = mesh.getWorldMatrix();
  68968. }
  68969. this._skeleton.computeAbsoluteTransforms();
  68970. var tmat = Bone._tmpMats[0];
  68971. if (mesh && wm) {
  68972. tmat.copyFrom(this.getAbsoluteTransform());
  68973. tmat.multiplyToRef(wm, tmat);
  68974. }
  68975. else {
  68976. tmat = this.getAbsoluteTransform();
  68977. }
  68978. result.x = tmat.m[12];
  68979. result.y = tmat.m[13];
  68980. result.z = tmat.m[14];
  68981. }
  68982. };
  68983. /**
  68984. * Get the absolute position of the bone (world space).
  68985. * @param mesh The mesh that this bone is attached to.
  68986. * @returns The absolute position of the bone
  68987. */
  68988. Bone.prototype.getAbsolutePosition = function (mesh) {
  68989. if (mesh === void 0) { mesh = null; }
  68990. var pos = BABYLON.Vector3.Zero();
  68991. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  68992. return pos;
  68993. };
  68994. /**
  68995. * Copy the absolute position of the bone (world space) to the result param.
  68996. * @param mesh The mesh that this bone is attached to.
  68997. * @param result The vector3 to copy the absolute position to.
  68998. */
  68999. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  69000. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  69001. };
  69002. /**
  69003. * Compute the absolute transforms of this bone and its children.
  69004. */
  69005. Bone.prototype.computeAbsoluteTransforms = function () {
  69006. if (this._parent) {
  69007. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  69008. }
  69009. else {
  69010. this._absoluteTransform.copyFrom(this._localMatrix);
  69011. var poseMatrix = this._skeleton.getPoseMatrix();
  69012. if (poseMatrix) {
  69013. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  69014. }
  69015. }
  69016. var children = this.children;
  69017. var len = children.length;
  69018. for (var i = 0; i < len; i++) {
  69019. children[i].computeAbsoluteTransforms();
  69020. }
  69021. };
  69022. Bone.prototype._syncScaleVector = function () {
  69023. var lm = this.getLocalMatrix();
  69024. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  69025. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  69026. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  69027. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  69028. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  69029. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  69030. this._scaleVector.x = xs * Math.sqrt(xsq);
  69031. this._scaleVector.y = ys * Math.sqrt(ysq);
  69032. this._scaleVector.z = zs * Math.sqrt(zsq);
  69033. if (this._parent) {
  69034. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  69035. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  69036. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  69037. }
  69038. 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);
  69039. };
  69040. /**
  69041. * Get the world direction from an axis that is in the local space of the bone.
  69042. * @param localAxis The local direction that is used to compute the world direction.
  69043. * @param mesh The mesh that this bone is attached to.
  69044. * @returns The world direction
  69045. */
  69046. Bone.prototype.getDirection = function (localAxis, mesh) {
  69047. if (mesh === void 0) { mesh = null; }
  69048. var result = BABYLON.Vector3.Zero();
  69049. this.getDirectionToRef(localAxis, mesh, result);
  69050. return result;
  69051. };
  69052. /**
  69053. * Copy the world direction to a vector3 from an axis that is in the local space of the bone.
  69054. * @param localAxis The local direction that is used to compute the world direction.
  69055. * @param mesh The mesh that this bone is attached to.
  69056. * @param result The vector3 that the world direction will be copied to.
  69057. */
  69058. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  69059. if (mesh === void 0) { mesh = null; }
  69060. var wm = null;
  69061. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  69062. if (mesh) {
  69063. wm = mesh.getWorldMatrix();
  69064. }
  69065. this._skeleton.computeAbsoluteTransforms();
  69066. var mat = Bone._tmpMats[0];
  69067. mat.copyFrom(this.getAbsoluteTransform());
  69068. if (mesh && wm) {
  69069. mat.multiplyToRef(wm, mat);
  69070. }
  69071. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  69072. result.normalize();
  69073. };
  69074. /**
  69075. * Get the euler rotation of the bone in local or world space.
  69076. * @param space The space that the rotation should be in.
  69077. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  69078. * @returns The euler rotation
  69079. */
  69080. Bone.prototype.getRotation = function (space, mesh) {
  69081. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  69082. if (mesh === void 0) { mesh = null; }
  69083. var result = BABYLON.Vector3.Zero();
  69084. this.getRotationToRef(space, mesh, result);
  69085. return result;
  69086. };
  69087. /**
  69088. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space.
  69089. * @param space The space that the rotation should be in.
  69090. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  69091. * @param result The vector3 that the rotation should be copied to.
  69092. */
  69093. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  69094. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  69095. if (mesh === void 0) { mesh = null; }
  69096. var quat = Bone._tmpQuat;
  69097. this.getRotationQuaternionToRef(space, mesh, quat);
  69098. quat.toEulerAnglesToRef(result);
  69099. };
  69100. /**
  69101. * Get the quaternion rotation of the bone in either local or world space.
  69102. * @param space The space that the rotation should be in.
  69103. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  69104. * @returns The quaternion rotation
  69105. */
  69106. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  69107. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  69108. if (mesh === void 0) { mesh = null; }
  69109. var result = BABYLON.Quaternion.Identity();
  69110. this.getRotationQuaternionToRef(space, mesh, result);
  69111. return result;
  69112. };
  69113. /**
  69114. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space.
  69115. * @param space The space that the rotation should be in.
  69116. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  69117. * @param result The quaternion that the rotation should be copied to.
  69118. */
  69119. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  69120. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  69121. if (mesh === void 0) { mesh = null; }
  69122. if (space == BABYLON.Space.LOCAL) {
  69123. this.getLocalMatrix().decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  69124. }
  69125. else {
  69126. var mat = Bone._tmpMats[0];
  69127. var amat = this.getAbsoluteTransform();
  69128. if (mesh) {
  69129. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  69130. }
  69131. else {
  69132. mat.copyFrom(amat);
  69133. }
  69134. mat.m[0] *= this._scalingDeterminant;
  69135. mat.m[1] *= this._scalingDeterminant;
  69136. mat.m[2] *= this._scalingDeterminant;
  69137. mat.decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  69138. }
  69139. };
  69140. /**
  69141. * Get the rotation matrix of the bone in local or world space.
  69142. * @param space The space that the rotation should be in.
  69143. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  69144. * @returns The rotation matrix
  69145. */
  69146. Bone.prototype.getRotationMatrix = function (space, mesh) {
  69147. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  69148. var result = BABYLON.Matrix.Identity();
  69149. this.getRotationMatrixToRef(space, mesh, result);
  69150. return result;
  69151. };
  69152. /**
  69153. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space.
  69154. * @param space The space that the rotation should be in.
  69155. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  69156. * @param result The quaternion that the rotation should be copied to.
  69157. */
  69158. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  69159. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  69160. if (space == BABYLON.Space.LOCAL) {
  69161. this.getLocalMatrix().getRotationMatrixToRef(result);
  69162. }
  69163. else {
  69164. var mat = Bone._tmpMats[0];
  69165. var amat = this.getAbsoluteTransform();
  69166. if (mesh) {
  69167. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  69168. }
  69169. else {
  69170. mat.copyFrom(amat);
  69171. }
  69172. mat.m[0] *= this._scalingDeterminant;
  69173. mat.m[1] *= this._scalingDeterminant;
  69174. mat.m[2] *= this._scalingDeterminant;
  69175. mat.getRotationMatrixToRef(result);
  69176. }
  69177. };
  69178. /**
  69179. * Get the world position of a point that is in the local space of the bone.
  69180. * @param position The local position
  69181. * @param mesh The mesh that this bone is attached to.
  69182. * @returns The world position
  69183. */
  69184. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  69185. if (mesh === void 0) { mesh = null; }
  69186. var result = BABYLON.Vector3.Zero();
  69187. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  69188. return result;
  69189. };
  69190. /**
  69191. * Get the world position of a point that is in the local space of the bone and copy it to the result param.
  69192. * @param position The local position
  69193. * @param mesh The mesh that this bone is attached to.
  69194. * @param result The vector3 that the world position should be copied to.
  69195. */
  69196. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  69197. if (mesh === void 0) { mesh = null; }
  69198. var wm = null;
  69199. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  69200. if (mesh) {
  69201. wm = mesh.getWorldMatrix();
  69202. }
  69203. this._skeleton.computeAbsoluteTransforms();
  69204. var tmat = Bone._tmpMats[0];
  69205. if (mesh && wm) {
  69206. tmat.copyFrom(this.getAbsoluteTransform());
  69207. tmat.multiplyToRef(wm, tmat);
  69208. }
  69209. else {
  69210. tmat = this.getAbsoluteTransform();
  69211. }
  69212. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  69213. };
  69214. /**
  69215. * Get the local position of a point that is in world space.
  69216. * @param position The world position
  69217. * @param mesh The mesh that this bone is attached to.
  69218. * @returns The local position
  69219. */
  69220. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  69221. if (mesh === void 0) { mesh = null; }
  69222. var result = BABYLON.Vector3.Zero();
  69223. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  69224. return result;
  69225. };
  69226. /**
  69227. * Get the local position of a point that is in world space and copy it to the result param.
  69228. * @param position The world position
  69229. * @param mesh The mesh that this bone is attached to.
  69230. * @param result The vector3 that the local position should be copied to.
  69231. */
  69232. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  69233. if (mesh === void 0) { mesh = null; }
  69234. var wm = null;
  69235. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  69236. if (mesh) {
  69237. wm = mesh.getWorldMatrix();
  69238. }
  69239. this._skeleton.computeAbsoluteTransforms();
  69240. var tmat = Bone._tmpMats[0];
  69241. tmat.copyFrom(this.getAbsoluteTransform());
  69242. if (mesh && wm) {
  69243. tmat.multiplyToRef(wm, tmat);
  69244. }
  69245. tmat.invert();
  69246. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  69247. };
  69248. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  69249. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  69250. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  69251. return Bone;
  69252. }(BABYLON.Node));
  69253. BABYLON.Bone = Bone;
  69254. })(BABYLON || (BABYLON = {}));
  69255. //# sourceMappingURL=babylon.bone.js.map
  69256. var BABYLON;
  69257. (function (BABYLON) {
  69258. var BoneIKController = /** @class */ (function () {
  69259. function BoneIKController(mesh, bone, options) {
  69260. this.targetPosition = BABYLON.Vector3.Zero();
  69261. this.poleTargetPosition = BABYLON.Vector3.Zero();
  69262. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  69263. this.poleAngle = 0;
  69264. this.slerpAmount = 1;
  69265. this._bone1Quat = BABYLON.Quaternion.Identity();
  69266. this._bone1Mat = BABYLON.Matrix.Identity();
  69267. this._bone2Ang = Math.PI;
  69268. this._maxAngle = Math.PI;
  69269. this._rightHandedSystem = false;
  69270. this._bendAxis = BABYLON.Vector3.Right();
  69271. this._slerping = false;
  69272. this._adjustRoll = 0;
  69273. this._bone2 = bone;
  69274. this._bone1 = bone.getParent();
  69275. if (!this._bone1) {
  69276. return;
  69277. }
  69278. this.mesh = mesh;
  69279. var bonePos = bone.getPosition();
  69280. if (bone.getAbsoluteTransform().determinant() > 0) {
  69281. this._rightHandedSystem = true;
  69282. this._bendAxis.x = 0;
  69283. this._bendAxis.y = 0;
  69284. this._bendAxis.z = -1;
  69285. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  69286. this._adjustRoll = Math.PI * .5;
  69287. this._bendAxis.z = 1;
  69288. }
  69289. }
  69290. if (this._bone1.length) {
  69291. var boneScale1 = this._bone1.getScale();
  69292. var boneScale2 = this._bone2.getScale();
  69293. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  69294. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  69295. }
  69296. else if (this._bone1.children[0]) {
  69297. mesh.computeWorldMatrix(true);
  69298. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  69299. var pos2 = this._bone2.getAbsolutePosition(mesh);
  69300. var pos3 = this._bone1.getAbsolutePosition(mesh);
  69301. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  69302. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  69303. }
  69304. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  69305. this.maxAngle = Math.PI;
  69306. if (options) {
  69307. if (options.targetMesh) {
  69308. this.targetMesh = options.targetMesh;
  69309. this.targetMesh.computeWorldMatrix(true);
  69310. }
  69311. if (options.poleTargetMesh) {
  69312. this.poleTargetMesh = options.poleTargetMesh;
  69313. this.poleTargetMesh.computeWorldMatrix(true);
  69314. }
  69315. else if (options.poleTargetBone) {
  69316. this.poleTargetBone = options.poleTargetBone;
  69317. }
  69318. else if (this._bone1.getParent()) {
  69319. this.poleTargetBone = this._bone1.getParent();
  69320. }
  69321. if (options.poleTargetLocalOffset) {
  69322. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  69323. }
  69324. if (options.poleAngle) {
  69325. this.poleAngle = options.poleAngle;
  69326. }
  69327. if (options.bendAxis) {
  69328. this._bendAxis.copyFrom(options.bendAxis);
  69329. }
  69330. if (options.maxAngle) {
  69331. this.maxAngle = options.maxAngle;
  69332. }
  69333. if (options.slerpAmount) {
  69334. this.slerpAmount = options.slerpAmount;
  69335. }
  69336. }
  69337. }
  69338. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  69339. get: function () {
  69340. return this._maxAngle;
  69341. },
  69342. set: function (value) {
  69343. this._setMaxAngle(value);
  69344. },
  69345. enumerable: true,
  69346. configurable: true
  69347. });
  69348. BoneIKController.prototype._setMaxAngle = function (ang) {
  69349. if (ang < 0) {
  69350. ang = 0;
  69351. }
  69352. if (ang > Math.PI || ang == undefined) {
  69353. ang = Math.PI;
  69354. }
  69355. this._maxAngle = ang;
  69356. var a = this._bone1Length;
  69357. var b = this._bone2Length;
  69358. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  69359. };
  69360. BoneIKController.prototype.update = function () {
  69361. var bone1 = this._bone1;
  69362. if (!bone1) {
  69363. return;
  69364. }
  69365. var target = this.targetPosition;
  69366. var poleTarget = this.poleTargetPosition;
  69367. var mat1 = BoneIKController._tmpMats[0];
  69368. var mat2 = BoneIKController._tmpMats[1];
  69369. if (this.targetMesh) {
  69370. target.copyFrom(this.targetMesh.getAbsolutePosition());
  69371. }
  69372. if (this.poleTargetBone) {
  69373. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  69374. }
  69375. else if (this.poleTargetMesh) {
  69376. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  69377. }
  69378. var bonePos = BoneIKController._tmpVecs[0];
  69379. var zaxis = BoneIKController._tmpVecs[1];
  69380. var xaxis = BoneIKController._tmpVecs[2];
  69381. var yaxis = BoneIKController._tmpVecs[3];
  69382. var upAxis = BoneIKController._tmpVecs[4];
  69383. var _tmpQuat = BoneIKController._tmpQuat;
  69384. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  69385. poleTarget.subtractToRef(bonePos, upAxis);
  69386. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  69387. upAxis.y = 1;
  69388. }
  69389. else {
  69390. upAxis.normalize();
  69391. }
  69392. target.subtractToRef(bonePos, yaxis);
  69393. yaxis.normalize();
  69394. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  69395. zaxis.normalize();
  69396. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  69397. xaxis.normalize();
  69398. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  69399. var a = this._bone1Length;
  69400. var b = this._bone2Length;
  69401. var c = BABYLON.Vector3.Distance(bonePos, target);
  69402. if (this._maxReach > 0) {
  69403. c = Math.min(this._maxReach, c);
  69404. }
  69405. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  69406. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  69407. if (acosa > 1) {
  69408. acosa = 1;
  69409. }
  69410. if (acosb > 1) {
  69411. acosb = 1;
  69412. }
  69413. if (acosa < -1) {
  69414. acosa = -1;
  69415. }
  69416. if (acosb < -1) {
  69417. acosb = -1;
  69418. }
  69419. var angA = Math.acos(acosa);
  69420. var angB = Math.acos(acosb);
  69421. var angC = -angA - angB;
  69422. if (this._rightHandedSystem) {
  69423. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  69424. mat2.multiplyToRef(mat1, mat1);
  69425. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  69426. mat2.multiplyToRef(mat1, mat1);
  69427. }
  69428. else {
  69429. var _tmpVec = BoneIKController._tmpVecs[5];
  69430. _tmpVec.copyFrom(this._bendAxis);
  69431. _tmpVec.x *= -1;
  69432. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  69433. mat2.multiplyToRef(mat1, mat1);
  69434. }
  69435. if (this.poleAngle) {
  69436. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  69437. mat1.multiplyToRef(mat2, mat1);
  69438. }
  69439. if (this._bone1) {
  69440. if (this.slerpAmount < 1) {
  69441. if (!this._slerping) {
  69442. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  69443. }
  69444. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  69445. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  69446. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  69447. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  69448. this._slerping = true;
  69449. }
  69450. else {
  69451. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  69452. this._bone1Mat.copyFrom(mat1);
  69453. this._slerping = false;
  69454. }
  69455. }
  69456. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  69457. this._bone2Ang = angC;
  69458. };
  69459. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  69460. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  69461. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  69462. return BoneIKController;
  69463. }());
  69464. BABYLON.BoneIKController = BoneIKController;
  69465. })(BABYLON || (BABYLON = {}));
  69466. //# sourceMappingURL=babylon.boneIKController.js.map
  69467. var BABYLON;
  69468. (function (BABYLON) {
  69469. var BoneLookController = /** @class */ (function () {
  69470. /**
  69471. * Create a BoneLookController
  69472. * @param mesh the mesh that the bone belongs to
  69473. * @param bone the bone that will be looking to the target
  69474. * @param target the target Vector3 to look at
  69475. * @param settings optional settings:
  69476. * - maxYaw: the maximum angle the bone will yaw to
  69477. * - minYaw: the minimum angle the bone will yaw to
  69478. * - maxPitch: the maximum angle the bone will pitch to
  69479. * - minPitch: the minimum angle the bone will yaw to
  69480. * - slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  69481. * - upAxis: the up axis of the coordinate system
  69482. * - upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  69483. * - yawAxis: set yawAxis if the bone does not yaw on the y axis
  69484. * - pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  69485. * - adjustYaw: used to make an adjustment to the yaw of the bone
  69486. * - adjustPitch: used to make an adjustment to the pitch of the bone
  69487. * - adjustRoll: used to make an adjustment to the roll of the bone
  69488. **/
  69489. function BoneLookController(mesh, bone, target, options) {
  69490. /**
  69491. * The up axis of the coordinate system that is used when the bone is rotated.
  69492. */
  69493. this.upAxis = BABYLON.Vector3.Up();
  69494. /**
  69495. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  69496. */
  69497. this.upAxisSpace = BABYLON.Space.LOCAL;
  69498. /**
  69499. * Used to make an adjustment to the yaw of the bone.
  69500. */
  69501. this.adjustYaw = 0;
  69502. /**
  69503. * Used to make an adjustment to the pitch of the bone.
  69504. */
  69505. this.adjustPitch = 0;
  69506. /**
  69507. * Used to make an adjustment to the roll of the bone.
  69508. */
  69509. this.adjustRoll = 0;
  69510. /**
  69511. * 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).
  69512. */
  69513. this.slerpAmount = 1;
  69514. this._boneQuat = BABYLON.Quaternion.Identity();
  69515. this._slerping = false;
  69516. this._firstFrameSkipped = false;
  69517. this._fowardAxis = BABYLON.Vector3.Forward();
  69518. this.mesh = mesh;
  69519. this.bone = bone;
  69520. this.target = target;
  69521. if (options) {
  69522. if (options.adjustYaw) {
  69523. this.adjustYaw = options.adjustYaw;
  69524. }
  69525. if (options.adjustPitch) {
  69526. this.adjustPitch = options.adjustPitch;
  69527. }
  69528. if (options.adjustRoll) {
  69529. this.adjustRoll = options.adjustRoll;
  69530. }
  69531. if (options.maxYaw != null) {
  69532. this.maxYaw = options.maxYaw;
  69533. }
  69534. else {
  69535. this.maxYaw = Math.PI;
  69536. }
  69537. if (options.minYaw != null) {
  69538. this.minYaw = options.minYaw;
  69539. }
  69540. else {
  69541. this.minYaw = -Math.PI;
  69542. }
  69543. if (options.maxPitch != null) {
  69544. this.maxPitch = options.maxPitch;
  69545. }
  69546. else {
  69547. this.maxPitch = Math.PI;
  69548. }
  69549. if (options.minPitch != null) {
  69550. this.minPitch = options.minPitch;
  69551. }
  69552. else {
  69553. this.minPitch = -Math.PI;
  69554. }
  69555. if (options.slerpAmount != null) {
  69556. this.slerpAmount = options.slerpAmount;
  69557. }
  69558. if (options.upAxis != null) {
  69559. this.upAxis = options.upAxis;
  69560. }
  69561. if (options.upAxisSpace != null) {
  69562. this.upAxisSpace = options.upAxisSpace;
  69563. }
  69564. if (options.yawAxis != null || options.pitchAxis != null) {
  69565. var newYawAxis = BABYLON.Axis.Y;
  69566. var newPitchAxis = BABYLON.Axis.X;
  69567. if (options.yawAxis != null) {
  69568. newYawAxis = options.yawAxis.clone();
  69569. newYawAxis.normalize();
  69570. }
  69571. if (options.pitchAxis != null) {
  69572. newPitchAxis = options.pitchAxis.clone();
  69573. newPitchAxis.normalize();
  69574. }
  69575. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  69576. this._transformYawPitch = BABYLON.Matrix.Identity();
  69577. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  69578. this._transformYawPitchInv = this._transformYawPitch.clone();
  69579. this._transformYawPitch.invert();
  69580. }
  69581. }
  69582. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  69583. this.upAxisSpace = BABYLON.Space.LOCAL;
  69584. }
  69585. }
  69586. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  69587. /**
  69588. * Get/set the minimum yaw angle that the bone can look to.
  69589. */
  69590. get: function () {
  69591. return this._minYaw;
  69592. },
  69593. set: function (value) {
  69594. this._minYaw = value;
  69595. this._minYawSin = Math.sin(value);
  69596. this._minYawCos = Math.cos(value);
  69597. if (this._maxYaw != null) {
  69598. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  69599. this._yawRange = this._maxYaw - this._minYaw;
  69600. }
  69601. },
  69602. enumerable: true,
  69603. configurable: true
  69604. });
  69605. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  69606. /**
  69607. * Get/set the maximum yaw angle that the bone can look to.
  69608. */
  69609. get: function () {
  69610. return this._maxYaw;
  69611. },
  69612. set: function (value) {
  69613. this._maxYaw = value;
  69614. this._maxYawSin = Math.sin(value);
  69615. this._maxYawCos = Math.cos(value);
  69616. if (this._minYaw != null) {
  69617. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  69618. this._yawRange = this._maxYaw - this._minYaw;
  69619. }
  69620. },
  69621. enumerable: true,
  69622. configurable: true
  69623. });
  69624. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  69625. /**
  69626. * Get/set the minimum pitch angle that the bone can look to.
  69627. */
  69628. get: function () {
  69629. return this._minPitch;
  69630. },
  69631. set: function (value) {
  69632. this._minPitch = value;
  69633. this._minPitchTan = Math.tan(value);
  69634. },
  69635. enumerable: true,
  69636. configurable: true
  69637. });
  69638. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  69639. /**
  69640. * Get/set the maximum pitch angle that the bone can look to.
  69641. */
  69642. get: function () {
  69643. return this._maxPitch;
  69644. },
  69645. set: function (value) {
  69646. this._maxPitch = value;
  69647. this._maxPitchTan = Math.tan(value);
  69648. },
  69649. enumerable: true,
  69650. configurable: true
  69651. });
  69652. /**
  69653. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender()).
  69654. */
  69655. BoneLookController.prototype.update = function () {
  69656. //skip the first frame when slerping so that the mesh rotation is correct
  69657. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  69658. this._firstFrameSkipped = true;
  69659. return;
  69660. }
  69661. var bone = this.bone;
  69662. var bonePos = BoneLookController._tmpVecs[0];
  69663. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  69664. var target = this.target;
  69665. var _tmpMat1 = BoneLookController._tmpMats[0];
  69666. var _tmpMat2 = BoneLookController._tmpMats[1];
  69667. var mesh = this.mesh;
  69668. var parentBone = bone.getParent();
  69669. var upAxis = BoneLookController._tmpVecs[1];
  69670. upAxis.copyFrom(this.upAxis);
  69671. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  69672. if (this._transformYawPitch) {
  69673. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  69674. }
  69675. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  69676. }
  69677. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  69678. mesh.getDirectionToRef(upAxis, upAxis);
  69679. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  69680. upAxis.normalize();
  69681. }
  69682. }
  69683. var checkYaw = false;
  69684. var checkPitch = false;
  69685. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  69686. checkYaw = true;
  69687. }
  69688. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  69689. checkPitch = true;
  69690. }
  69691. if (checkYaw || checkPitch) {
  69692. var spaceMat = BoneLookController._tmpMats[2];
  69693. var spaceMatInv = BoneLookController._tmpMats[3];
  69694. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  69695. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  69696. }
  69697. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  69698. spaceMat.copyFrom(mesh.getWorldMatrix());
  69699. }
  69700. else {
  69701. var forwardAxis = BoneLookController._tmpVecs[2];
  69702. forwardAxis.copyFrom(this._fowardAxis);
  69703. if (this._transformYawPitch) {
  69704. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  69705. }
  69706. if (parentBone) {
  69707. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  69708. }
  69709. else {
  69710. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  69711. }
  69712. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  69713. rightAxis.normalize();
  69714. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  69715. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  69716. }
  69717. spaceMat.invertToRef(spaceMatInv);
  69718. var xzlen = null;
  69719. if (checkPitch) {
  69720. var localTarget = BoneLookController._tmpVecs[3];
  69721. target.subtractToRef(bonePos, localTarget);
  69722. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  69723. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  69724. var pitch = Math.atan2(localTarget.y, xzlen);
  69725. var newPitch = pitch;
  69726. if (pitch > this._maxPitch) {
  69727. localTarget.y = this._maxPitchTan * xzlen;
  69728. newPitch = this._maxPitch;
  69729. }
  69730. else if (pitch < this._minPitch) {
  69731. localTarget.y = this._minPitchTan * xzlen;
  69732. newPitch = this._minPitch;
  69733. }
  69734. if (pitch != newPitch) {
  69735. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  69736. localTarget.addInPlace(bonePos);
  69737. target = localTarget;
  69738. }
  69739. }
  69740. if (checkYaw) {
  69741. var localTarget = BoneLookController._tmpVecs[4];
  69742. target.subtractToRef(bonePos, localTarget);
  69743. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  69744. var yaw = Math.atan2(localTarget.x, localTarget.z);
  69745. var newYaw = yaw;
  69746. if (yaw > this._maxYaw || yaw < this._minYaw) {
  69747. if (xzlen == null) {
  69748. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  69749. }
  69750. if (this._yawRange > Math.PI) {
  69751. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  69752. localTarget.z = this._maxYawCos * xzlen;
  69753. localTarget.x = this._maxYawSin * xzlen;
  69754. newYaw = this._maxYaw;
  69755. }
  69756. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  69757. localTarget.z = this._minYawCos * xzlen;
  69758. localTarget.x = this._minYawSin * xzlen;
  69759. newYaw = this._minYaw;
  69760. }
  69761. }
  69762. else {
  69763. if (yaw > this._maxYaw) {
  69764. localTarget.z = this._maxYawCos * xzlen;
  69765. localTarget.x = this._maxYawSin * xzlen;
  69766. newYaw = this._maxYaw;
  69767. }
  69768. else if (yaw < this._minYaw) {
  69769. localTarget.z = this._minYawCos * xzlen;
  69770. localTarget.x = this._minYawSin * xzlen;
  69771. newYaw = this._minYaw;
  69772. }
  69773. }
  69774. }
  69775. if (this._slerping && this._yawRange > Math.PI) {
  69776. //are we going to be crossing into the min/max region?
  69777. var boneFwd = BoneLookController._tmpVecs[8];
  69778. boneFwd.copyFrom(BABYLON.Axis.Z);
  69779. if (this._transformYawPitch) {
  69780. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  69781. }
  69782. var boneRotMat = BoneLookController._tmpMats[4];
  69783. this._boneQuat.toRotationMatrix(boneRotMat);
  69784. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  69785. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  69786. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  69787. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  69788. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  69789. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  69790. if (angBtwTar > angBtwMidYaw) {
  69791. if (xzlen == null) {
  69792. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  69793. }
  69794. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  69795. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  69796. if (angBtwMin < angBtwMax) {
  69797. newYaw = boneYaw + Math.PI * .75;
  69798. localTarget.z = Math.cos(newYaw) * xzlen;
  69799. localTarget.x = Math.sin(newYaw) * xzlen;
  69800. }
  69801. else {
  69802. newYaw = boneYaw - Math.PI * .75;
  69803. localTarget.z = Math.cos(newYaw) * xzlen;
  69804. localTarget.x = Math.sin(newYaw) * xzlen;
  69805. }
  69806. }
  69807. }
  69808. if (yaw != newYaw) {
  69809. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  69810. localTarget.addInPlace(bonePos);
  69811. target = localTarget;
  69812. }
  69813. }
  69814. }
  69815. var zaxis = BoneLookController._tmpVecs[5];
  69816. var xaxis = BoneLookController._tmpVecs[6];
  69817. var yaxis = BoneLookController._tmpVecs[7];
  69818. var _tmpQuat = BoneLookController._tmpQuat;
  69819. target.subtractToRef(bonePos, zaxis);
  69820. zaxis.normalize();
  69821. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  69822. xaxis.normalize();
  69823. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  69824. yaxis.normalize();
  69825. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  69826. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  69827. return;
  69828. }
  69829. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  69830. return;
  69831. }
  69832. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  69833. return;
  69834. }
  69835. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  69836. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  69837. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  69838. }
  69839. if (this.slerpAmount < 1) {
  69840. if (!this._slerping) {
  69841. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  69842. }
  69843. if (this._transformYawPitch) {
  69844. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  69845. }
  69846. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  69847. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  69848. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  69849. this._slerping = true;
  69850. }
  69851. else {
  69852. if (this._transformYawPitch) {
  69853. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  69854. }
  69855. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  69856. this._slerping = false;
  69857. }
  69858. };
  69859. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  69860. var angDiff = ang2 - ang1;
  69861. angDiff %= Math.PI * 2;
  69862. if (angDiff > Math.PI) {
  69863. angDiff -= Math.PI * 2;
  69864. }
  69865. else if (angDiff < -Math.PI) {
  69866. angDiff += Math.PI * 2;
  69867. }
  69868. return angDiff;
  69869. };
  69870. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  69871. ang1 %= (2 * Math.PI);
  69872. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  69873. ang2 %= (2 * Math.PI);
  69874. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  69875. var ab = 0;
  69876. if (ang1 < ang2) {
  69877. ab = ang2 - ang1;
  69878. }
  69879. else {
  69880. ab = ang1 - ang2;
  69881. }
  69882. if (ab > Math.PI) {
  69883. ab = Math.PI * 2 - ab;
  69884. }
  69885. return ab;
  69886. };
  69887. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  69888. ang %= (2 * Math.PI);
  69889. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  69890. ang1 %= (2 * Math.PI);
  69891. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  69892. ang2 %= (2 * Math.PI);
  69893. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  69894. if (ang1 < ang2) {
  69895. if (ang > ang1 && ang < ang2) {
  69896. return true;
  69897. }
  69898. }
  69899. else {
  69900. if (ang > ang2 && ang < ang1) {
  69901. return true;
  69902. }
  69903. }
  69904. return false;
  69905. };
  69906. 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()];
  69907. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  69908. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  69909. return BoneLookController;
  69910. }());
  69911. BABYLON.BoneLookController = BoneLookController;
  69912. })(BABYLON || (BABYLON = {}));
  69913. //# sourceMappingURL=babylon.boneLookController.js.map
  69914. var BABYLON;
  69915. (function (BABYLON) {
  69916. var Skeleton = /** @class */ (function () {
  69917. function Skeleton(name, id, scene) {
  69918. this.name = name;
  69919. this.id = id;
  69920. this.bones = new Array();
  69921. this.needInitialSkinMatrix = false;
  69922. this._isDirty = true;
  69923. this._meshesWithPoseMatrix = new Array();
  69924. this._identity = BABYLON.Matrix.Identity();
  69925. this._ranges = {};
  69926. this._lastAbsoluteTransformsUpdateId = -1;
  69927. // Events
  69928. /**
  69929. * An event triggered before computing the skeleton's matrices
  69930. * @type {BABYLON.Observable}
  69931. */
  69932. this.onBeforeComputeObservable = new BABYLON.Observable();
  69933. this.bones = [];
  69934. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  69935. scene.skeletons.push(this);
  69936. //make sure it will recalculate the matrix next time prepare is called.
  69937. this._isDirty = true;
  69938. }
  69939. // Members
  69940. Skeleton.prototype.getTransformMatrices = function (mesh) {
  69941. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  69942. return mesh._bonesTransformMatrices;
  69943. }
  69944. if (!this._transformMatrices) {
  69945. this.prepare();
  69946. }
  69947. return this._transformMatrices;
  69948. };
  69949. Skeleton.prototype.getScene = function () {
  69950. return this._scene;
  69951. };
  69952. // Methods
  69953. /**
  69954. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  69955. */
  69956. Skeleton.prototype.toString = function (fullDetails) {
  69957. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  69958. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  69959. if (fullDetails) {
  69960. ret += ", Ranges: {";
  69961. var first = true;
  69962. for (var name_1 in this._ranges) {
  69963. if (first) {
  69964. ret += ", ";
  69965. first = false;
  69966. }
  69967. ret += name_1;
  69968. }
  69969. ret += "}";
  69970. }
  69971. return ret;
  69972. };
  69973. /**
  69974. * Get bone's index searching by name
  69975. * @param {string} name is bone's name to search for
  69976. * @return {number} Indice of the bone. Returns -1 if not found
  69977. */
  69978. Skeleton.prototype.getBoneIndexByName = function (name) {
  69979. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  69980. if (this.bones[boneIndex].name === name) {
  69981. return boneIndex;
  69982. }
  69983. }
  69984. return -1;
  69985. };
  69986. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  69987. // check name not already in use
  69988. if (!this._ranges[name]) {
  69989. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  69990. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  69991. if (this.bones[i].animations[0]) {
  69992. this.bones[i].animations[0].createRange(name, from, to);
  69993. }
  69994. }
  69995. }
  69996. };
  69997. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  69998. if (deleteFrames === void 0) { deleteFrames = true; }
  69999. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  70000. if (this.bones[i].animations[0]) {
  70001. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  70002. }
  70003. }
  70004. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  70005. };
  70006. Skeleton.prototype.getAnimationRange = function (name) {
  70007. return this._ranges[name];
  70008. };
  70009. /**
  70010. * Returns as an Array, all AnimationRanges defined on this skeleton
  70011. */
  70012. Skeleton.prototype.getAnimationRanges = function () {
  70013. var animationRanges = [];
  70014. var name;
  70015. var i = 0;
  70016. for (name in this._ranges) {
  70017. animationRanges[i] = this._ranges[name];
  70018. i++;
  70019. }
  70020. return animationRanges;
  70021. };
  70022. /**
  70023. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  70024. */
  70025. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  70026. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  70027. if (this._ranges[name] || !source.getAnimationRange(name)) {
  70028. return false;
  70029. }
  70030. var ret = true;
  70031. var frameOffset = this._getHighestAnimationFrame() + 1;
  70032. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  70033. var boneDict = {};
  70034. var sourceBones = source.bones;
  70035. var nBones;
  70036. var i;
  70037. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  70038. boneDict[sourceBones[i].name] = sourceBones[i];
  70039. }
  70040. if (this.bones.length !== sourceBones.length) {
  70041. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  70042. ret = false;
  70043. }
  70044. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  70045. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  70046. var boneName = this.bones[i].name;
  70047. var sourceBone = boneDict[boneName];
  70048. if (sourceBone) {
  70049. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  70050. }
  70051. else {
  70052. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  70053. ret = false;
  70054. }
  70055. }
  70056. // do not call createAnimationRange(), since it also is done to bones, which was already done
  70057. var range = source.getAnimationRange(name);
  70058. if (range) {
  70059. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  70060. }
  70061. return ret;
  70062. };
  70063. Skeleton.prototype.returnToRest = function () {
  70064. for (var index = 0; index < this.bones.length; index++) {
  70065. this.bones[index].returnToRest();
  70066. }
  70067. };
  70068. Skeleton.prototype._getHighestAnimationFrame = function () {
  70069. var ret = 0;
  70070. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  70071. if (this.bones[i].animations[0]) {
  70072. var highest = this.bones[i].animations[0].getHighestFrame();
  70073. if (ret < highest) {
  70074. ret = highest;
  70075. }
  70076. }
  70077. }
  70078. return ret;
  70079. };
  70080. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  70081. var range = this.getAnimationRange(name);
  70082. if (!range) {
  70083. return null;
  70084. }
  70085. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  70086. };
  70087. Skeleton.prototype._markAsDirty = function () {
  70088. this._isDirty = true;
  70089. };
  70090. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  70091. this._meshesWithPoseMatrix.push(mesh);
  70092. };
  70093. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  70094. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  70095. if (index > -1) {
  70096. this._meshesWithPoseMatrix.splice(index, 1);
  70097. }
  70098. };
  70099. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  70100. this.onBeforeComputeObservable.notifyObservers(this);
  70101. for (var index = 0; index < this.bones.length; index++) {
  70102. var bone = this.bones[index];
  70103. var parentBone = bone.getParent();
  70104. if (parentBone) {
  70105. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  70106. }
  70107. else {
  70108. if (initialSkinMatrix) {
  70109. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  70110. }
  70111. else {
  70112. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  70113. }
  70114. }
  70115. if (bone._index !== -1) {
  70116. var mappedIndex = bone._index === null ? index : bone._index;
  70117. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  70118. }
  70119. }
  70120. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  70121. };
  70122. Skeleton.prototype.prepare = function () {
  70123. if (!this._isDirty) {
  70124. return;
  70125. }
  70126. if (this.needInitialSkinMatrix) {
  70127. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  70128. var mesh = this._meshesWithPoseMatrix[index];
  70129. var poseMatrix = mesh.getPoseMatrix();
  70130. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  70131. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  70132. }
  70133. if (this._synchronizedWithMesh !== mesh) {
  70134. this._synchronizedWithMesh = mesh;
  70135. // Prepare bones
  70136. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  70137. var bone = this.bones[boneIndex];
  70138. if (!bone.getParent()) {
  70139. var matrix = bone.getBaseMatrix();
  70140. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  70141. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  70142. }
  70143. }
  70144. }
  70145. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  70146. }
  70147. }
  70148. else {
  70149. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  70150. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  70151. }
  70152. this._computeTransformMatrices(this._transformMatrices, null);
  70153. }
  70154. this._isDirty = false;
  70155. this._scene._activeBones.addCount(this.bones.length, false);
  70156. };
  70157. Skeleton.prototype.getAnimatables = function () {
  70158. if (!this._animatables || this._animatables.length !== this.bones.length) {
  70159. this._animatables = [];
  70160. for (var index = 0; index < this.bones.length; index++) {
  70161. this._animatables.push(this.bones[index]);
  70162. }
  70163. }
  70164. return this._animatables;
  70165. };
  70166. Skeleton.prototype.clone = function (name, id) {
  70167. var result = new Skeleton(name, id || name, this._scene);
  70168. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  70169. for (var index = 0; index < this.bones.length; index++) {
  70170. var source = this.bones[index];
  70171. var parentBone = null;
  70172. var parent_1 = source.getParent();
  70173. if (parent_1) {
  70174. var parentIndex = this.bones.indexOf(parent_1);
  70175. parentBone = result.bones[parentIndex];
  70176. }
  70177. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  70178. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  70179. }
  70180. if (this._ranges) {
  70181. result._ranges = {};
  70182. for (var rangeName in this._ranges) {
  70183. var range = this._ranges[rangeName];
  70184. if (range) {
  70185. result._ranges[rangeName] = range.clone();
  70186. }
  70187. }
  70188. }
  70189. this._isDirty = true;
  70190. return result;
  70191. };
  70192. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  70193. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  70194. this.bones.forEach(function (bone) {
  70195. bone.animations.forEach(function (animation) {
  70196. animation.enableBlending = true;
  70197. animation.blendingSpeed = blendingSpeed;
  70198. });
  70199. });
  70200. };
  70201. Skeleton.prototype.dispose = function () {
  70202. this._meshesWithPoseMatrix = [];
  70203. // Animations
  70204. this.getScene().stopAnimation(this);
  70205. // Remove from scene
  70206. this.getScene().removeSkeleton(this);
  70207. };
  70208. Skeleton.prototype.serialize = function () {
  70209. var serializationObject = {};
  70210. serializationObject.name = this.name;
  70211. serializationObject.id = this.id;
  70212. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  70213. serializationObject.bones = [];
  70214. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  70215. for (var index = 0; index < this.bones.length; index++) {
  70216. var bone = this.bones[index];
  70217. var parent_2 = bone.getParent();
  70218. var serializedBone = {
  70219. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  70220. name: bone.name,
  70221. matrix: bone.getBaseMatrix().toArray(),
  70222. rest: bone.getRestPose().toArray()
  70223. };
  70224. serializationObject.bones.push(serializedBone);
  70225. if (bone.length) {
  70226. serializedBone.length = bone.length;
  70227. }
  70228. if (bone.animations && bone.animations.length > 0) {
  70229. serializedBone.animation = bone.animations[0].serialize();
  70230. }
  70231. serializationObject.ranges = [];
  70232. for (var name in this._ranges) {
  70233. var source = this._ranges[name];
  70234. if (!source) {
  70235. continue;
  70236. }
  70237. var range = {};
  70238. range.name = name;
  70239. range.from = source.from;
  70240. range.to = source.to;
  70241. serializationObject.ranges.push(range);
  70242. }
  70243. }
  70244. return serializationObject;
  70245. };
  70246. Skeleton.Parse = function (parsedSkeleton, scene) {
  70247. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  70248. if (parsedSkeleton.dimensionsAtRest) {
  70249. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  70250. }
  70251. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  70252. var index;
  70253. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  70254. var parsedBone = parsedSkeleton.bones[index];
  70255. var parentBone = null;
  70256. if (parsedBone.parentBoneIndex > -1) {
  70257. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  70258. }
  70259. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  70260. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  70261. if (parsedBone.length) {
  70262. bone.length = parsedBone.length;
  70263. }
  70264. if (parsedBone.animation) {
  70265. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  70266. }
  70267. }
  70268. // placed after bones, so createAnimationRange can cascade down
  70269. if (parsedSkeleton.ranges) {
  70270. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  70271. var data = parsedSkeleton.ranges[index];
  70272. skeleton.createAnimationRange(data.name, data.from, data.to);
  70273. }
  70274. }
  70275. return skeleton;
  70276. };
  70277. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  70278. if (forceUpdate === void 0) { forceUpdate = false; }
  70279. var renderId = this._scene.getRenderId();
  70280. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  70281. this.bones[0].computeAbsoluteTransforms();
  70282. this._lastAbsoluteTransformsUpdateId = renderId;
  70283. }
  70284. };
  70285. Skeleton.prototype.getPoseMatrix = function () {
  70286. var poseMatrix = null;
  70287. if (this._meshesWithPoseMatrix.length > 0) {
  70288. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  70289. }
  70290. return poseMatrix;
  70291. };
  70292. Skeleton.prototype.sortBones = function () {
  70293. var bones = new Array();
  70294. var visited = new Array(this.bones.length);
  70295. for (var index = 0; index < this.bones.length; index++) {
  70296. this._sortBones(index, bones, visited);
  70297. }
  70298. this.bones = bones;
  70299. };
  70300. Skeleton.prototype._sortBones = function (index, bones, visited) {
  70301. if (visited[index]) {
  70302. return;
  70303. }
  70304. visited[index] = true;
  70305. var bone = this.bones[index];
  70306. if (bone._index === undefined) {
  70307. bone._index = index;
  70308. }
  70309. var parentBone = bone.getParent();
  70310. if (parentBone) {
  70311. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  70312. }
  70313. bones.push(bone);
  70314. };
  70315. return Skeleton;
  70316. }());
  70317. BABYLON.Skeleton = Skeleton;
  70318. })(BABYLON || (BABYLON = {}));
  70319. //# sourceMappingURL=babylon.skeleton.js.map
  70320. var BABYLON;
  70321. (function (BABYLON) {
  70322. var SphericalPolynomial = /** @class */ (function () {
  70323. function SphericalPolynomial() {
  70324. this.x = BABYLON.Vector3.Zero();
  70325. this.y = BABYLON.Vector3.Zero();
  70326. this.z = BABYLON.Vector3.Zero();
  70327. this.xx = BABYLON.Vector3.Zero();
  70328. this.yy = BABYLON.Vector3.Zero();
  70329. this.zz = BABYLON.Vector3.Zero();
  70330. this.xy = BABYLON.Vector3.Zero();
  70331. this.yz = BABYLON.Vector3.Zero();
  70332. this.zx = BABYLON.Vector3.Zero();
  70333. }
  70334. SphericalPolynomial.prototype.addAmbient = function (color) {
  70335. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  70336. this.xx = this.xx.add(colorVector);
  70337. this.yy = this.yy.add(colorVector);
  70338. this.zz = this.zz.add(colorVector);
  70339. };
  70340. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  70341. var result = new SphericalPolynomial();
  70342. result.x = harmonics.L11.scale(1.02333);
  70343. result.y = harmonics.L1_1.scale(1.02333);
  70344. result.z = harmonics.L10.scale(1.02333);
  70345. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  70346. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  70347. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  70348. result.yz = harmonics.L2_1.scale(0.858086);
  70349. result.zx = harmonics.L21.scale(0.858086);
  70350. result.xy = harmonics.L2_2.scale(0.858086);
  70351. result.scale(1.0 / Math.PI);
  70352. return result;
  70353. };
  70354. SphericalPolynomial.prototype.scale = function (scale) {
  70355. this.x = this.x.scale(scale);
  70356. this.y = this.y.scale(scale);
  70357. this.z = this.z.scale(scale);
  70358. this.xx = this.xx.scale(scale);
  70359. this.yy = this.yy.scale(scale);
  70360. this.zz = this.zz.scale(scale);
  70361. this.yz = this.yz.scale(scale);
  70362. this.zx = this.zx.scale(scale);
  70363. this.xy = this.xy.scale(scale);
  70364. };
  70365. return SphericalPolynomial;
  70366. }());
  70367. BABYLON.SphericalPolynomial = SphericalPolynomial;
  70368. var SphericalHarmonics = /** @class */ (function () {
  70369. function SphericalHarmonics() {
  70370. this.L00 = BABYLON.Vector3.Zero();
  70371. this.L1_1 = BABYLON.Vector3.Zero();
  70372. this.L10 = BABYLON.Vector3.Zero();
  70373. this.L11 = BABYLON.Vector3.Zero();
  70374. this.L2_2 = BABYLON.Vector3.Zero();
  70375. this.L2_1 = BABYLON.Vector3.Zero();
  70376. this.L20 = BABYLON.Vector3.Zero();
  70377. this.L21 = BABYLON.Vector3.Zero();
  70378. this.L22 = BABYLON.Vector3.Zero();
  70379. }
  70380. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  70381. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  70382. var c = colorVector.scale(deltaSolidAngle);
  70383. this.L00 = this.L00.add(c.scale(0.282095));
  70384. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  70385. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  70386. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  70387. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  70388. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  70389. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  70390. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  70391. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  70392. };
  70393. SphericalHarmonics.prototype.scale = function (scale) {
  70394. this.L00 = this.L00.scale(scale);
  70395. this.L1_1 = this.L1_1.scale(scale);
  70396. this.L10 = this.L10.scale(scale);
  70397. this.L11 = this.L11.scale(scale);
  70398. this.L2_2 = this.L2_2.scale(scale);
  70399. this.L2_1 = this.L2_1.scale(scale);
  70400. this.L20 = this.L20.scale(scale);
  70401. this.L21 = this.L21.scale(scale);
  70402. this.L22 = this.L22.scale(scale);
  70403. };
  70404. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  70405. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  70406. //
  70407. // E_lm = A_l * L_lm
  70408. //
  70409. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  70410. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  70411. // the scaling factors are given in equation 9.
  70412. // Constant (Band 0)
  70413. this.L00 = this.L00.scale(3.141593);
  70414. // Linear (Band 1)
  70415. this.L1_1 = this.L1_1.scale(2.094395);
  70416. this.L10 = this.L10.scale(2.094395);
  70417. this.L11 = this.L11.scale(2.094395);
  70418. // Quadratic (Band 2)
  70419. this.L2_2 = this.L2_2.scale(0.785398);
  70420. this.L2_1 = this.L2_1.scale(0.785398);
  70421. this.L20 = this.L20.scale(0.785398);
  70422. this.L21 = this.L21.scale(0.785398);
  70423. this.L22 = this.L22.scale(0.785398);
  70424. };
  70425. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  70426. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  70427. // L = (1/pi) * E * rho
  70428. //
  70429. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  70430. this.scale(1.0 / Math.PI);
  70431. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  70432. // (The pixel shader must apply albedo after texture fetches, etc).
  70433. };
  70434. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  70435. var result = new SphericalHarmonics();
  70436. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  70437. result.L1_1 = polynomial.y.scale(0.977204);
  70438. result.L10 = polynomial.z.scale(0.977204);
  70439. result.L11 = polynomial.x.scale(0.977204);
  70440. result.L2_2 = polynomial.xy.scale(1.16538);
  70441. result.L2_1 = polynomial.yz.scale(1.16538);
  70442. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  70443. result.L21 = polynomial.zx.scale(1.16538);
  70444. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  70445. result.scale(Math.PI);
  70446. return result;
  70447. };
  70448. return SphericalHarmonics;
  70449. }());
  70450. BABYLON.SphericalHarmonics = SphericalHarmonics;
  70451. })(BABYLON || (BABYLON = {}));
  70452. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  70453. var BABYLON;
  70454. (function (BABYLON) {
  70455. var FileFaceOrientation = /** @class */ (function () {
  70456. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  70457. this.name = name;
  70458. this.worldAxisForNormal = worldAxisForNormal;
  70459. this.worldAxisForFileX = worldAxisForFileX;
  70460. this.worldAxisForFileY = worldAxisForFileY;
  70461. }
  70462. return FileFaceOrientation;
  70463. }());
  70464. ;
  70465. /**
  70466. * Helper class dealing with the extraction of spherical polynomial dataArray
  70467. * from a cube map.
  70468. */
  70469. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  70470. function CubeMapToSphericalPolynomialTools() {
  70471. }
  70472. /**
  70473. * Converts a texture to the according Spherical Polynomial data.
  70474. * This extracts the first 3 orders only as they are the only one used in the lighting.
  70475. *
  70476. * @param texture The texture to extract the information from.
  70477. * @return The Spherical Polynomial data.
  70478. */
  70479. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  70480. if (!texture.isCube) {
  70481. // Only supports cube Textures currently.
  70482. return null;
  70483. }
  70484. var size = texture.getSize().width;
  70485. var right = texture.readPixels(0);
  70486. var left = texture.readPixels(1);
  70487. var up;
  70488. var down;
  70489. if (texture.isRenderTarget) {
  70490. up = texture.readPixels(3);
  70491. down = texture.readPixels(2);
  70492. }
  70493. else {
  70494. up = texture.readPixels(2);
  70495. down = texture.readPixels(3);
  70496. }
  70497. var front = texture.readPixels(4);
  70498. var back = texture.readPixels(5);
  70499. var gammaSpace = texture.gammaSpace;
  70500. // Always read as RGBA.
  70501. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  70502. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  70503. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  70504. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  70505. }
  70506. var cubeInfo = {
  70507. size: size,
  70508. right: right,
  70509. left: left,
  70510. up: up,
  70511. down: down,
  70512. front: front,
  70513. back: back,
  70514. format: format,
  70515. type: type,
  70516. gammaSpace: gammaSpace,
  70517. };
  70518. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  70519. };
  70520. /**
  70521. * Converts a cubemap to the according Spherical Polynomial data.
  70522. * This extracts the first 3 orders only as they are the only one used in the lighting.
  70523. *
  70524. * @param cubeInfo The Cube map to extract the information from.
  70525. * @return The Spherical Polynomial data.
  70526. */
  70527. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  70528. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  70529. var totalSolidAngle = 0.0;
  70530. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  70531. var du = 2.0 / cubeInfo.size;
  70532. var dv = du;
  70533. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  70534. var minUV = du * 0.5 - 1.0;
  70535. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  70536. var fileFace = this.FileFaces[faceIndex];
  70537. var dataArray = cubeInfo[fileFace.name];
  70538. var v = minUV;
  70539. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  70540. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  70541. // Because SP is still linear, so summation is fine in that basis.
  70542. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  70543. for (var y = 0; y < cubeInfo.size; y++) {
  70544. var u = minUV;
  70545. for (var x = 0; x < cubeInfo.size; x++) {
  70546. // World direction (not normalised)
  70547. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  70548. worldDirection.normalize();
  70549. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  70550. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  70551. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  70552. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  70553. // Handle Integer types.
  70554. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  70555. r /= 255;
  70556. g /= 255;
  70557. b /= 255;
  70558. }
  70559. // Handle Gamma space textures.
  70560. if (cubeInfo.gammaSpace) {
  70561. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  70562. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  70563. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  70564. }
  70565. var color = new BABYLON.Color3(r, g, b);
  70566. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  70567. totalSolidAngle += deltaSolidAngle;
  70568. u += du;
  70569. }
  70570. v += dv;
  70571. }
  70572. }
  70573. // Solid angle for entire sphere is 4*pi
  70574. var sphereSolidAngle = 4.0 * Math.PI;
  70575. // Adjust the solid angle to allow for how many faces we processed.
  70576. var facesProcessed = 6.0;
  70577. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  70578. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  70579. // This is needed because the numerical integration over the cube uses a
  70580. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  70581. // and also to compensate for accumulative error due to float precision in the summation.
  70582. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  70583. sphericalHarmonics.scale(correctionFactor);
  70584. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  70585. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  70586. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  70587. };
  70588. CubeMapToSphericalPolynomialTools.FileFaces = [
  70589. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  70590. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  70591. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  70592. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  70593. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  70594. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  70595. ];
  70596. return CubeMapToSphericalPolynomialTools;
  70597. }());
  70598. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  70599. })(BABYLON || (BABYLON = {}));
  70600. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  70601. var BABYLON;
  70602. (function (BABYLON) {
  70603. /**
  70604. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  70605. */
  70606. var PanoramaToCubeMapTools = /** @class */ (function () {
  70607. function PanoramaToCubeMapTools() {
  70608. }
  70609. /**
  70610. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  70611. *
  70612. * @param float32Array The source data.
  70613. * @param inputWidth The width of the input panorama.
  70614. * @param inputhHeight The height of the input panorama.
  70615. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  70616. * @return The cubemap data
  70617. */
  70618. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  70619. if (!float32Array) {
  70620. throw "ConvertPanoramaToCubemap: input cannot be null";
  70621. }
  70622. if (float32Array.length != inputWidth * inputHeight * 3) {
  70623. throw "ConvertPanoramaToCubemap: input size is wrong";
  70624. }
  70625. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  70626. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  70627. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  70628. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  70629. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  70630. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  70631. return {
  70632. front: textureFront,
  70633. back: textureBack,
  70634. left: textureLeft,
  70635. right: textureRight,
  70636. up: textureUp,
  70637. down: textureDown,
  70638. size: size,
  70639. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  70640. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  70641. gammaSpace: false,
  70642. };
  70643. };
  70644. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  70645. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  70646. var textureArray = new Float32Array(buffer);
  70647. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  70648. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  70649. var dy = 1 / texSize;
  70650. var fy = 0;
  70651. for (var y = 0; y < texSize; y++) {
  70652. var xv1 = faceData[0];
  70653. var xv2 = faceData[2];
  70654. for (var x = 0; x < texSize; x++) {
  70655. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  70656. v.normalize();
  70657. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  70658. // 3 channels per pixels
  70659. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  70660. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  70661. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  70662. xv1 = xv1.add(rotDX1);
  70663. xv2 = xv2.add(rotDX2);
  70664. }
  70665. fy += dy;
  70666. }
  70667. return textureArray;
  70668. };
  70669. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  70670. var theta = Math.atan2(vDir.z, vDir.x);
  70671. var phi = Math.acos(vDir.y);
  70672. while (theta < -Math.PI)
  70673. theta += 2 * Math.PI;
  70674. while (theta > Math.PI)
  70675. theta -= 2 * Math.PI;
  70676. var dx = theta / Math.PI;
  70677. var dy = phi / Math.PI;
  70678. // recenter.
  70679. dx = dx * 0.5 + 0.5;
  70680. var px = Math.round(dx * inputWidth);
  70681. if (px < 0)
  70682. px = 0;
  70683. else if (px >= inputWidth)
  70684. px = inputWidth - 1;
  70685. var py = Math.round(dy * inputHeight);
  70686. if (py < 0)
  70687. py = 0;
  70688. else if (py >= inputHeight)
  70689. py = inputHeight - 1;
  70690. var inputY = (inputHeight - py - 1);
  70691. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  70692. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  70693. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  70694. return {
  70695. r: r,
  70696. g: g,
  70697. b: b
  70698. };
  70699. };
  70700. PanoramaToCubeMapTools.FACE_FRONT = [
  70701. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  70702. new BABYLON.Vector3(1.0, -1.0, -1.0),
  70703. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  70704. new BABYLON.Vector3(1.0, 1.0, -1.0)
  70705. ];
  70706. PanoramaToCubeMapTools.FACE_BACK = [
  70707. new BABYLON.Vector3(1.0, -1.0, 1.0),
  70708. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  70709. new BABYLON.Vector3(1.0, 1.0, 1.0),
  70710. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  70711. ];
  70712. PanoramaToCubeMapTools.FACE_RIGHT = [
  70713. new BABYLON.Vector3(1.0, -1.0, -1.0),
  70714. new BABYLON.Vector3(1.0, -1.0, 1.0),
  70715. new BABYLON.Vector3(1.0, 1.0, -1.0),
  70716. new BABYLON.Vector3(1.0, 1.0, 1.0)
  70717. ];
  70718. PanoramaToCubeMapTools.FACE_LEFT = [
  70719. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  70720. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  70721. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  70722. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  70723. ];
  70724. PanoramaToCubeMapTools.FACE_DOWN = [
  70725. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  70726. new BABYLON.Vector3(1.0, 1.0, -1.0),
  70727. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  70728. new BABYLON.Vector3(1.0, 1.0, 1.0)
  70729. ];
  70730. PanoramaToCubeMapTools.FACE_UP = [
  70731. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  70732. new BABYLON.Vector3(1.0, -1.0, 1.0),
  70733. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  70734. new BABYLON.Vector3(1.0, -1.0, -1.0)
  70735. ];
  70736. return PanoramaToCubeMapTools;
  70737. }());
  70738. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  70739. })(BABYLON || (BABYLON = {}));
  70740. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  70741. var BABYLON;
  70742. (function (BABYLON) {
  70743. ;
  70744. /**
  70745. * This groups tools to convert HDR texture to native colors array.
  70746. */
  70747. var HDRTools = /** @class */ (function () {
  70748. function HDRTools() {
  70749. }
  70750. HDRTools.Ldexp = function (mantissa, exponent) {
  70751. if (exponent > 1023) {
  70752. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  70753. }
  70754. if (exponent < -1074) {
  70755. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  70756. }
  70757. return mantissa * Math.pow(2, exponent);
  70758. };
  70759. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  70760. if (exponent > 0) {
  70761. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  70762. float32array[index + 0] = red * exponent;
  70763. float32array[index + 1] = green * exponent;
  70764. float32array[index + 2] = blue * exponent;
  70765. }
  70766. else {
  70767. float32array[index + 0] = 0;
  70768. float32array[index + 1] = 0;
  70769. float32array[index + 2] = 0;
  70770. }
  70771. };
  70772. HDRTools.readStringLine = function (uint8array, startIndex) {
  70773. var line = "";
  70774. var character = "";
  70775. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  70776. character = String.fromCharCode(uint8array[i]);
  70777. if (character == "\n") {
  70778. break;
  70779. }
  70780. line += character;
  70781. }
  70782. return line;
  70783. };
  70784. /**
  70785. * Reads header information from an RGBE texture stored in a native array.
  70786. * More information on this format are available here:
  70787. * https://en.wikipedia.org/wiki/RGBE_image_format
  70788. *
  70789. * @param uint8array The binary file stored in native array.
  70790. * @return The header information.
  70791. */
  70792. HDRTools.RGBE_ReadHeader = function (uint8array) {
  70793. var height = 0;
  70794. var width = 0;
  70795. var line = this.readStringLine(uint8array, 0);
  70796. if (line[0] != '#' || line[1] != '?') {
  70797. throw "Bad HDR Format.";
  70798. }
  70799. var endOfHeader = false;
  70800. var findFormat = false;
  70801. var lineIndex = 0;
  70802. do {
  70803. lineIndex += (line.length + 1);
  70804. line = this.readStringLine(uint8array, lineIndex);
  70805. if (line == "FORMAT=32-bit_rle_rgbe") {
  70806. findFormat = true;
  70807. }
  70808. else if (line.length == 0) {
  70809. endOfHeader = true;
  70810. }
  70811. } while (!endOfHeader);
  70812. if (!findFormat) {
  70813. throw "HDR Bad header format, unsupported FORMAT";
  70814. }
  70815. lineIndex += (line.length + 1);
  70816. line = this.readStringLine(uint8array, lineIndex);
  70817. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  70818. var match = sizeRegexp.exec(line);
  70819. // TODO. Support +Y and -X if needed.
  70820. if (!match || match.length < 3) {
  70821. throw "HDR Bad header format, no size";
  70822. }
  70823. width = parseInt(match[2]);
  70824. height = parseInt(match[1]);
  70825. if (width < 8 || width > 0x7fff) {
  70826. throw "HDR Bad header format, unsupported size";
  70827. }
  70828. lineIndex += (line.length + 1);
  70829. return {
  70830. height: height,
  70831. width: width,
  70832. dataPosition: lineIndex
  70833. };
  70834. };
  70835. /**
  70836. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  70837. * This RGBE texture needs to store the information as a panorama.
  70838. *
  70839. * More information on this format are available here:
  70840. * https://en.wikipedia.org/wiki/RGBE_image_format
  70841. *
  70842. * @param buffer The binary file stored in an array buffer.
  70843. * @param size The expected size of the extracted cubemap.
  70844. * @return The Cube Map information.
  70845. */
  70846. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  70847. var uint8array = new Uint8Array(buffer);
  70848. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  70849. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  70850. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  70851. return cubeMapData;
  70852. };
  70853. /**
  70854. * Returns the pixels data extracted from an RGBE texture.
  70855. * This pixels will be stored left to right up to down in the R G B order in one array.
  70856. *
  70857. * More information on this format are available here:
  70858. * https://en.wikipedia.org/wiki/RGBE_image_format
  70859. *
  70860. * @param uint8array The binary file stored in an array buffer.
  70861. * @param hdrInfo The header information of the file.
  70862. * @return The pixels data in RGB right to left up to down order.
  70863. */
  70864. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  70865. // Keep for multi format supports.
  70866. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  70867. };
  70868. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  70869. var num_scanlines = hdrInfo.height;
  70870. var scanline_width = hdrInfo.width;
  70871. var a, b, c, d, count;
  70872. var dataIndex = hdrInfo.dataPosition;
  70873. var index = 0, endIndex = 0, i = 0;
  70874. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  70875. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  70876. // 3 channels of 4 bytes per pixel in float.
  70877. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  70878. var resultArray = new Float32Array(resultBuffer);
  70879. // read in each successive scanline
  70880. while (num_scanlines > 0) {
  70881. a = uint8array[dataIndex++];
  70882. b = uint8array[dataIndex++];
  70883. c = uint8array[dataIndex++];
  70884. d = uint8array[dataIndex++];
  70885. if (a != 2 || b != 2 || (c & 0x80)) {
  70886. // this file is not run length encoded
  70887. throw "HDR Bad header format, not RLE";
  70888. }
  70889. if (((c << 8) | d) != scanline_width) {
  70890. throw "HDR Bad header format, wrong scan line width";
  70891. }
  70892. index = 0;
  70893. // read each of the four channels for the scanline into the buffer
  70894. for (i = 0; i < 4; i++) {
  70895. endIndex = (i + 1) * scanline_width;
  70896. while (index < endIndex) {
  70897. a = uint8array[dataIndex++];
  70898. b = uint8array[dataIndex++];
  70899. if (a > 128) {
  70900. // a run of the same value
  70901. count = a - 128;
  70902. if ((count == 0) || (count > endIndex - index)) {
  70903. throw "HDR Bad Format, bad scanline data (run)";
  70904. }
  70905. while (count-- > 0) {
  70906. scanLineArray[index++] = b;
  70907. }
  70908. }
  70909. else {
  70910. // a non-run
  70911. count = a;
  70912. if ((count == 0) || (count > endIndex - index)) {
  70913. throw "HDR Bad Format, bad scanline data (non-run)";
  70914. }
  70915. scanLineArray[index++] = b;
  70916. if (--count > 0) {
  70917. for (var j = 0; j < count; j++) {
  70918. scanLineArray[index++] = uint8array[dataIndex++];
  70919. }
  70920. }
  70921. }
  70922. }
  70923. }
  70924. // now convert data from buffer into floats
  70925. for (i = 0; i < scanline_width; i++) {
  70926. a = scanLineArray[i];
  70927. b = scanLineArray[i + scanline_width];
  70928. c = scanLineArray[i + 2 * scanline_width];
  70929. d = scanLineArray[i + 3 * scanline_width];
  70930. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  70931. }
  70932. num_scanlines--;
  70933. }
  70934. return resultArray;
  70935. };
  70936. return HDRTools;
  70937. }());
  70938. BABYLON.HDRTools = HDRTools;
  70939. })(BABYLON || (BABYLON = {}));
  70940. //# sourceMappingURL=babylon.hdr.js.map
  70941. var BABYLON;
  70942. (function (BABYLON) {
  70943. /**
  70944. * This represents a texture coming from an HDR input.
  70945. *
  70946. * The only supported format is currently panorama picture stored in RGBE format.
  70947. * Example of such files can be found on HDRLib: http://hdrlib.com/
  70948. */
  70949. var HDRCubeTexture = /** @class */ (function (_super) {
  70950. __extends(HDRCubeTexture, _super);
  70951. /**
  70952. * Instantiates an HDRTexture from the following parameters.
  70953. *
  70954. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  70955. * @param scene The scene the texture will be used in
  70956. * @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.
  70957. * @param noMipmap Forces to not generate the mipmap if true
  70958. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  70959. * @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)
  70960. * @param usePMREMGenerator Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  70961. */
  70962. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  70963. if (noMipmap === void 0) { noMipmap = false; }
  70964. if (generateHarmonics === void 0) { generateHarmonics = true; }
  70965. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  70966. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  70967. if (onLoad === void 0) { onLoad = null; }
  70968. if (onError === void 0) { onError = null; }
  70969. var _this = _super.call(this, scene) || this;
  70970. _this._useInGammaSpace = false;
  70971. _this._generateHarmonics = true;
  70972. _this._isBABYLONPreprocessed = false;
  70973. _this._onLoad = null;
  70974. _this._onError = null;
  70975. /**
  70976. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  70977. */
  70978. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  70979. /**
  70980. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  70981. * This is usefull at run time to apply the good shader.
  70982. */
  70983. _this.isPMREM = false;
  70984. _this._isBlocking = true;
  70985. if (!url) {
  70986. return _this;
  70987. }
  70988. _this.name = url;
  70989. _this.url = url;
  70990. _this.hasAlpha = false;
  70991. _this.isCube = true;
  70992. _this._textureMatrix = BABYLON.Matrix.Identity();
  70993. _this._onLoad = onLoad;
  70994. _this._onError = onError;
  70995. _this.gammaSpace = false;
  70996. var caps = scene.getEngine().getCaps();
  70997. if (size) {
  70998. _this._isBABYLONPreprocessed = false;
  70999. _this._noMipmap = noMipmap;
  71000. _this._size = size;
  71001. _this._useInGammaSpace = useInGammaSpace;
  71002. _this._usePMREMGenerator = usePMREMGenerator &&
  71003. caps.textureLOD &&
  71004. caps.textureFloat &&
  71005. !_this._useInGammaSpace;
  71006. }
  71007. else {
  71008. _this._isBABYLONPreprocessed = true;
  71009. _this._noMipmap = false;
  71010. _this._useInGammaSpace = false;
  71011. _this._usePMREMGenerator = caps.textureLOD && caps.textureFloat &&
  71012. !_this._useInGammaSpace;
  71013. }
  71014. _this.isPMREM = _this._usePMREMGenerator;
  71015. _this._texture = _this._getFromCache(url, _this._noMipmap);
  71016. if (!_this._texture) {
  71017. if (!scene.useDelayedTextureLoading) {
  71018. _this.loadTexture();
  71019. }
  71020. else {
  71021. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  71022. }
  71023. }
  71024. return _this;
  71025. }
  71026. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  71027. /**
  71028. * Gets wether or not the texture is blocking during loading.
  71029. */
  71030. get: function () {
  71031. return this._isBlocking;
  71032. },
  71033. /**
  71034. * Sets wether or not the texture is blocking during loading.
  71035. */
  71036. set: function (value) {
  71037. this._isBlocking = value;
  71038. },
  71039. enumerable: true,
  71040. configurable: true
  71041. });
  71042. /**
  71043. * Occurs when the file is a preprocessed .babylon.hdr file.
  71044. */
  71045. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  71046. var _this = this;
  71047. var mipLevels = 0;
  71048. var floatArrayView = null;
  71049. var scene = this.getScene();
  71050. var mipmapGenerator = (!this._useInGammaSpace && scene && scene.getEngine().getCaps().textureFloat) ? function (data) {
  71051. var mips = new Array();
  71052. if (!floatArrayView) {
  71053. return mips;
  71054. }
  71055. var startIndex = 30;
  71056. for (var level = 0; level < mipLevels; level++) {
  71057. mips.push([]);
  71058. // Fill each pixel of the mip level.
  71059. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  71060. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  71061. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  71062. mips[level].push(faceData);
  71063. startIndex += faceSize;
  71064. }
  71065. }
  71066. return mips;
  71067. } : null;
  71068. var callback = function (buffer) {
  71069. var scene = _this.getScene();
  71070. if (!scene) {
  71071. return null;
  71072. }
  71073. // Create Native Array Views
  71074. var intArrayView = new Int32Array(buffer);
  71075. floatArrayView = new Float32Array(buffer);
  71076. // Fill header.
  71077. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  71078. _this._size = intArrayView[1]; // CubeMap max mip face size.
  71079. // Update Texture Information.
  71080. if (!_this._texture) {
  71081. return null;
  71082. }
  71083. _this._texture.updateSize(_this._size, _this._size);
  71084. // Fill polynomial information.
  71085. var sphericalPolynomial = new BABYLON.SphericalPolynomial();
  71086. sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  71087. sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  71088. sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  71089. sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  71090. sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  71091. sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  71092. sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  71093. sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  71094. sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  71095. _this.sphericalPolynomial = sphericalPolynomial;
  71096. // Fill pixel data.
  71097. mipLevels = intArrayView[29]; // Number of mip levels.
  71098. var startIndex = 30;
  71099. var data = [];
  71100. var faceSize = Math.pow(_this._size, 2) * 3;
  71101. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  71102. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  71103. startIndex += faceSize;
  71104. }
  71105. var results = [];
  71106. var byteArray = null;
  71107. // Push each faces.
  71108. for (var k = 0; k < 6; k++) {
  71109. var dataFace = null;
  71110. // To be deprecated.
  71111. if (version === 1) {
  71112. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y...
  71113. dataFace = data[j];
  71114. }
  71115. // If special cases.
  71116. if (!mipmapGenerator && dataFace) {
  71117. if (!scene.getEngine().getCaps().textureFloat) {
  71118. // 3 channels of 1 bytes per pixel in bytes.
  71119. var byteBuffer = new ArrayBuffer(faceSize);
  71120. byteArray = new Uint8Array(byteBuffer);
  71121. }
  71122. for (var i = 0; i < _this._size * _this._size; i++) {
  71123. // Put in gamma space if requested.
  71124. if (_this._useInGammaSpace) {
  71125. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  71126. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  71127. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  71128. }
  71129. // Convert to int texture for fallback.
  71130. if (byteArray) {
  71131. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  71132. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  71133. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  71134. // May use luminance instead if the result is not accurate.
  71135. var max = Math.max(Math.max(r, g), b);
  71136. if (max > 255) {
  71137. var scale = 255 / max;
  71138. r *= scale;
  71139. g *= scale;
  71140. b *= scale;
  71141. }
  71142. byteArray[(i * 3) + 0] = r;
  71143. byteArray[(i * 3) + 1] = g;
  71144. byteArray[(i * 3) + 2] = b;
  71145. }
  71146. }
  71147. }
  71148. // Fill the array accordingly.
  71149. if (byteArray) {
  71150. results.push(byteArray);
  71151. }
  71152. else {
  71153. results.push(dataFace);
  71154. }
  71155. }
  71156. return results;
  71157. };
  71158. if (scene) {
  71159. 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);
  71160. }
  71161. };
  71162. /**
  71163. * Occurs when the file is raw .hdr file.
  71164. */
  71165. HDRCubeTexture.prototype.loadHDRTexture = function () {
  71166. var _this = this;
  71167. var callback = function (buffer) {
  71168. var scene = _this.getScene();
  71169. if (!scene) {
  71170. return null;
  71171. }
  71172. // Extract the raw linear data.
  71173. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  71174. // Generate harmonics if needed.
  71175. if (_this._generateHarmonics) {
  71176. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  71177. _this.sphericalPolynomial = sphericalPolynomial;
  71178. }
  71179. var results = [];
  71180. var byteArray = null;
  71181. // Push each faces.
  71182. for (var j = 0; j < 6; j++) {
  71183. // Create uintarray fallback.
  71184. if (!scene.getEngine().getCaps().textureFloat) {
  71185. // 3 channels of 1 bytes per pixel in bytes.
  71186. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  71187. byteArray = new Uint8Array(byteBuffer);
  71188. }
  71189. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  71190. // If special cases.
  71191. if (_this._useInGammaSpace || byteArray) {
  71192. for (var i = 0; i < _this._size * _this._size; i++) {
  71193. // Put in gamma space if requested.
  71194. if (_this._useInGammaSpace) {
  71195. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  71196. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  71197. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  71198. }
  71199. // Convert to int texture for fallback.
  71200. if (byteArray) {
  71201. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  71202. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  71203. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  71204. // May use luminance instead if the result is not accurate.
  71205. var max = Math.max(Math.max(r, g), b);
  71206. if (max > 255) {
  71207. var scale = 255 / max;
  71208. r *= scale;
  71209. g *= scale;
  71210. b *= scale;
  71211. }
  71212. byteArray[(i * 3) + 0] = r;
  71213. byteArray[(i * 3) + 1] = g;
  71214. byteArray[(i * 3) + 2] = b;
  71215. }
  71216. }
  71217. }
  71218. if (byteArray) {
  71219. results.push(byteArray);
  71220. }
  71221. else {
  71222. results.push(dataFace);
  71223. }
  71224. }
  71225. return results;
  71226. };
  71227. var mipmapGenerator = null;
  71228. // TODO. Implement In code PMREM Generator following the LYS toolset generation.
  71229. // if (!this._noMipmap &&
  71230. // this._usePMREMGenerator) {
  71231. // mipmapGenerator = (data: ArrayBufferView[]) => {
  71232. // // Custom setup of the generator matching with the PBR shader values.
  71233. // var generator = new BABYLON.PMREMGenerator(data,
  71234. // this._size,
  71235. // this._size,
  71236. // 0,
  71237. // 3,
  71238. // this.getScene().getEngine().getCaps().textureFloat,
  71239. // 2048,
  71240. // 0.25,
  71241. // false,
  71242. // true);
  71243. // return generator.filterCubeMap();
  71244. // };
  71245. // }
  71246. var scene = this.getScene();
  71247. if (scene) {
  71248. 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);
  71249. }
  71250. };
  71251. /**
  71252. * Starts the loading process of the texture.
  71253. */
  71254. HDRCubeTexture.prototype.loadTexture = function () {
  71255. if (this._isBABYLONPreprocessed) {
  71256. this.loadBabylonTexture();
  71257. }
  71258. else {
  71259. this.loadHDRTexture();
  71260. }
  71261. };
  71262. HDRCubeTexture.prototype.clone = function () {
  71263. var scene = this.getScene();
  71264. if (!scene) {
  71265. return this;
  71266. }
  71267. var size = (this._isBABYLONPreprocessed ? null : this._size);
  71268. var newTexture = new HDRCubeTexture(this.url, scene, size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  71269. // Base texture
  71270. newTexture.level = this.level;
  71271. newTexture.wrapU = this.wrapU;
  71272. newTexture.wrapV = this.wrapV;
  71273. newTexture.coordinatesIndex = this.coordinatesIndex;
  71274. newTexture.coordinatesMode = this.coordinatesMode;
  71275. return newTexture;
  71276. };
  71277. // Methods
  71278. HDRCubeTexture.prototype.delayLoad = function () {
  71279. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  71280. return;
  71281. }
  71282. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  71283. this._texture = this._getFromCache(this.url, this._noMipmap);
  71284. if (!this._texture) {
  71285. this.loadTexture();
  71286. }
  71287. };
  71288. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  71289. return this._textureMatrix;
  71290. };
  71291. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  71292. this._textureMatrix = value;
  71293. };
  71294. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  71295. var texture = null;
  71296. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  71297. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  71298. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  71299. texture.name = parsedTexture.name;
  71300. texture.hasAlpha = parsedTexture.hasAlpha;
  71301. texture.level = parsedTexture.level;
  71302. texture.coordinatesMode = parsedTexture.coordinatesMode;
  71303. texture.isBlocking = parsedTexture.isBlocking;
  71304. }
  71305. return texture;
  71306. };
  71307. HDRCubeTexture.prototype.serialize = function () {
  71308. if (!this.name) {
  71309. return null;
  71310. }
  71311. var serializationObject = {};
  71312. serializationObject.name = this.name;
  71313. serializationObject.hasAlpha = this.hasAlpha;
  71314. serializationObject.isCube = true;
  71315. serializationObject.level = this.level;
  71316. serializationObject.size = this._size;
  71317. serializationObject.coordinatesMode = this.coordinatesMode;
  71318. serializationObject.useInGammaSpace = this._useInGammaSpace;
  71319. serializationObject.generateHarmonics = this._generateHarmonics;
  71320. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  71321. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  71322. serializationObject.customType = "BABYLON.HDRCubeTexture";
  71323. serializationObject.noMipmap = this._noMipmap;
  71324. serializationObject.isBlocking = this._isBlocking;
  71325. return serializationObject;
  71326. };
  71327. /**
  71328. * Saves as a file the data contained in the texture in a binary format.
  71329. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  71330. * as the spherical used in the lighting.
  71331. * @param url The HDR file url.
  71332. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  71333. * @param onError Method called if any error happens during download.
  71334. * @return The packed binary data.
  71335. */
  71336. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  71337. if (onError === void 0) { onError = null; }
  71338. var callback = function (buffer) {
  71339. var data = new Blob([buffer], { type: 'application/octet-stream' });
  71340. // Returns a URL you can use as a href.
  71341. var objUrl = window.URL.createObjectURL(data);
  71342. // Simulates a link to it and click to dowload.
  71343. var a = document.createElement("a");
  71344. document.body.appendChild(a);
  71345. a.style.display = "none";
  71346. a.href = objUrl;
  71347. a.download = "envmap.babylon.hdr";
  71348. a.click();
  71349. };
  71350. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  71351. };
  71352. /**
  71353. * Serializes the data contained in the texture in a binary format.
  71354. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  71355. * as the spherical used in the lighting.
  71356. * @param url The HDR file url.
  71357. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  71358. * @param onError Method called if any error happens during download.
  71359. * @return The packed binary data.
  71360. */
  71361. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  71362. if (onError === void 0) { onError = null; }
  71363. // Needs the url tho create the texture.
  71364. if (!url) {
  71365. return;
  71366. }
  71367. // Check Power of two size.
  71368. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  71369. return;
  71370. }
  71371. // Coming Back in 3.x.
  71372. BABYLON.Tools.Error("Generation of Babylon HDR is coming back in 3.2.");
  71373. };
  71374. HDRCubeTexture._facesMapping = [
  71375. "right",
  71376. "left",
  71377. "up",
  71378. "down",
  71379. "front",
  71380. "back"
  71381. ];
  71382. return HDRCubeTexture;
  71383. }(BABYLON.BaseTexture));
  71384. BABYLON.HDRCubeTexture = HDRCubeTexture;
  71385. })(BABYLON || (BABYLON = {}));
  71386. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  71387. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  71388. // Huge respect for a such great lib.
  71389. // Earcut license:
  71390. // Copyright (c) 2016, Mapbox
  71391. //
  71392. // Permission to use, copy, modify, and/or distribute this software for any purpose
  71393. // with or without fee is hereby granted, provided that the above copyright notice
  71394. // and this permission notice appear in all copies.
  71395. //
  71396. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  71397. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  71398. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  71399. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  71400. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  71401. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  71402. // THIS SOFTWARE.
  71403. var Earcut;
  71404. (function (Earcut) {
  71405. /**
  71406. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  71407. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  71408. * @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).
  71409. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  71410. */
  71411. function earcut(data, holeIndices, dim) {
  71412. dim = dim || 2;
  71413. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = new Array();
  71414. if (!outerNode)
  71415. return triangles;
  71416. var minX = 0, minY = 0, maxX, maxY, x, y, size = 0;
  71417. if (hasHoles)
  71418. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  71419. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  71420. if (data.length > 80 * dim) {
  71421. minX = maxX = data[0];
  71422. minY = maxY = data[1];
  71423. for (var i = dim; i < outerLen; i += dim) {
  71424. x = data[i];
  71425. y = data[i + 1];
  71426. if (x < minX)
  71427. minX = x;
  71428. if (y < minY)
  71429. minY = y;
  71430. if (x > maxX)
  71431. maxX = x;
  71432. if (y > maxY)
  71433. maxY = y;
  71434. }
  71435. // minX, minY and size are later used to transform coords into integers for z-order calculation
  71436. size = Math.max(maxX - minX, maxY - minY);
  71437. }
  71438. earcutLinked(outerNode, triangles, dim, minX, minY, size, 0);
  71439. return triangles;
  71440. }
  71441. Earcut.earcut = earcut;
  71442. var Node = /** @class */ (function () {
  71443. function Node(i, x, y) {
  71444. this.i = i;
  71445. this.x = x;
  71446. this.y = y;
  71447. this.prev = null;
  71448. this.next = null;
  71449. this.z = null;
  71450. this.prevZ = null;
  71451. this.nextZ = null;
  71452. this.steiner = false;
  71453. }
  71454. return Node;
  71455. }());
  71456. // create a circular doubly linked list from polygon points in the specified winding order
  71457. function linkedList(data, start, end, dim, clockwise) {
  71458. var i, last = null;
  71459. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  71460. for (i = start; i < end; i += dim)
  71461. last = insertNode(i, data[i], data[i + 1], last);
  71462. }
  71463. else {
  71464. for (i = end - dim; i >= start; i -= dim)
  71465. last = insertNode(i, data[i], data[i + 1], last);
  71466. }
  71467. if (last && equals(last, last.next)) {
  71468. removeNode(last);
  71469. last = last.next;
  71470. }
  71471. return last;
  71472. }
  71473. // eliminate colinear or duplicate points
  71474. function filterPoints(start, end) {
  71475. if (!start)
  71476. return start;
  71477. if (!end)
  71478. end = start;
  71479. var p = start, again;
  71480. do {
  71481. again = false;
  71482. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  71483. removeNode(p);
  71484. p = end = p.prev;
  71485. if (p === p.next)
  71486. return undefined;
  71487. again = true;
  71488. }
  71489. else {
  71490. p = p.next;
  71491. }
  71492. } while (again || p !== end);
  71493. return end;
  71494. }
  71495. // main ear slicing loop which triangulates a polygon (given as a linked list)
  71496. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  71497. if (!ear)
  71498. return;
  71499. // interlink polygon nodes in z-order
  71500. if (!pass && size)
  71501. indexCurve(ear, minX, minY, size);
  71502. var stop = ear, prev, next;
  71503. // iterate through ears, slicing them one by one
  71504. while (ear.prev !== ear.next) {
  71505. prev = ear.prev;
  71506. next = ear.next;
  71507. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  71508. // cut off the triangle
  71509. triangles.push(prev.i / dim);
  71510. triangles.push(ear.i / dim);
  71511. triangles.push(next.i / dim);
  71512. removeNode(ear);
  71513. // skipping the next vertice leads to less sliver triangles
  71514. ear = next.next;
  71515. stop = next.next;
  71516. continue;
  71517. }
  71518. ear = next;
  71519. // if we looped through the whole remaining polygon and can't find any more ears
  71520. if (ear === stop) {
  71521. // try filtering points and slicing again
  71522. if (!pass) {
  71523. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  71524. // if this didn't work, try curing all small self-intersections locally
  71525. }
  71526. else if (pass === 1) {
  71527. ear = cureLocalIntersections(ear, triangles, dim);
  71528. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  71529. // as a last resort, try splitting the remaining polygon into two
  71530. }
  71531. else if (pass === 2) {
  71532. splitEarcut(ear, triangles, dim, minX, minY, size);
  71533. }
  71534. break;
  71535. }
  71536. }
  71537. }
  71538. // check whether a polygon node forms a valid ear with adjacent nodes
  71539. function isEar(ear) {
  71540. var a = ear.prev, b = ear, c = ear.next;
  71541. if (area(a, b, c) >= 0)
  71542. return false; // reflex, can't be an ear
  71543. // now make sure we don't have other points inside the potential ear
  71544. var p = ear.next.next;
  71545. while (p !== ear.prev) {
  71546. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  71547. area(p.prev, p, p.next) >= 0)
  71548. return false;
  71549. p = p.next;
  71550. }
  71551. return true;
  71552. }
  71553. function isEarHashed(ear, minX, minY, size) {
  71554. var a = ear.prev, b = ear, c = ear.next;
  71555. if (area(a, b, c) >= 0)
  71556. return false; // reflex, can't be an ear
  71557. // triangle bbox; min & max are calculated like this for speed
  71558. 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);
  71559. // z-order range for the current triangle bbox;
  71560. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  71561. // first look for points inside the triangle in increasing z-order
  71562. var p = ear.nextZ;
  71563. while (p && p.z <= maxZ) {
  71564. if (p !== ear.prev &&
  71565. p !== ear.next &&
  71566. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  71567. area(p.prev, p, p.next) >= 0)
  71568. return false;
  71569. p = p.nextZ;
  71570. }
  71571. // then look for points in decreasing z-order
  71572. p = ear.prevZ;
  71573. while (p && p.z >= minZ) {
  71574. if (p !== ear.prev &&
  71575. p !== ear.next &&
  71576. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  71577. area(p.prev, p, p.next) >= 0)
  71578. return false;
  71579. p = p.prevZ;
  71580. }
  71581. return true;
  71582. }
  71583. // go through all polygon nodes and cure small local self-intersections
  71584. function cureLocalIntersections(start, triangles, dim) {
  71585. var p = start;
  71586. do {
  71587. var a = p.prev, b = p.next.next;
  71588. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  71589. triangles.push(a.i / dim);
  71590. triangles.push(p.i / dim);
  71591. triangles.push(b.i / dim);
  71592. // remove two nodes involved
  71593. removeNode(p);
  71594. removeNode(p.next);
  71595. p = start = b;
  71596. }
  71597. p = p.next;
  71598. } while (p !== start);
  71599. return p;
  71600. }
  71601. // try splitting polygon into two and triangulate them independently
  71602. function splitEarcut(start, triangles, dim, minX, minY, size) {
  71603. // look for a valid diagonal that divides the polygon into two
  71604. var a = start;
  71605. do {
  71606. var b = a.next.next;
  71607. while (b !== a.prev) {
  71608. if (a.i !== b.i && isValidDiagonal(a, b)) {
  71609. // split the polygon in two by the diagonal
  71610. var c = splitPolygon(a, b);
  71611. // filter colinear points around the cuts
  71612. a = filterPoints(a, a.next);
  71613. c = filterPoints(c, c.next);
  71614. // run earcut on each half
  71615. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  71616. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  71617. return;
  71618. }
  71619. b = b.next;
  71620. }
  71621. a = a.next;
  71622. } while (a !== start);
  71623. }
  71624. // link every hole into the outer loop, producing a single-ring polygon without holes
  71625. function eliminateHoles(data, holeIndices, outerNode, dim) {
  71626. var queue = [], i, len, start, end, list;
  71627. for (i = 0, len = holeIndices.length; i < len; i++) {
  71628. start = holeIndices[i] * dim;
  71629. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  71630. list = linkedList(data, start, end, dim, false);
  71631. if (list === list.next)
  71632. list.steiner = true;
  71633. queue.push(getLeftmost(list));
  71634. }
  71635. queue.sort(compareX);
  71636. // process holes from left to right
  71637. for (i = 0; i < queue.length; i++) {
  71638. eliminateHole(queue[i], outerNode);
  71639. outerNode = filterPoints(outerNode, outerNode.next);
  71640. }
  71641. return outerNode;
  71642. }
  71643. function compareX(a, b) {
  71644. return a.x - b.x;
  71645. }
  71646. // find a bridge between vertices that connects hole with an outer ring and and link it
  71647. function eliminateHole(hole, outerNode) {
  71648. outerNode = findHoleBridge(hole, outerNode);
  71649. if (outerNode) {
  71650. var b = splitPolygon(outerNode, hole);
  71651. filterPoints(b, b.next);
  71652. }
  71653. }
  71654. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  71655. function findHoleBridge(hole, outerNode) {
  71656. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  71657. // find a segment intersected by a ray from the hole's leftmost point to the left;
  71658. // segment's endpoint with lesser x will be potential connection point
  71659. do {
  71660. if (hy <= p.y && hy >= p.next.y) {
  71661. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  71662. if (x <= hx && x > qx) {
  71663. qx = x;
  71664. if (x === hx) {
  71665. if (hy === p.y)
  71666. return p;
  71667. if (hy === p.next.y)
  71668. return p.next;
  71669. }
  71670. m = p.x < p.next.x ? p : p.next;
  71671. }
  71672. }
  71673. p = p.next;
  71674. } while (p !== outerNode);
  71675. if (!m)
  71676. return null;
  71677. if (hx === qx)
  71678. return m.prev; // hole touches outer segment; pick lower endpoint
  71679. // look for points inside the triangle of hole point, segment intersection and endpoint;
  71680. // if there are no points found, we have a valid connection;
  71681. // otherwise choose the point of the minimum angle with the ray as connection point
  71682. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  71683. p = m.next;
  71684. while (p !== stop) {
  71685. if (hx >= p.x &&
  71686. p.x >= mx &&
  71687. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  71688. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  71689. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  71690. m = p;
  71691. tanMin = tan;
  71692. }
  71693. }
  71694. p = p.next;
  71695. }
  71696. return m;
  71697. }
  71698. // interlink polygon nodes in z-order
  71699. function indexCurve(start, minX, minY, size) {
  71700. var p = start;
  71701. do {
  71702. if (p.z === null)
  71703. p.z = zOrder(p.x, p.y, minX, minY, size);
  71704. p.prevZ = p.prev;
  71705. p.nextZ = p.next;
  71706. p = p.next;
  71707. } while (p !== start);
  71708. p.prevZ.nextZ = null;
  71709. p.prevZ = null;
  71710. sortLinked(p);
  71711. }
  71712. // Simon Tatham's linked list merge sort algorithm
  71713. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  71714. function sortLinked(list) {
  71715. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  71716. do {
  71717. p = list;
  71718. list = null;
  71719. tail = null;
  71720. numMerges = 0;
  71721. while (p) {
  71722. numMerges++;
  71723. q = p;
  71724. pSize = 0;
  71725. for (i = 0; i < inSize; i++) {
  71726. pSize++;
  71727. q = q.nextZ;
  71728. if (!q)
  71729. break;
  71730. }
  71731. qSize = inSize;
  71732. while (pSize > 0 || (qSize > 0 && q)) {
  71733. if (pSize === 0) {
  71734. e = q;
  71735. q = q.nextZ;
  71736. qSize--;
  71737. }
  71738. else if (qSize === 0 || !q) {
  71739. e = p;
  71740. p = p.nextZ;
  71741. pSize--;
  71742. }
  71743. else if (p.z <= q.z) {
  71744. e = p;
  71745. p = p.nextZ;
  71746. pSize--;
  71747. }
  71748. else {
  71749. e = q;
  71750. q = q.nextZ;
  71751. qSize--;
  71752. }
  71753. if (tail)
  71754. tail.nextZ = e;
  71755. else
  71756. list = e;
  71757. e.prevZ = tail;
  71758. tail = e;
  71759. }
  71760. p = q;
  71761. }
  71762. tail.nextZ = null;
  71763. inSize *= 2;
  71764. } while (numMerges > 1);
  71765. return list;
  71766. }
  71767. // z-order of a point given coords and size of the data bounding box
  71768. function zOrder(x, y, minX, minY, size) {
  71769. // coords are transformed into non-negative 15-bit integer range
  71770. x = 32767 * (x - minX) / size;
  71771. y = 32767 * (y - minY) / size;
  71772. x = (x | (x << 8)) & 0x00FF00FF;
  71773. x = (x | (x << 4)) & 0x0F0F0F0F;
  71774. x = (x | (x << 2)) & 0x33333333;
  71775. x = (x | (x << 1)) & 0x55555555;
  71776. y = (y | (y << 8)) & 0x00FF00FF;
  71777. y = (y | (y << 4)) & 0x0F0F0F0F;
  71778. y = (y | (y << 2)) & 0x33333333;
  71779. y = (y | (y << 1)) & 0x55555555;
  71780. return x | (y << 1);
  71781. }
  71782. // find the leftmost node of a polygon ring
  71783. function getLeftmost(start) {
  71784. var p = start, leftmost = start;
  71785. do {
  71786. if (p.x < leftmost.x)
  71787. leftmost = p;
  71788. p = p.next;
  71789. } while (p !== start);
  71790. return leftmost;
  71791. }
  71792. // check if a point lies within a convex triangle
  71793. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  71794. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  71795. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  71796. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  71797. }
  71798. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  71799. function isValidDiagonal(a, b) {
  71800. return a.next.i !== b.i &&
  71801. a.prev.i !== b.i &&
  71802. !intersectsPolygon(a, b) &&
  71803. locallyInside(a, b) &&
  71804. locallyInside(b, a) &&
  71805. middleInside(a, b);
  71806. }
  71807. // signed area of a triangle
  71808. function area(p, q, r) {
  71809. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  71810. }
  71811. // check if two points are equal
  71812. function equals(p1, p2) {
  71813. return p1.x === p2.x && p1.y === p2.y;
  71814. }
  71815. // check if two segments intersect
  71816. function intersects(p1, q1, p2, q2) {
  71817. if ((equals(p1, q1) && equals(p2, q2)) ||
  71818. (equals(p1, q2) && equals(p2, q1)))
  71819. return true;
  71820. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  71821. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  71822. }
  71823. // check if a polygon diagonal intersects any polygon segments
  71824. function intersectsPolygon(a, b) {
  71825. var p = a;
  71826. do {
  71827. if (p.i !== a.i &&
  71828. p.next.i !== a.i &&
  71829. p.i !== b.i &&
  71830. p.next.i !== b.i &&
  71831. intersects(p, p.next, a, b))
  71832. return true;
  71833. p = p.next;
  71834. } while (p !== a);
  71835. return false;
  71836. }
  71837. // check if a polygon diagonal is locally inside the polygon
  71838. function locallyInside(a, b) {
  71839. return area(a.prev, a, a.next) < 0
  71840. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  71841. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  71842. }
  71843. // check if the middle point of a polygon diagonal is inside the polygon
  71844. function middleInside(a, b) {
  71845. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  71846. do {
  71847. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  71848. inside = !inside;
  71849. p = p.next;
  71850. } while (p !== a);
  71851. return inside;
  71852. }
  71853. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  71854. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  71855. function splitPolygon(a, b) {
  71856. 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;
  71857. a.next = b;
  71858. b.prev = a;
  71859. a2.next = an;
  71860. an.prev = a2;
  71861. b2.next = a2;
  71862. a2.prev = b2;
  71863. bp.next = b2;
  71864. b2.prev = bp;
  71865. return b2;
  71866. }
  71867. // create a node and optionally link it with previous one (in a circular doubly linked list)
  71868. function insertNode(i, x, y, last) {
  71869. var p = new Node(i, x, y);
  71870. if (!last) {
  71871. p.prev = p;
  71872. p.next = p;
  71873. }
  71874. else {
  71875. p.next = last.next;
  71876. p.prev = last;
  71877. last.next.prev = p;
  71878. last.next = p;
  71879. }
  71880. return p;
  71881. }
  71882. function removeNode(p) {
  71883. p.next.prev = p.prev;
  71884. p.prev.next = p.next;
  71885. if (p.prevZ)
  71886. p.prevZ.nextZ = p.nextZ;
  71887. if (p.nextZ)
  71888. p.nextZ.prevZ = p.prevZ;
  71889. }
  71890. /**
  71891. * return a percentage difference between the polygon area and its triangulation area;
  71892. * used to verify correctness of triangulation
  71893. */
  71894. function deviation(data, holeIndices, dim, triangles) {
  71895. var hasHoles = holeIndices && holeIndices.length;
  71896. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  71897. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  71898. if (hasHoles) {
  71899. for (var i = 0, len = holeIndices.length; i < len; i++) {
  71900. var start = holeIndices[i] * dim;
  71901. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  71902. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  71903. }
  71904. }
  71905. var trianglesArea = 0;
  71906. for (i = 0; i < triangles.length; i += 3) {
  71907. var a = triangles[i] * dim;
  71908. var b = triangles[i + 1] * dim;
  71909. var c = triangles[i + 2] * dim;
  71910. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  71911. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  71912. }
  71913. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  71914. }
  71915. Earcut.deviation = deviation;
  71916. ;
  71917. function signedArea(data, start, end, dim) {
  71918. var sum = 0;
  71919. for (var i = start, j = end - dim; i < end; i += dim) {
  71920. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  71921. j = i;
  71922. }
  71923. return sum;
  71924. }
  71925. /**
  71926. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  71927. */
  71928. function flatten(data) {
  71929. var dim = data[0][0].length, result = { vertices: new Array(), holes: new Array(), dimensions: dim }, holeIndex = 0;
  71930. for (var i = 0; i < data.length; i++) {
  71931. for (var j = 0; j < data[i].length; j++) {
  71932. for (var d = 0; d < dim; d++)
  71933. result.vertices.push(data[i][j][d]);
  71934. }
  71935. if (i > 0) {
  71936. holeIndex += data[i - 1].length;
  71937. result.holes.push(holeIndex);
  71938. }
  71939. }
  71940. return result;
  71941. }
  71942. Earcut.flatten = flatten;
  71943. ;
  71944. })(Earcut || (Earcut = {}));
  71945. //# sourceMappingURL=babylon.earcut.js.map
  71946. var BABYLON;
  71947. (function (BABYLON) {
  71948. var IndexedVector2 = /** @class */ (function (_super) {
  71949. __extends(IndexedVector2, _super);
  71950. function IndexedVector2(original, index) {
  71951. var _this = _super.call(this, original.x, original.y) || this;
  71952. _this.index = index;
  71953. return _this;
  71954. }
  71955. return IndexedVector2;
  71956. }(BABYLON.Vector2));
  71957. var PolygonPoints = /** @class */ (function () {
  71958. function PolygonPoints() {
  71959. this.elements = new Array();
  71960. }
  71961. PolygonPoints.prototype.add = function (originalPoints) {
  71962. var _this = this;
  71963. var result = new Array();
  71964. originalPoints.forEach(function (point) {
  71965. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  71966. var newPoint = new IndexedVector2(point, _this.elements.length);
  71967. result.push(newPoint);
  71968. _this.elements.push(newPoint);
  71969. }
  71970. });
  71971. return result;
  71972. };
  71973. PolygonPoints.prototype.computeBounds = function () {
  71974. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  71975. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  71976. this.elements.forEach(function (point) {
  71977. // x
  71978. if (point.x < lmin.x) {
  71979. lmin.x = point.x;
  71980. }
  71981. else if (point.x > lmax.x) {
  71982. lmax.x = point.x;
  71983. }
  71984. // y
  71985. if (point.y < lmin.y) {
  71986. lmin.y = point.y;
  71987. }
  71988. else if (point.y > lmax.y) {
  71989. lmax.y = point.y;
  71990. }
  71991. });
  71992. return {
  71993. min: lmin,
  71994. max: lmax,
  71995. width: lmax.x - lmin.x,
  71996. height: lmax.y - lmin.y
  71997. };
  71998. };
  71999. return PolygonPoints;
  72000. }());
  72001. var Polygon = /** @class */ (function () {
  72002. function Polygon() {
  72003. }
  72004. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  72005. return [
  72006. new BABYLON.Vector2(xmin, ymin),
  72007. new BABYLON.Vector2(xmax, ymin),
  72008. new BABYLON.Vector2(xmax, ymax),
  72009. new BABYLON.Vector2(xmin, ymax)
  72010. ];
  72011. };
  72012. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  72013. if (cx === void 0) { cx = 0; }
  72014. if (cy === void 0) { cy = 0; }
  72015. if (numberOfSides === void 0) { numberOfSides = 32; }
  72016. var result = new Array();
  72017. var angle = 0;
  72018. var increment = (Math.PI * 2) / numberOfSides;
  72019. for (var i = 0; i < numberOfSides; i++) {
  72020. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  72021. angle -= increment;
  72022. }
  72023. return result;
  72024. };
  72025. Polygon.Parse = function (input) {
  72026. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  72027. var i, result = [];
  72028. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  72029. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  72030. }
  72031. return result;
  72032. };
  72033. Polygon.StartingAt = function (x, y) {
  72034. return BABYLON.Path2.StartingAt(x, y);
  72035. };
  72036. return Polygon;
  72037. }());
  72038. BABYLON.Polygon = Polygon;
  72039. var PolygonMeshBuilder = /** @class */ (function () {
  72040. function PolygonMeshBuilder(name, contours, scene) {
  72041. this._points = new PolygonPoints();
  72042. this._outlinepoints = new PolygonPoints();
  72043. this._holes = new Array();
  72044. this._epoints = new Array();
  72045. this._eholes = new Array();
  72046. this._name = name;
  72047. this._scene = scene;
  72048. var points;
  72049. if (contours instanceof BABYLON.Path2) {
  72050. points = contours.getPoints();
  72051. }
  72052. else {
  72053. points = contours;
  72054. }
  72055. this._addToepoint(points);
  72056. this._points.add(points);
  72057. this._outlinepoints.add(points);
  72058. }
  72059. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  72060. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  72061. var p = points_1[_i];
  72062. this._epoints.push(p.x, p.y);
  72063. }
  72064. };
  72065. PolygonMeshBuilder.prototype.addHole = function (hole) {
  72066. this._points.add(hole);
  72067. var holepoints = new PolygonPoints();
  72068. holepoints.add(hole);
  72069. this._holes.push(holepoints);
  72070. this._eholes.push(this._epoints.length / 2);
  72071. this._addToepoint(hole);
  72072. return this;
  72073. };
  72074. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  72075. var _this = this;
  72076. if (updatable === void 0) { updatable = false; }
  72077. if (depth === void 0) { depth = 0; }
  72078. var result = new BABYLON.Mesh(this._name, this._scene);
  72079. var normals = new Array();
  72080. var positions = new Array();
  72081. var uvs = new Array();
  72082. var bounds = this._points.computeBounds();
  72083. this._points.elements.forEach(function (p) {
  72084. normals.push(0, 1.0, 0);
  72085. positions.push(p.x, 0, p.y);
  72086. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  72087. });
  72088. var indices = new Array();
  72089. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  72090. for (var i = 0; i < res.length; i++) {
  72091. indices.push(res[i]);
  72092. }
  72093. if (depth > 0) {
  72094. var positionscount = (positions.length / 3); //get the current pointcount
  72095. this._points.elements.forEach(function (p) {
  72096. normals.push(0, -1.0, 0);
  72097. positions.push(p.x, -depth, p.y);
  72098. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  72099. });
  72100. var totalCount = indices.length;
  72101. for (var i = 0; i < totalCount; i += 3) {
  72102. var i0 = indices[i + 0];
  72103. var i1 = indices[i + 1];
  72104. var i2 = indices[i + 2];
  72105. indices.push(i2 + positionscount);
  72106. indices.push(i1 + positionscount);
  72107. indices.push(i0 + positionscount);
  72108. }
  72109. //Add the sides
  72110. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  72111. this._holes.forEach(function (hole) {
  72112. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  72113. });
  72114. }
  72115. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  72116. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  72117. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  72118. result.setIndices(indices);
  72119. return result;
  72120. };
  72121. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  72122. var StartIndex = positions.length / 3;
  72123. var ulength = 0;
  72124. for (var i = 0; i < points.elements.length; i++) {
  72125. var p = points.elements[i];
  72126. var p1;
  72127. if ((i + 1) > points.elements.length - 1) {
  72128. p1 = points.elements[0];
  72129. }
  72130. else {
  72131. p1 = points.elements[i + 1];
  72132. }
  72133. positions.push(p.x, 0, p.y);
  72134. positions.push(p.x, -depth, p.y);
  72135. positions.push(p1.x, 0, p1.y);
  72136. positions.push(p1.x, -depth, p1.y);
  72137. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  72138. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  72139. var v3 = v2.subtract(v1);
  72140. var v4 = new BABYLON.Vector3(0, 1, 0);
  72141. var vn = BABYLON.Vector3.Cross(v3, v4);
  72142. vn = vn.normalize();
  72143. uvs.push(ulength / bounds.width, 0);
  72144. uvs.push(ulength / bounds.width, 1);
  72145. ulength += v3.length();
  72146. uvs.push((ulength / bounds.width), 0);
  72147. uvs.push((ulength / bounds.width), 1);
  72148. if (!flip) {
  72149. normals.push(-vn.x, -vn.y, -vn.z);
  72150. normals.push(-vn.x, -vn.y, -vn.z);
  72151. normals.push(-vn.x, -vn.y, -vn.z);
  72152. normals.push(-vn.x, -vn.y, -vn.z);
  72153. indices.push(StartIndex);
  72154. indices.push(StartIndex + 1);
  72155. indices.push(StartIndex + 2);
  72156. indices.push(StartIndex + 1);
  72157. indices.push(StartIndex + 3);
  72158. indices.push(StartIndex + 2);
  72159. }
  72160. else {
  72161. normals.push(vn.x, vn.y, vn.z);
  72162. normals.push(vn.x, vn.y, vn.z);
  72163. normals.push(vn.x, vn.y, vn.z);
  72164. normals.push(vn.x, vn.y, vn.z);
  72165. indices.push(StartIndex);
  72166. indices.push(StartIndex + 2);
  72167. indices.push(StartIndex + 1);
  72168. indices.push(StartIndex + 1);
  72169. indices.push(StartIndex + 2);
  72170. indices.push(StartIndex + 3);
  72171. }
  72172. StartIndex += 4;
  72173. }
  72174. ;
  72175. };
  72176. return PolygonMeshBuilder;
  72177. }());
  72178. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  72179. })(BABYLON || (BABYLON = {}));
  72180. //# sourceMappingURL=babylon.polygonMesh.js.map
  72181. var BABYLON;
  72182. (function (BABYLON) {
  72183. // Unique ID when we import meshes from Babylon to CSG
  72184. var currentCSGMeshId = 0;
  72185. // # class Vertex
  72186. // Represents a vertex of a polygon. Use your own vertex class instead of this
  72187. // one to provide additional features like texture coordinates and vertex
  72188. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  72189. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  72190. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  72191. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  72192. // is not used anywhere else.
  72193. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  72194. var Vertex = /** @class */ (function () {
  72195. function Vertex(pos, normal, uv) {
  72196. this.pos = pos;
  72197. this.normal = normal;
  72198. this.uv = uv;
  72199. }
  72200. Vertex.prototype.clone = function () {
  72201. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  72202. };
  72203. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  72204. // orientation of a polygon is flipped.
  72205. Vertex.prototype.flip = function () {
  72206. this.normal = this.normal.scale(-1);
  72207. };
  72208. // Create a new vertex between this vertex and `other` by linearly
  72209. // interpolating all properties using a parameter of `t`. Subclasses should
  72210. // override this to interpolate additional properties.
  72211. Vertex.prototype.interpolate = function (other, t) {
  72212. 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));
  72213. };
  72214. return Vertex;
  72215. }());
  72216. // # class Plane
  72217. // Represents a plane in 3D space.
  72218. var Plane = /** @class */ (function () {
  72219. function Plane(normal, w) {
  72220. this.normal = normal;
  72221. this.w = w;
  72222. }
  72223. Plane.FromPoints = function (a, b, c) {
  72224. var v0 = c.subtract(a);
  72225. var v1 = b.subtract(a);
  72226. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  72227. return null;
  72228. }
  72229. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  72230. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  72231. };
  72232. Plane.prototype.clone = function () {
  72233. return new Plane(this.normal.clone(), this.w);
  72234. };
  72235. Plane.prototype.flip = function () {
  72236. this.normal.scaleInPlace(-1);
  72237. this.w = -this.w;
  72238. };
  72239. // Split `polygon` by this plane if needed, then put the polygon or polygon
  72240. // fragments in the appropriate lists. Coplanar polygons go into either
  72241. // `coplanarFront` or `coplanarBack` depending on their orientation with
  72242. // respect to this plane. Polygons in front or in back of this plane go into
  72243. // either `front` or `back`.
  72244. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  72245. var COPLANAR = 0;
  72246. var FRONT = 1;
  72247. var BACK = 2;
  72248. var SPANNING = 3;
  72249. // Classify each point as well as the entire polygon into one of the above
  72250. // four classes.
  72251. var polygonType = 0;
  72252. var types = [];
  72253. var i;
  72254. var t;
  72255. for (i = 0; i < polygon.vertices.length; i++) {
  72256. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  72257. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  72258. polygonType |= type;
  72259. types.push(type);
  72260. }
  72261. // Put the polygon in the correct list, splitting it when necessary.
  72262. switch (polygonType) {
  72263. case COPLANAR:
  72264. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  72265. break;
  72266. case FRONT:
  72267. front.push(polygon);
  72268. break;
  72269. case BACK:
  72270. back.push(polygon);
  72271. break;
  72272. case SPANNING:
  72273. var f = [], b = [];
  72274. for (i = 0; i < polygon.vertices.length; i++) {
  72275. var j = (i + 1) % polygon.vertices.length;
  72276. var ti = types[i], tj = types[j];
  72277. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  72278. if (ti !== BACK)
  72279. f.push(vi);
  72280. if (ti !== FRONT)
  72281. b.push(ti !== BACK ? vi.clone() : vi);
  72282. if ((ti | tj) === SPANNING) {
  72283. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  72284. var v = vi.interpolate(vj, t);
  72285. f.push(v);
  72286. b.push(v.clone());
  72287. }
  72288. }
  72289. var poly;
  72290. if (f.length >= 3) {
  72291. poly = new Polygon(f, polygon.shared);
  72292. if (poly.plane)
  72293. front.push(poly);
  72294. }
  72295. if (b.length >= 3) {
  72296. poly = new Polygon(b, polygon.shared);
  72297. if (poly.plane)
  72298. back.push(poly);
  72299. }
  72300. break;
  72301. }
  72302. };
  72303. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  72304. // point is on the plane.
  72305. Plane.EPSILON = 1e-5;
  72306. return Plane;
  72307. }());
  72308. // # class Polygon
  72309. // Represents a convex polygon. The vertices used to initialize a polygon must
  72310. // be coplanar and form a convex loop.
  72311. //
  72312. // Each convex polygon has a `shared` property, which is shared between all
  72313. // polygons that are clones of each other or were split from the same polygon.
  72314. // This can be used to define per-polygon properties (such as surface color).
  72315. var Polygon = /** @class */ (function () {
  72316. function Polygon(vertices, shared) {
  72317. this.vertices = vertices;
  72318. this.shared = shared;
  72319. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  72320. }
  72321. Polygon.prototype.clone = function () {
  72322. var vertices = this.vertices.map(function (v) { return v.clone(); });
  72323. return new Polygon(vertices, this.shared);
  72324. };
  72325. Polygon.prototype.flip = function () {
  72326. this.vertices.reverse().map(function (v) { v.flip(); });
  72327. this.plane.flip();
  72328. };
  72329. return Polygon;
  72330. }());
  72331. // # class Node
  72332. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  72333. // by picking a polygon to split along. That polygon (and all other coplanar
  72334. // polygons) are added directly to that node and the other polygons are added to
  72335. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  72336. // no distinction between internal and leaf nodes.
  72337. var Node = /** @class */ (function () {
  72338. function Node(polygons) {
  72339. this.plane = null;
  72340. this.front = null;
  72341. this.back = null;
  72342. this.polygons = new Array();
  72343. if (polygons) {
  72344. this.build(polygons);
  72345. }
  72346. }
  72347. Node.prototype.clone = function () {
  72348. var node = new Node();
  72349. node.plane = this.plane && this.plane.clone();
  72350. node.front = this.front && this.front.clone();
  72351. node.back = this.back && this.back.clone();
  72352. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  72353. return node;
  72354. };
  72355. // Convert solid space to empty space and empty space to solid space.
  72356. Node.prototype.invert = function () {
  72357. for (var i = 0; i < this.polygons.length; i++) {
  72358. this.polygons[i].flip();
  72359. }
  72360. if (this.plane) {
  72361. this.plane.flip();
  72362. }
  72363. if (this.front) {
  72364. this.front.invert();
  72365. }
  72366. if (this.back) {
  72367. this.back.invert();
  72368. }
  72369. var temp = this.front;
  72370. this.front = this.back;
  72371. this.back = temp;
  72372. };
  72373. // Recursively remove all polygons in `polygons` that are inside this BSP
  72374. // tree.
  72375. Node.prototype.clipPolygons = function (polygons) {
  72376. if (!this.plane)
  72377. return polygons.slice();
  72378. var front = new Array(), back = new Array();
  72379. for (var i = 0; i < polygons.length; i++) {
  72380. this.plane.splitPolygon(polygons[i], front, back, front, back);
  72381. }
  72382. if (this.front) {
  72383. front = this.front.clipPolygons(front);
  72384. }
  72385. if (this.back) {
  72386. back = this.back.clipPolygons(back);
  72387. }
  72388. else {
  72389. back = [];
  72390. }
  72391. return front.concat(back);
  72392. };
  72393. // Remove all polygons in this BSP tree that are inside the other BSP tree
  72394. // `bsp`.
  72395. Node.prototype.clipTo = function (bsp) {
  72396. this.polygons = bsp.clipPolygons(this.polygons);
  72397. if (this.front)
  72398. this.front.clipTo(bsp);
  72399. if (this.back)
  72400. this.back.clipTo(bsp);
  72401. };
  72402. // Return a list of all polygons in this BSP tree.
  72403. Node.prototype.allPolygons = function () {
  72404. var polygons = this.polygons.slice();
  72405. if (this.front)
  72406. polygons = polygons.concat(this.front.allPolygons());
  72407. if (this.back)
  72408. polygons = polygons.concat(this.back.allPolygons());
  72409. return polygons;
  72410. };
  72411. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  72412. // new polygons are filtered down to the bottom of the tree and become new
  72413. // nodes there. Each set of polygons is partitioned using the first polygon
  72414. // (no heuristic is used to pick a good split).
  72415. Node.prototype.build = function (polygons) {
  72416. if (!polygons.length)
  72417. return;
  72418. if (!this.plane)
  72419. this.plane = polygons[0].plane.clone();
  72420. var front = new Array(), back = new Array();
  72421. for (var i = 0; i < polygons.length; i++) {
  72422. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  72423. }
  72424. if (front.length) {
  72425. if (!this.front)
  72426. this.front = new Node();
  72427. this.front.build(front);
  72428. }
  72429. if (back.length) {
  72430. if (!this.back)
  72431. this.back = new Node();
  72432. this.back.build(back);
  72433. }
  72434. };
  72435. return Node;
  72436. }());
  72437. var CSG = /** @class */ (function () {
  72438. function CSG() {
  72439. this.polygons = new Array();
  72440. }
  72441. // Convert BABYLON.Mesh to BABYLON.CSG
  72442. CSG.FromMesh = function (mesh) {
  72443. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  72444. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  72445. if (mesh instanceof BABYLON.Mesh) {
  72446. mesh.computeWorldMatrix(true);
  72447. matrix = mesh.getWorldMatrix();
  72448. meshPosition = mesh.position.clone();
  72449. meshRotation = mesh.rotation.clone();
  72450. if (mesh.rotationQuaternion) {
  72451. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  72452. }
  72453. meshScaling = mesh.scaling.clone();
  72454. }
  72455. else {
  72456. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  72457. }
  72458. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  72459. var subMeshes = mesh.subMeshes;
  72460. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  72461. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  72462. vertices = [];
  72463. for (var j = 0; j < 3; j++) {
  72464. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  72465. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  72466. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  72467. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  72468. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  72469. vertex = new Vertex(position, normal, uv);
  72470. vertices.push(vertex);
  72471. }
  72472. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  72473. // To handle the case of degenerated triangle
  72474. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  72475. if (polygon.plane)
  72476. polygons.push(polygon);
  72477. }
  72478. }
  72479. var csg = CSG.FromPolygons(polygons);
  72480. csg.matrix = matrix;
  72481. csg.position = meshPosition;
  72482. csg.rotation = meshRotation;
  72483. csg.scaling = meshScaling;
  72484. csg.rotationQuaternion = meshRotationQuaternion;
  72485. currentCSGMeshId++;
  72486. return csg;
  72487. };
  72488. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  72489. CSG.FromPolygons = function (polygons) {
  72490. var csg = new CSG();
  72491. csg.polygons = polygons;
  72492. return csg;
  72493. };
  72494. CSG.prototype.clone = function () {
  72495. var csg = new CSG();
  72496. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  72497. csg.copyTransformAttributes(this);
  72498. return csg;
  72499. };
  72500. CSG.prototype.union = function (csg) {
  72501. var a = new Node(this.clone().polygons);
  72502. var b = new Node(csg.clone().polygons);
  72503. a.clipTo(b);
  72504. b.clipTo(a);
  72505. b.invert();
  72506. b.clipTo(a);
  72507. b.invert();
  72508. a.build(b.allPolygons());
  72509. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  72510. };
  72511. CSG.prototype.unionInPlace = function (csg) {
  72512. var a = new Node(this.polygons);
  72513. var b = new Node(csg.polygons);
  72514. a.clipTo(b);
  72515. b.clipTo(a);
  72516. b.invert();
  72517. b.clipTo(a);
  72518. b.invert();
  72519. a.build(b.allPolygons());
  72520. this.polygons = a.allPolygons();
  72521. };
  72522. CSG.prototype.subtract = function (csg) {
  72523. var a = new Node(this.clone().polygons);
  72524. var b = new Node(csg.clone().polygons);
  72525. a.invert();
  72526. a.clipTo(b);
  72527. b.clipTo(a);
  72528. b.invert();
  72529. b.clipTo(a);
  72530. b.invert();
  72531. a.build(b.allPolygons());
  72532. a.invert();
  72533. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  72534. };
  72535. CSG.prototype.subtractInPlace = function (csg) {
  72536. var a = new Node(this.polygons);
  72537. var b = new Node(csg.polygons);
  72538. a.invert();
  72539. a.clipTo(b);
  72540. b.clipTo(a);
  72541. b.invert();
  72542. b.clipTo(a);
  72543. b.invert();
  72544. a.build(b.allPolygons());
  72545. a.invert();
  72546. this.polygons = a.allPolygons();
  72547. };
  72548. CSG.prototype.intersect = function (csg) {
  72549. var a = new Node(this.clone().polygons);
  72550. var b = new Node(csg.clone().polygons);
  72551. a.invert();
  72552. b.clipTo(a);
  72553. b.invert();
  72554. a.clipTo(b);
  72555. b.clipTo(a);
  72556. a.build(b.allPolygons());
  72557. a.invert();
  72558. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  72559. };
  72560. CSG.prototype.intersectInPlace = function (csg) {
  72561. var a = new Node(this.polygons);
  72562. var b = new Node(csg.polygons);
  72563. a.invert();
  72564. b.clipTo(a);
  72565. b.invert();
  72566. a.clipTo(b);
  72567. b.clipTo(a);
  72568. a.build(b.allPolygons());
  72569. a.invert();
  72570. this.polygons = a.allPolygons();
  72571. };
  72572. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  72573. // not modified.
  72574. CSG.prototype.inverse = function () {
  72575. var csg = this.clone();
  72576. csg.inverseInPlace();
  72577. return csg;
  72578. };
  72579. CSG.prototype.inverseInPlace = function () {
  72580. this.polygons.map(function (p) { p.flip(); });
  72581. };
  72582. // This is used to keep meshes transformations so they can be restored
  72583. // when we build back a Babylon Mesh
  72584. // NB : All CSG operations are performed in world coordinates
  72585. CSG.prototype.copyTransformAttributes = function (csg) {
  72586. this.matrix = csg.matrix;
  72587. this.position = csg.position;
  72588. this.rotation = csg.rotation;
  72589. this.scaling = csg.scaling;
  72590. this.rotationQuaternion = csg.rotationQuaternion;
  72591. return this;
  72592. };
  72593. // Build Raw mesh from CSG
  72594. // Coordinates here are in world space
  72595. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  72596. var matrix = this.matrix.clone();
  72597. matrix.invert();
  72598. 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;
  72599. if (keepSubMeshes) {
  72600. // Sort Polygons, since subMeshes are indices range
  72601. polygons.sort(function (a, b) {
  72602. if (a.shared.meshId === b.shared.meshId) {
  72603. return a.shared.subMeshId - b.shared.subMeshId;
  72604. }
  72605. else {
  72606. return a.shared.meshId - b.shared.meshId;
  72607. }
  72608. });
  72609. }
  72610. for (var i = 0, il = polygons.length; i < il; i++) {
  72611. polygon = polygons[i];
  72612. // Building SubMeshes
  72613. if (!subMesh_dict[polygon.shared.meshId]) {
  72614. subMesh_dict[polygon.shared.meshId] = {};
  72615. }
  72616. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  72617. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  72618. indexStart: +Infinity,
  72619. indexEnd: -Infinity,
  72620. materialIndex: polygon.shared.materialIndex
  72621. };
  72622. }
  72623. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  72624. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  72625. polygonIndices[0] = 0;
  72626. polygonIndices[1] = j - 1;
  72627. polygonIndices[2] = j;
  72628. for (var k = 0; k < 3; k++) {
  72629. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  72630. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  72631. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  72632. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  72633. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  72634. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  72635. // Check if 2 points can be merged
  72636. if (!(typeof vertex_idx !== 'undefined' &&
  72637. normals[vertex_idx * 3] === localNormal.x &&
  72638. normals[vertex_idx * 3 + 1] === localNormal.y &&
  72639. normals[vertex_idx * 3 + 2] === localNormal.z &&
  72640. uvs[vertex_idx * 2] === uv.x &&
  72641. uvs[vertex_idx * 2 + 1] === uv.y)) {
  72642. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  72643. uvs.push(uv.x, uv.y);
  72644. normals.push(normal.x, normal.y, normal.z);
  72645. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  72646. }
  72647. indices.push(vertex_idx);
  72648. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  72649. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  72650. currentIndex++;
  72651. }
  72652. }
  72653. }
  72654. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  72655. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  72656. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  72657. mesh.setIndices(indices, null);
  72658. if (keepSubMeshes) {
  72659. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  72660. var materialIndexOffset = 0, materialMaxIndex;
  72661. mesh.subMeshes = new Array();
  72662. for (var m in subMesh_dict) {
  72663. materialMaxIndex = -1;
  72664. for (var sm in subMesh_dict[m]) {
  72665. subMesh_obj = subMesh_dict[m][sm];
  72666. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  72667. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  72668. }
  72669. materialIndexOffset += ++materialMaxIndex;
  72670. }
  72671. }
  72672. return mesh;
  72673. };
  72674. // Build Mesh from CSG taking material and transforms into account
  72675. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  72676. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  72677. mesh.material = material;
  72678. mesh.position.copyFrom(this.position);
  72679. mesh.rotation.copyFrom(this.rotation);
  72680. if (this.rotationQuaternion) {
  72681. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  72682. }
  72683. mesh.scaling.copyFrom(this.scaling);
  72684. mesh.computeWorldMatrix(true);
  72685. return mesh;
  72686. };
  72687. return CSG;
  72688. }());
  72689. BABYLON.CSG = CSG;
  72690. })(BABYLON || (BABYLON = {}));
  72691. //# sourceMappingURL=babylon.csg.js.map
  72692. var BABYLON;
  72693. (function (BABYLON) {
  72694. var LensFlare = /** @class */ (function () {
  72695. function LensFlare(size, position, color, imgUrl, system) {
  72696. this.size = size;
  72697. this.position = position;
  72698. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  72699. this.color = color || new BABYLON.Color3(1, 1, 1);
  72700. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  72701. this._system = system;
  72702. system.lensFlares.push(this);
  72703. }
  72704. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  72705. return new LensFlare(size, position, color, imgUrl, system);
  72706. };
  72707. LensFlare.prototype.dispose = function () {
  72708. if (this.texture) {
  72709. this.texture.dispose();
  72710. }
  72711. // Remove from scene
  72712. var index = this._system.lensFlares.indexOf(this);
  72713. this._system.lensFlares.splice(index, 1);
  72714. };
  72715. ;
  72716. return LensFlare;
  72717. }());
  72718. BABYLON.LensFlare = LensFlare;
  72719. })(BABYLON || (BABYLON = {}));
  72720. //# sourceMappingURL=babylon.lensFlare.js.map
  72721. var BABYLON;
  72722. (function (BABYLON) {
  72723. var LensFlareSystem = /** @class */ (function () {
  72724. function LensFlareSystem(name, emitter, scene) {
  72725. this.name = name;
  72726. this.lensFlares = new Array();
  72727. this.borderLimit = 300;
  72728. this.viewportBorder = 0;
  72729. this.layerMask = 0x0FFFFFFF;
  72730. this._vertexBuffers = {};
  72731. this._isEnabled = true;
  72732. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  72733. this._emitter = emitter;
  72734. this.id = name;
  72735. scene.lensFlareSystems.push(this);
  72736. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  72737. var engine = scene.getEngine();
  72738. // VBO
  72739. var vertices = [];
  72740. vertices.push(1, 1);
  72741. vertices.push(-1, 1);
  72742. vertices.push(-1, -1);
  72743. vertices.push(1, -1);
  72744. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  72745. // Indices
  72746. var indices = [];
  72747. indices.push(0);
  72748. indices.push(1);
  72749. indices.push(2);
  72750. indices.push(0);
  72751. indices.push(2);
  72752. indices.push(3);
  72753. this._indexBuffer = engine.createIndexBuffer(indices);
  72754. // Effects
  72755. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  72756. }
  72757. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  72758. get: function () {
  72759. return this._isEnabled;
  72760. },
  72761. set: function (value) {
  72762. this._isEnabled = value;
  72763. },
  72764. enumerable: true,
  72765. configurable: true
  72766. });
  72767. LensFlareSystem.prototype.getScene = function () {
  72768. return this._scene;
  72769. };
  72770. LensFlareSystem.prototype.getEmitter = function () {
  72771. return this._emitter;
  72772. };
  72773. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  72774. this._emitter = newEmitter;
  72775. };
  72776. LensFlareSystem.prototype.getEmitterPosition = function () {
  72777. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  72778. };
  72779. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  72780. var position = this.getEmitterPosition();
  72781. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  72782. this._positionX = position.x;
  72783. this._positionY = position.y;
  72784. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  72785. if (this.viewportBorder > 0) {
  72786. globalViewport.x -= this.viewportBorder;
  72787. globalViewport.y -= this.viewportBorder;
  72788. globalViewport.width += this.viewportBorder * 2;
  72789. globalViewport.height += this.viewportBorder * 2;
  72790. position.x += this.viewportBorder;
  72791. position.y += this.viewportBorder;
  72792. this._positionX += this.viewportBorder;
  72793. this._positionY += this.viewportBorder;
  72794. }
  72795. if (position.z > 0) {
  72796. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  72797. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  72798. return true;
  72799. }
  72800. return true;
  72801. }
  72802. return false;
  72803. };
  72804. LensFlareSystem.prototype._isVisible = function () {
  72805. if (!this._isEnabled || !this._scene.activeCamera) {
  72806. return false;
  72807. }
  72808. var emitterPosition = this.getEmitterPosition();
  72809. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  72810. var distance = direction.length();
  72811. direction.normalize();
  72812. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  72813. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  72814. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  72815. };
  72816. LensFlareSystem.prototype.render = function () {
  72817. if (!this._effect.isReady() || !this._scene.activeCamera)
  72818. return false;
  72819. var engine = this._scene.getEngine();
  72820. var viewport = this._scene.activeCamera.viewport;
  72821. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  72822. // Position
  72823. if (!this.computeEffectivePosition(globalViewport)) {
  72824. return false;
  72825. }
  72826. // Visibility
  72827. if (!this._isVisible()) {
  72828. return false;
  72829. }
  72830. // Intensity
  72831. var awayX;
  72832. var awayY;
  72833. if (this._positionX < this.borderLimit + globalViewport.x) {
  72834. awayX = this.borderLimit + globalViewport.x - this._positionX;
  72835. }
  72836. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  72837. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  72838. }
  72839. else {
  72840. awayX = 0;
  72841. }
  72842. if (this._positionY < this.borderLimit + globalViewport.y) {
  72843. awayY = this.borderLimit + globalViewport.y - this._positionY;
  72844. }
  72845. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  72846. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  72847. }
  72848. else {
  72849. awayY = 0;
  72850. }
  72851. var away = (awayX > awayY) ? awayX : awayY;
  72852. away -= this.viewportBorder;
  72853. if (away > this.borderLimit) {
  72854. away = this.borderLimit;
  72855. }
  72856. var intensity = 1.0 - (away / this.borderLimit);
  72857. if (intensity < 0) {
  72858. return false;
  72859. }
  72860. if (intensity > 1.0) {
  72861. intensity = 1.0;
  72862. }
  72863. if (this.viewportBorder > 0) {
  72864. globalViewport.x += this.viewportBorder;
  72865. globalViewport.y += this.viewportBorder;
  72866. globalViewport.width -= this.viewportBorder * 2;
  72867. globalViewport.height -= this.viewportBorder * 2;
  72868. this._positionX -= this.viewportBorder;
  72869. this._positionY -= this.viewportBorder;
  72870. }
  72871. // Position
  72872. var centerX = globalViewport.x + globalViewport.width / 2;
  72873. var centerY = globalViewport.y + globalViewport.height / 2;
  72874. var distX = centerX - this._positionX;
  72875. var distY = centerY - this._positionY;
  72876. // Effects
  72877. engine.enableEffect(this._effect);
  72878. engine.setState(false);
  72879. engine.setDepthBuffer(false);
  72880. // VBOs
  72881. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  72882. // Flares
  72883. for (var index = 0; index < this.lensFlares.length; index++) {
  72884. var flare = this.lensFlares[index];
  72885. engine.setAlphaMode(flare.alphaMode);
  72886. var x = centerX - (distX * flare.position);
  72887. var y = centerY - (distY * flare.position);
  72888. var cw = flare.size;
  72889. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  72890. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  72891. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  72892. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  72893. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  72894. // Texture
  72895. this._effect.setTexture("textureSampler", flare.texture);
  72896. // Color
  72897. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  72898. // Draw order
  72899. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  72900. }
  72901. engine.setDepthBuffer(true);
  72902. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  72903. return true;
  72904. };
  72905. LensFlareSystem.prototype.dispose = function () {
  72906. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  72907. if (vertexBuffer) {
  72908. vertexBuffer.dispose();
  72909. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  72910. }
  72911. if (this._indexBuffer) {
  72912. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  72913. this._indexBuffer = null;
  72914. }
  72915. while (this.lensFlares.length) {
  72916. this.lensFlares[0].dispose();
  72917. }
  72918. // Remove from scene
  72919. var index = this._scene.lensFlareSystems.indexOf(this);
  72920. this._scene.lensFlareSystems.splice(index, 1);
  72921. };
  72922. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  72923. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  72924. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  72925. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  72926. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  72927. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  72928. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  72929. var parsedFlare = parsedLensFlareSystem.flares[index];
  72930. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  72931. }
  72932. return lensFlareSystem;
  72933. };
  72934. LensFlareSystem.prototype.serialize = function () {
  72935. var serializationObject = {};
  72936. serializationObject.id = this.id;
  72937. serializationObject.name = this.name;
  72938. serializationObject.emitterId = this.getEmitter().id;
  72939. serializationObject.borderLimit = this.borderLimit;
  72940. serializationObject.flares = [];
  72941. for (var index = 0; index < this.lensFlares.length; index++) {
  72942. var flare = this.lensFlares[index];
  72943. serializationObject.flares.push({
  72944. size: flare.size,
  72945. position: flare.position,
  72946. color: flare.color.asArray(),
  72947. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  72948. });
  72949. }
  72950. return serializationObject;
  72951. };
  72952. return LensFlareSystem;
  72953. }());
  72954. BABYLON.LensFlareSystem = LensFlareSystem;
  72955. })(BABYLON || (BABYLON = {}));
  72956. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  72957. var BABYLON;
  72958. (function (BABYLON) {
  72959. /**
  72960. * This is a holder class for the physics joint created by the physics plugin.
  72961. * It holds a set of functions to control the underlying joint.
  72962. */
  72963. var PhysicsJoint = /** @class */ (function () {
  72964. function PhysicsJoint(type, jointData) {
  72965. this.type = type;
  72966. this.jointData = jointData;
  72967. jointData.nativeParams = jointData.nativeParams || {};
  72968. }
  72969. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  72970. get: function () {
  72971. return this._physicsJoint;
  72972. },
  72973. set: function (newJoint) {
  72974. if (this._physicsJoint) {
  72975. //remove from the wolrd
  72976. }
  72977. this._physicsJoint = newJoint;
  72978. },
  72979. enumerable: true,
  72980. configurable: true
  72981. });
  72982. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  72983. set: function (physicsPlugin) {
  72984. this._physicsPlugin = physicsPlugin;
  72985. },
  72986. enumerable: true,
  72987. configurable: true
  72988. });
  72989. /**
  72990. * Execute a function that is physics-plugin specific.
  72991. * @param {Function} func the function that will be executed.
  72992. * It accepts two parameters: the physics world and the physics joint.
  72993. */
  72994. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  72995. func(this._physicsPlugin.world, this._physicsJoint);
  72996. };
  72997. //TODO check if the native joints are the same
  72998. //Joint Types
  72999. PhysicsJoint.DistanceJoint = 0;
  73000. PhysicsJoint.HingeJoint = 1;
  73001. PhysicsJoint.BallAndSocketJoint = 2;
  73002. PhysicsJoint.WheelJoint = 3;
  73003. PhysicsJoint.SliderJoint = 4;
  73004. //OIMO
  73005. PhysicsJoint.PrismaticJoint = 5;
  73006. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  73007. PhysicsJoint.UniversalJoint = 6;
  73008. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  73009. //Cannon
  73010. //Similar to a Ball-Joint. Different in params
  73011. PhysicsJoint.PointToPointJoint = 8;
  73012. //Cannon only at the moment
  73013. PhysicsJoint.SpringJoint = 9;
  73014. PhysicsJoint.LockJoint = 10;
  73015. return PhysicsJoint;
  73016. }());
  73017. BABYLON.PhysicsJoint = PhysicsJoint;
  73018. /**
  73019. * A class representing a physics distance joint.
  73020. */
  73021. var DistanceJoint = /** @class */ (function (_super) {
  73022. __extends(DistanceJoint, _super);
  73023. function DistanceJoint(jointData) {
  73024. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  73025. }
  73026. /**
  73027. * Update the predefined distance.
  73028. */
  73029. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  73030. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  73031. };
  73032. return DistanceJoint;
  73033. }(PhysicsJoint));
  73034. BABYLON.DistanceJoint = DistanceJoint;
  73035. var MotorEnabledJoint = /** @class */ (function (_super) {
  73036. __extends(MotorEnabledJoint, _super);
  73037. function MotorEnabledJoint(type, jointData) {
  73038. return _super.call(this, type, jointData) || this;
  73039. }
  73040. /**
  73041. * Set the motor values.
  73042. * Attention, this function is plugin specific. Engines won't react 100% the same.
  73043. * @param {number} force the force to apply
  73044. * @param {number} maxForce max force for this motor.
  73045. */
  73046. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  73047. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  73048. };
  73049. /**
  73050. * Set the motor's limits.
  73051. * Attention, this function is plugin specific. Engines won't react 100% the same.
  73052. */
  73053. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  73054. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  73055. };
  73056. return MotorEnabledJoint;
  73057. }(PhysicsJoint));
  73058. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  73059. /**
  73060. * This class represents a single hinge physics joint
  73061. */
  73062. var HingeJoint = /** @class */ (function (_super) {
  73063. __extends(HingeJoint, _super);
  73064. function HingeJoint(jointData) {
  73065. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  73066. }
  73067. /**
  73068. * Set the motor values.
  73069. * Attention, this function is plugin specific. Engines won't react 100% the same.
  73070. * @param {number} force the force to apply
  73071. * @param {number} maxForce max force for this motor.
  73072. */
  73073. HingeJoint.prototype.setMotor = function (force, maxForce) {
  73074. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  73075. };
  73076. /**
  73077. * Set the motor's limits.
  73078. * Attention, this function is plugin specific. Engines won't react 100% the same.
  73079. */
  73080. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  73081. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  73082. };
  73083. return HingeJoint;
  73084. }(MotorEnabledJoint));
  73085. BABYLON.HingeJoint = HingeJoint;
  73086. /**
  73087. * This class represents a dual hinge physics joint (same as wheel joint)
  73088. */
  73089. var Hinge2Joint = /** @class */ (function (_super) {
  73090. __extends(Hinge2Joint, _super);
  73091. function Hinge2Joint(jointData) {
  73092. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  73093. }
  73094. /**
  73095. * Set the motor values.
  73096. * Attention, this function is plugin specific. Engines won't react 100% the same.
  73097. * @param {number} force the force to apply
  73098. * @param {number} maxForce max force for this motor.
  73099. * @param {motorIndex} the motor's index, 0 or 1.
  73100. */
  73101. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  73102. if (motorIndex === void 0) { motorIndex = 0; }
  73103. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  73104. };
  73105. /**
  73106. * Set the motor limits.
  73107. * Attention, this function is plugin specific. Engines won't react 100% the same.
  73108. * @param {number} upperLimit the upper limit
  73109. * @param {number} lowerLimit lower limit
  73110. * @param {motorIndex} the motor's index, 0 or 1.
  73111. */
  73112. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  73113. if (motorIndex === void 0) { motorIndex = 0; }
  73114. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  73115. };
  73116. return Hinge2Joint;
  73117. }(MotorEnabledJoint));
  73118. BABYLON.Hinge2Joint = Hinge2Joint;
  73119. })(BABYLON || (BABYLON = {}));
  73120. //# sourceMappingURL=babylon.physicsJoint.js.map
  73121. var BABYLON;
  73122. (function (BABYLON) {
  73123. var PhysicsImpostor = /** @class */ (function () {
  73124. function PhysicsImpostor(object, type, _options, _scene) {
  73125. if (_options === void 0) { _options = { mass: 0 }; }
  73126. var _this = this;
  73127. this.object = object;
  73128. this.type = type;
  73129. this._options = _options;
  73130. this._scene = _scene;
  73131. this._bodyUpdateRequired = false;
  73132. this._onBeforePhysicsStepCallbacks = new Array();
  73133. this._onAfterPhysicsStepCallbacks = new Array();
  73134. this._onPhysicsCollideCallbacks = [];
  73135. this._deltaPosition = BABYLON.Vector3.Zero();
  73136. this._isDisposed = false;
  73137. //temp variables for parent rotation calculations
  73138. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  73139. this._tmpQuat = new BABYLON.Quaternion();
  73140. this._tmpQuat2 = new BABYLON.Quaternion();
  73141. /**
  73142. * this function is executed by the physics engine.
  73143. */
  73144. this.beforeStep = function () {
  73145. if (!_this._physicsEngine) {
  73146. return;
  73147. }
  73148. _this.object.translate(_this._deltaPosition, -1);
  73149. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  73150. _this.object.computeWorldMatrix(false);
  73151. if (_this.object.parent && _this.object.rotationQuaternion) {
  73152. _this.getParentsRotation();
  73153. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  73154. }
  73155. else {
  73156. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  73157. }
  73158. if (!_this._options.disableBidirectionalTransformation) {
  73159. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  73160. }
  73161. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  73162. func(_this);
  73163. });
  73164. };
  73165. /**
  73166. * this function is executed by the physics engine.
  73167. */
  73168. this.afterStep = function () {
  73169. if (!_this._physicsEngine) {
  73170. return;
  73171. }
  73172. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  73173. func(_this);
  73174. });
  73175. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  73176. // object has now its world rotation. needs to be converted to local.
  73177. if (_this.object.parent && _this.object.rotationQuaternion) {
  73178. _this.getParentsRotation();
  73179. _this._tmpQuat.conjugateInPlace();
  73180. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  73181. }
  73182. // take the position set and make it the absolute position of this object.
  73183. _this.object.setAbsolutePosition(_this.object.position);
  73184. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  73185. _this.object.translate(_this._deltaPosition, 1);
  73186. };
  73187. /**
  73188. * Legacy collision detection event support
  73189. */
  73190. this.onCollideEvent = null;
  73191. //event and body object due to cannon's event-based architecture.
  73192. this.onCollide = function (e) {
  73193. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  73194. return;
  73195. }
  73196. if (!_this._physicsEngine) {
  73197. return;
  73198. }
  73199. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  73200. if (otherImpostor) {
  73201. // Legacy collision detection event support
  73202. if (_this.onCollideEvent) {
  73203. _this.onCollideEvent(_this, otherImpostor);
  73204. }
  73205. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  73206. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  73207. }).forEach(function (obj) {
  73208. obj.callback(_this, otherImpostor);
  73209. });
  73210. }
  73211. };
  73212. //sanity check!
  73213. if (!this.object) {
  73214. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  73215. return;
  73216. }
  73217. //legacy support for old syntax.
  73218. if (!this._scene && object.getScene) {
  73219. this._scene = object.getScene();
  73220. }
  73221. if (!this._scene) {
  73222. return;
  73223. }
  73224. this._physicsEngine = this._scene.getPhysicsEngine();
  73225. if (!this._physicsEngine) {
  73226. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  73227. }
  73228. else {
  73229. //set the object's quaternion, if not set
  73230. if (!this.object.rotationQuaternion) {
  73231. if (this.object.rotation) {
  73232. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  73233. }
  73234. else {
  73235. this.object.rotationQuaternion = new BABYLON.Quaternion();
  73236. }
  73237. }
  73238. //default options params
  73239. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  73240. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  73241. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  73242. this._joints = [];
  73243. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  73244. if (!this.object.parent || this._options.ignoreParent) {
  73245. this._init();
  73246. }
  73247. else if (this.object.parent.physicsImpostor) {
  73248. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  73249. }
  73250. }
  73251. }
  73252. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  73253. get: function () {
  73254. return this._isDisposed;
  73255. },
  73256. enumerable: true,
  73257. configurable: true
  73258. });
  73259. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  73260. get: function () {
  73261. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  73262. },
  73263. set: function (value) {
  73264. this.setMass(value);
  73265. },
  73266. enumerable: true,
  73267. configurable: true
  73268. });
  73269. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  73270. get: function () {
  73271. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  73272. },
  73273. set: function (value) {
  73274. if (!this._physicsEngine) {
  73275. return;
  73276. }
  73277. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  73278. },
  73279. enumerable: true,
  73280. configurable: true
  73281. });
  73282. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  73283. get: function () {
  73284. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  73285. },
  73286. set: function (value) {
  73287. if (!this._physicsEngine) {
  73288. return;
  73289. }
  73290. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  73291. },
  73292. enumerable: true,
  73293. configurable: true
  73294. });
  73295. /**
  73296. * This function will completly initialize this impostor.
  73297. * It will create a new body - but only if this mesh has no parent.
  73298. * If it has, this impostor will not be used other than to define the impostor
  73299. * of the child mesh.
  73300. */
  73301. PhysicsImpostor.prototype._init = function () {
  73302. if (!this._physicsEngine) {
  73303. return;
  73304. }
  73305. this._physicsEngine.removeImpostor(this);
  73306. this.physicsBody = null;
  73307. this._parent = this._parent || this._getPhysicsParent();
  73308. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  73309. this._physicsEngine.addImpostor(this);
  73310. }
  73311. };
  73312. PhysicsImpostor.prototype._getPhysicsParent = function () {
  73313. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  73314. var parentMesh = this.object.parent;
  73315. return parentMesh.physicsImpostor;
  73316. }
  73317. return null;
  73318. };
  73319. /**
  73320. * Should a new body be generated.
  73321. */
  73322. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  73323. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  73324. };
  73325. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  73326. this.forceUpdate();
  73327. };
  73328. /**
  73329. * Force a regeneration of this or the parent's impostor's body.
  73330. * Use under cautious - This will remove all joints already implemented.
  73331. */
  73332. PhysicsImpostor.prototype.forceUpdate = function () {
  73333. this._init();
  73334. if (this.parent && !this._options.ignoreParent) {
  73335. this.parent.forceUpdate();
  73336. }
  73337. };
  73338. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  73339. /*public get mesh(): AbstractMesh {
  73340. return this._mesh;
  73341. }*/
  73342. /**
  73343. * Gets the body that holds this impostor. Either its own, or its parent.
  73344. */
  73345. get: function () {
  73346. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  73347. },
  73348. /**
  73349. * Set the physics body. Used mainly by the physics engine/plugin
  73350. */
  73351. set: function (physicsBody) {
  73352. if (this._physicsBody && this._physicsEngine) {
  73353. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  73354. }
  73355. this._physicsBody = physicsBody;
  73356. this.resetUpdateFlags();
  73357. },
  73358. enumerable: true,
  73359. configurable: true
  73360. });
  73361. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  73362. get: function () {
  73363. return !this._options.ignoreParent && this._parent ? this._parent : null;
  73364. },
  73365. set: function (value) {
  73366. this._parent = value;
  73367. },
  73368. enumerable: true,
  73369. configurable: true
  73370. });
  73371. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  73372. this._bodyUpdateRequired = false;
  73373. };
  73374. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  73375. if (this.object.getBoundingInfo) {
  73376. var q = this.object.rotationQuaternion;
  73377. //reset rotation
  73378. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  73379. //calculate the world matrix with no rotation
  73380. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  73381. var boundingInfo = this.object.getBoundingInfo();
  73382. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  73383. //bring back the rotation
  73384. this.object.rotationQuaternion = q;
  73385. //calculate the world matrix with the new rotation
  73386. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  73387. return size;
  73388. }
  73389. else {
  73390. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  73391. }
  73392. };
  73393. PhysicsImpostor.prototype.getObjectCenter = function () {
  73394. if (this.object.getBoundingInfo) {
  73395. var boundingInfo = this.object.getBoundingInfo();
  73396. return boundingInfo.boundingBox.centerWorld;
  73397. }
  73398. else {
  73399. return this.object.position;
  73400. }
  73401. };
  73402. /**
  73403. * Get a specific parametes from the options parameter.
  73404. */
  73405. PhysicsImpostor.prototype.getParam = function (paramName) {
  73406. return this._options[paramName];
  73407. };
  73408. /**
  73409. * Sets a specific parameter in the options given to the physics plugin
  73410. */
  73411. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  73412. this._options[paramName] = value;
  73413. this._bodyUpdateRequired = true;
  73414. };
  73415. /**
  73416. * Specifically change the body's mass option. Won't recreate the physics body object
  73417. */
  73418. PhysicsImpostor.prototype.setMass = function (mass) {
  73419. if (this.getParam("mass") !== mass) {
  73420. this.setParam("mass", mass);
  73421. }
  73422. if (this._physicsEngine) {
  73423. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  73424. }
  73425. };
  73426. PhysicsImpostor.prototype.getLinearVelocity = function () {
  73427. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  73428. };
  73429. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  73430. if (this._physicsEngine) {
  73431. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  73432. }
  73433. };
  73434. PhysicsImpostor.prototype.getAngularVelocity = function () {
  73435. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  73436. };
  73437. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  73438. if (this._physicsEngine) {
  73439. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  73440. }
  73441. };
  73442. /**
  73443. * Execute a function with the physics plugin native code.
  73444. * Provide a function the will have two variables - the world object and the physics body object.
  73445. */
  73446. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  73447. if (this._physicsEngine) {
  73448. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  73449. }
  73450. };
  73451. /**
  73452. * Register a function that will be executed before the physics world is stepping forward.
  73453. */
  73454. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  73455. this._onBeforePhysicsStepCallbacks.push(func);
  73456. };
  73457. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  73458. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  73459. if (index > -1) {
  73460. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  73461. }
  73462. else {
  73463. BABYLON.Tools.Warn("Function to remove was not found");
  73464. }
  73465. };
  73466. /**
  73467. * Register a function that will be executed after the physics step
  73468. */
  73469. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  73470. this._onAfterPhysicsStepCallbacks.push(func);
  73471. };
  73472. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  73473. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  73474. if (index > -1) {
  73475. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  73476. }
  73477. else {
  73478. BABYLON.Tools.Warn("Function to remove was not found");
  73479. }
  73480. };
  73481. /**
  73482. * register a function that will be executed when this impostor collides against a different body.
  73483. */
  73484. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  73485. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  73486. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  73487. };
  73488. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  73489. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  73490. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  73491. if (index > -1) {
  73492. this._onPhysicsCollideCallbacks.splice(index, 1);
  73493. }
  73494. else {
  73495. BABYLON.Tools.Warn("Function to remove was not found");
  73496. }
  73497. };
  73498. PhysicsImpostor.prototype.getParentsRotation = function () {
  73499. var parent = this.object.parent;
  73500. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  73501. while (parent) {
  73502. if (parent.rotationQuaternion) {
  73503. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  73504. }
  73505. else {
  73506. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  73507. }
  73508. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  73509. parent = parent.parent;
  73510. }
  73511. return this._tmpQuat;
  73512. };
  73513. /**
  73514. * Apply a force
  73515. */
  73516. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  73517. if (this._physicsEngine) {
  73518. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  73519. }
  73520. return this;
  73521. };
  73522. /**
  73523. * Apply an impulse
  73524. */
  73525. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  73526. if (this._physicsEngine) {
  73527. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  73528. }
  73529. return this;
  73530. };
  73531. /**
  73532. * A help function to create a joint.
  73533. */
  73534. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  73535. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  73536. this.addJoint(otherImpostor, joint);
  73537. return this;
  73538. };
  73539. /**
  73540. * Add a joint to this impostor with a different impostor.
  73541. */
  73542. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  73543. this._joints.push({
  73544. otherImpostor: otherImpostor,
  73545. joint: joint
  73546. });
  73547. if (this._physicsEngine) {
  73548. this._physicsEngine.addJoint(this, otherImpostor, joint);
  73549. }
  73550. return this;
  73551. };
  73552. /**
  73553. * Will keep this body still, in a sleep mode.
  73554. */
  73555. PhysicsImpostor.prototype.sleep = function () {
  73556. if (this._physicsEngine) {
  73557. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  73558. }
  73559. return this;
  73560. };
  73561. /**
  73562. * Wake the body up.
  73563. */
  73564. PhysicsImpostor.prototype.wakeUp = function () {
  73565. if (this._physicsEngine) {
  73566. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  73567. }
  73568. return this;
  73569. };
  73570. PhysicsImpostor.prototype.clone = function (newObject) {
  73571. if (!newObject)
  73572. return null;
  73573. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  73574. };
  73575. PhysicsImpostor.prototype.dispose = function () {
  73576. var _this = this;
  73577. //no dispose if no physics engine is available.
  73578. if (!this._physicsEngine) {
  73579. return;
  73580. }
  73581. this._joints.forEach(function (j) {
  73582. if (_this._physicsEngine) {
  73583. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  73584. }
  73585. });
  73586. //dispose the physics body
  73587. this._physicsEngine.removeImpostor(this);
  73588. if (this.parent) {
  73589. this.parent.forceUpdate();
  73590. }
  73591. else {
  73592. /*this._object.getChildMeshes().forEach(function(mesh) {
  73593. if (mesh.physicsImpostor) {
  73594. if (disposeChildren) {
  73595. mesh.physicsImpostor.dispose();
  73596. mesh.physicsImpostor = null;
  73597. }
  73598. }
  73599. })*/
  73600. }
  73601. this._isDisposed = true;
  73602. };
  73603. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  73604. this._deltaPosition.copyFrom(position);
  73605. };
  73606. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  73607. if (!this._deltaRotation) {
  73608. this._deltaRotation = new BABYLON.Quaternion();
  73609. }
  73610. this._deltaRotation.copyFrom(rotation);
  73611. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  73612. };
  73613. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  73614. if (this._physicsEngine) {
  73615. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  73616. }
  73617. return this;
  73618. };
  73619. PhysicsImpostor.prototype.getRadius = function () {
  73620. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  73621. };
  73622. /**
  73623. * Sync a bone with this impostor
  73624. * @param bone The bone to sync to the impostor.
  73625. * @param boneMesh The mesh that the bone is influencing.
  73626. * @param jointPivot The pivot of the joint / bone in local space.
  73627. * @param distToJoint Optional distance from the impostor to the joint.
  73628. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  73629. */
  73630. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  73631. var tempVec = PhysicsImpostor._tmpVecs[0];
  73632. var mesh = this.object;
  73633. if (mesh.rotationQuaternion) {
  73634. if (adjustRotation) {
  73635. var tempQuat = PhysicsImpostor._tmpQuat;
  73636. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  73637. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  73638. }
  73639. else {
  73640. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  73641. }
  73642. }
  73643. tempVec.x = 0;
  73644. tempVec.y = 0;
  73645. tempVec.z = 0;
  73646. if (jointPivot) {
  73647. tempVec.x = jointPivot.x;
  73648. tempVec.y = jointPivot.y;
  73649. tempVec.z = jointPivot.z;
  73650. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  73651. if (distToJoint === undefined || distToJoint === null) {
  73652. distToJoint = jointPivot.length();
  73653. }
  73654. tempVec.x *= distToJoint;
  73655. tempVec.y *= distToJoint;
  73656. tempVec.z *= distToJoint;
  73657. }
  73658. if (bone.getParent()) {
  73659. tempVec.addInPlace(mesh.getAbsolutePosition());
  73660. bone.setAbsolutePosition(tempVec, boneMesh);
  73661. }
  73662. else {
  73663. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  73664. boneMesh.position.x -= tempVec.x;
  73665. boneMesh.position.y -= tempVec.y;
  73666. boneMesh.position.z -= tempVec.z;
  73667. }
  73668. };
  73669. /**
  73670. * Sync impostor to a bone
  73671. * @param bone The bone that the impostor will be synced to.
  73672. * @param boneMesh The mesh that the bone is influencing.
  73673. * @param jointPivot The pivot of the joint / bone in local space.
  73674. * @param distToJoint Optional distance from the impostor to the joint.
  73675. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  73676. * @param boneAxis Optional vector3 axis the bone is aligned with
  73677. */
  73678. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  73679. var mesh = this.object;
  73680. if (mesh.rotationQuaternion) {
  73681. if (adjustRotation) {
  73682. var tempQuat = PhysicsImpostor._tmpQuat;
  73683. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  73684. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  73685. }
  73686. else {
  73687. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  73688. }
  73689. }
  73690. var pos = PhysicsImpostor._tmpVecs[0];
  73691. var boneDir = PhysicsImpostor._tmpVecs[1];
  73692. if (!boneAxis) {
  73693. boneAxis = PhysicsImpostor._tmpVecs[2];
  73694. boneAxis.x = 0;
  73695. boneAxis.y = 1;
  73696. boneAxis.z = 0;
  73697. }
  73698. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  73699. bone.getAbsolutePositionToRef(boneMesh, pos);
  73700. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  73701. distToJoint = jointPivot.length();
  73702. }
  73703. if (distToJoint !== undefined && distToJoint !== null) {
  73704. pos.x += boneDir.x * distToJoint;
  73705. pos.y += boneDir.y * distToJoint;
  73706. pos.z += boneDir.z * distToJoint;
  73707. }
  73708. mesh.setAbsolutePosition(pos);
  73709. };
  73710. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  73711. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  73712. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  73713. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  73714. //Impostor types
  73715. PhysicsImpostor.NoImpostor = 0;
  73716. PhysicsImpostor.SphereImpostor = 1;
  73717. PhysicsImpostor.BoxImpostor = 2;
  73718. PhysicsImpostor.PlaneImpostor = 3;
  73719. PhysicsImpostor.MeshImpostor = 4;
  73720. PhysicsImpostor.CylinderImpostor = 7;
  73721. PhysicsImpostor.ParticleImpostor = 8;
  73722. PhysicsImpostor.HeightmapImpostor = 9;
  73723. return PhysicsImpostor;
  73724. }());
  73725. BABYLON.PhysicsImpostor = PhysicsImpostor;
  73726. })(BABYLON || (BABYLON = {}));
  73727. //# sourceMappingURL=babylon.physicsImpostor.js.map
  73728. var BABYLON;
  73729. (function (BABYLON) {
  73730. var PhysicsEngine = /** @class */ (function () {
  73731. function PhysicsEngine(gravity, _physicsPlugin) {
  73732. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  73733. this._physicsPlugin = _physicsPlugin;
  73734. //new methods and parameters
  73735. this._impostors = [];
  73736. this._joints = [];
  73737. if (!this._physicsPlugin.isSupported()) {
  73738. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  73739. + "Please make sure it is included.");
  73740. }
  73741. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  73742. this.setGravity(gravity);
  73743. this.setTimeStep();
  73744. }
  73745. PhysicsEngine.prototype.setGravity = function (gravity) {
  73746. this.gravity = gravity;
  73747. this._physicsPlugin.setGravity(this.gravity);
  73748. };
  73749. /**
  73750. * Set the time step of the physics engine.
  73751. * default is 1/60.
  73752. * To slow it down, enter 1/600 for example.
  73753. * To speed it up, 1/30
  73754. * @param {number} newTimeStep the new timestep to apply to this world.
  73755. */
  73756. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  73757. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  73758. this._physicsPlugin.setTimeStep(newTimeStep);
  73759. };
  73760. /**
  73761. * Get the time step of the physics engine.
  73762. */
  73763. PhysicsEngine.prototype.getTimeStep = function () {
  73764. return this._physicsPlugin.getTimeStep();
  73765. };
  73766. PhysicsEngine.prototype.dispose = function () {
  73767. this._impostors.forEach(function (impostor) {
  73768. impostor.dispose();
  73769. });
  73770. this._physicsPlugin.dispose();
  73771. };
  73772. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  73773. return this._physicsPlugin.name;
  73774. };
  73775. /**
  73776. * Adding a new impostor for the impostor tracking.
  73777. * This will be done by the impostor itself.
  73778. * @param {PhysicsImpostor} impostor the impostor to add
  73779. */
  73780. PhysicsEngine.prototype.addImpostor = function (impostor) {
  73781. impostor.uniqueId = this._impostors.push(impostor);
  73782. //if no parent, generate the body
  73783. if (!impostor.parent) {
  73784. this._physicsPlugin.generatePhysicsBody(impostor);
  73785. }
  73786. };
  73787. /**
  73788. * Remove an impostor from the engine.
  73789. * This impostor and its mesh will not longer be updated by the physics engine.
  73790. * @param {PhysicsImpostor} impostor the impostor to remove
  73791. */
  73792. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  73793. var index = this._impostors.indexOf(impostor);
  73794. if (index > -1) {
  73795. var removed = this._impostors.splice(index, 1);
  73796. //Is it needed?
  73797. if (removed.length) {
  73798. //this will also remove it from the world.
  73799. removed[0].physicsBody = null;
  73800. }
  73801. }
  73802. };
  73803. /**
  73804. * Add a joint to the physics engine
  73805. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  73806. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  73807. * @param {PhysicsJoint} the joint that will connect both impostors.
  73808. */
  73809. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  73810. var impostorJoint = {
  73811. mainImpostor: mainImpostor,
  73812. connectedImpostor: connectedImpostor,
  73813. joint: joint
  73814. };
  73815. joint.physicsPlugin = this._physicsPlugin;
  73816. this._joints.push(impostorJoint);
  73817. this._physicsPlugin.generateJoint(impostorJoint);
  73818. };
  73819. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  73820. var matchingJoints = this._joints.filter(function (impostorJoint) {
  73821. return (impostorJoint.connectedImpostor === connectedImpostor
  73822. && impostorJoint.joint === joint
  73823. && impostorJoint.mainImpostor === mainImpostor);
  73824. });
  73825. if (matchingJoints.length) {
  73826. this._physicsPlugin.removeJoint(matchingJoints[0]);
  73827. //TODO remove it from the list as well
  73828. }
  73829. };
  73830. /**
  73831. * Called by the scene. no need to call it.
  73832. */
  73833. PhysicsEngine.prototype._step = function (delta) {
  73834. var _this = this;
  73835. //check if any mesh has no body / requires an update
  73836. this._impostors.forEach(function (impostor) {
  73837. if (impostor.isBodyInitRequired()) {
  73838. _this._physicsPlugin.generatePhysicsBody(impostor);
  73839. }
  73840. });
  73841. if (delta > 0.1) {
  73842. delta = 0.1;
  73843. }
  73844. else if (delta <= 0) {
  73845. delta = 1.0 / 60.0;
  73846. }
  73847. this._physicsPlugin.executeStep(delta, this._impostors);
  73848. };
  73849. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  73850. return this._physicsPlugin;
  73851. };
  73852. PhysicsEngine.prototype.getImpostors = function () {
  73853. return this._impostors;
  73854. };
  73855. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  73856. for (var i = 0; i < this._impostors.length; ++i) {
  73857. if (this._impostors[i].object === object) {
  73858. return this._impostors[i];
  73859. }
  73860. }
  73861. return null;
  73862. };
  73863. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  73864. for (var i = 0; i < this._impostors.length; ++i) {
  73865. if (this._impostors[i].physicsBody === body) {
  73866. return this._impostors[i];
  73867. }
  73868. }
  73869. return null;
  73870. };
  73871. // Statics
  73872. PhysicsEngine.Epsilon = 0.001;
  73873. return PhysicsEngine;
  73874. }());
  73875. BABYLON.PhysicsEngine = PhysicsEngine;
  73876. })(BABYLON || (BABYLON = {}));
  73877. //# sourceMappingURL=babylon.physicsEngine.js.map
  73878. var BABYLON;
  73879. (function (BABYLON) {
  73880. var PhysicsHelper = /** @class */ (function () {
  73881. function PhysicsHelper(scene) {
  73882. this._scene = scene;
  73883. this._physicsEngine = this._scene.getPhysicsEngine();
  73884. if (!this._physicsEngine) {
  73885. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  73886. }
  73887. }
  73888. /**
  73889. * @param {Vector3} origin the origin of the explosion
  73890. * @param {number} radius the explosion radius
  73891. * @param {number} strength the explosion strength
  73892. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  73893. */
  73894. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  73895. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  73896. if (!this._physicsEngine) {
  73897. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  73898. return null;
  73899. }
  73900. var impostors = this._physicsEngine.getImpostors();
  73901. if (impostors.length === 0) {
  73902. return null;
  73903. }
  73904. var event = new PhysicsRadialExplosionEvent(this._scene);
  73905. impostors.forEach(function (impostor) {
  73906. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  73907. if (!impostorForceAndContactPoint) {
  73908. return;
  73909. }
  73910. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  73911. });
  73912. event.dispose(false);
  73913. return event;
  73914. };
  73915. /**
  73916. * @param {Vector3} origin the origin of the explosion
  73917. * @param {number} radius the explosion radius
  73918. * @param {number} strength the explosion strength
  73919. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  73920. */
  73921. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  73922. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  73923. if (!this._physicsEngine) {
  73924. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  73925. return null;
  73926. }
  73927. var impostors = this._physicsEngine.getImpostors();
  73928. if (impostors.length === 0) {
  73929. return null;
  73930. }
  73931. var event = new PhysicsRadialExplosionEvent(this._scene);
  73932. impostors.forEach(function (impostor) {
  73933. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  73934. if (!impostorForceAndContactPoint) {
  73935. return;
  73936. }
  73937. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  73938. });
  73939. event.dispose(false);
  73940. return event;
  73941. };
  73942. /**
  73943. * @param {Vector3} origin the origin of the explosion
  73944. * @param {number} radius the explosion radius
  73945. * @param {number} strength the explosion strength
  73946. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  73947. */
  73948. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  73949. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  73950. if (!this._physicsEngine) {
  73951. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  73952. return null;
  73953. }
  73954. var impostors = this._physicsEngine.getImpostors();
  73955. if (impostors.length === 0) {
  73956. return null;
  73957. }
  73958. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  73959. event.dispose(false);
  73960. return event;
  73961. };
  73962. /**
  73963. * @param {Vector3} origin the origin of the updraft
  73964. * @param {number} radius the radius of the updraft
  73965. * @param {number} strength the strength of the updraft
  73966. * @param {number} height the height of the updraft
  73967. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  73968. */
  73969. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  73970. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  73971. if (!this._physicsEngine) {
  73972. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  73973. return null;
  73974. }
  73975. if (this._physicsEngine.getImpostors().length === 0) {
  73976. return null;
  73977. }
  73978. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  73979. event.dispose(false);
  73980. return event;
  73981. };
  73982. /**
  73983. * @param {Vector3} origin the of the vortex
  73984. * @param {number} radius the radius of the vortex
  73985. * @param {number} strength the strength of the vortex
  73986. * @param {number} height the height of the vortex
  73987. */
  73988. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  73989. if (!this._physicsEngine) {
  73990. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  73991. return null;
  73992. }
  73993. if (this._physicsEngine.getImpostors().length === 0) {
  73994. return null;
  73995. }
  73996. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  73997. event.dispose(false);
  73998. return event;
  73999. };
  74000. return PhysicsHelper;
  74001. }());
  74002. BABYLON.PhysicsHelper = PhysicsHelper;
  74003. /***** Radial explosion *****/
  74004. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  74005. function PhysicsRadialExplosionEvent(scene) {
  74006. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  74007. this._rays = [];
  74008. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  74009. this._scene = scene;
  74010. }
  74011. /**
  74012. * Returns the data related to the radial explosion event (sphere & rays).
  74013. * @returns {PhysicsRadialExplosionEventData}
  74014. */
  74015. PhysicsRadialExplosionEvent.prototype.getData = function () {
  74016. this._dataFetched = true;
  74017. return {
  74018. sphere: this._sphere,
  74019. rays: this._rays,
  74020. };
  74021. };
  74022. /**
  74023. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  74024. * @param impostor
  74025. * @param {Vector3} origin the origin of the explosion
  74026. * @param {number} radius the explosion radius
  74027. * @param {number} strength the explosion strength
  74028. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  74029. * @returns {Nullable<PhysicsForceAndContactPoint>}
  74030. */
  74031. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  74032. if (impostor.mass === 0) {
  74033. return null;
  74034. }
  74035. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  74036. return null;
  74037. }
  74038. if (impostor.object.getClassName() !== 'Mesh') {
  74039. return null;
  74040. }
  74041. var impostorObject = impostor.object;
  74042. var impostorObjectCenter = impostor.getObjectCenter();
  74043. var direction = impostorObjectCenter.subtract(origin);
  74044. var ray = new BABYLON.Ray(origin, direction, radius);
  74045. this._rays.push(ray);
  74046. var hit = ray.intersectsMesh(impostorObject);
  74047. var contactPoint = hit.pickedPoint;
  74048. if (!contactPoint) {
  74049. return null;
  74050. }
  74051. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  74052. if (distanceFromOrigin > radius) {
  74053. return null;
  74054. }
  74055. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  74056. ? strength
  74057. : strength * (1 - (distanceFromOrigin / radius));
  74058. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  74059. return { force: force, contactPoint: contactPoint };
  74060. };
  74061. /**
  74062. * Disposes the sphere.
  74063. * @param {bolean} force
  74064. */
  74065. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  74066. var _this = this;
  74067. if (force === void 0) { force = true; }
  74068. if (force) {
  74069. this._sphere.dispose();
  74070. }
  74071. else {
  74072. setTimeout(function () {
  74073. if (!_this._dataFetched) {
  74074. _this._sphere.dispose();
  74075. }
  74076. }, 0);
  74077. }
  74078. };
  74079. /*** Helpers ***/
  74080. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  74081. if (!this._sphere) {
  74082. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  74083. this._sphere.isVisible = false;
  74084. }
  74085. };
  74086. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  74087. var impostorObject = impostor.object;
  74088. this._prepareSphere();
  74089. this._sphere.position = origin;
  74090. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  74091. this._sphere._updateBoundingInfo();
  74092. this._sphere.computeWorldMatrix(true);
  74093. return this._sphere.intersectsMesh(impostorObject, true);
  74094. };
  74095. return PhysicsRadialExplosionEvent;
  74096. }());
  74097. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  74098. /***** Gravitational Field *****/
  74099. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  74100. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  74101. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  74102. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  74103. this._physicsHelper = physicsHelper;
  74104. this._scene = scene;
  74105. this._origin = origin;
  74106. this._radius = radius;
  74107. this._strength = strength;
  74108. this._falloff = falloff;
  74109. this._tickCallback = this._tick.bind(this);
  74110. }
  74111. /**
  74112. * Returns the data related to the gravitational field event (sphere).
  74113. * @returns {PhysicsGravitationalFieldEventData}
  74114. */
  74115. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  74116. this._dataFetched = true;
  74117. return {
  74118. sphere: this._sphere,
  74119. };
  74120. };
  74121. /**
  74122. * Enables the gravitational field.
  74123. */
  74124. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  74125. this._tickCallback.call(this);
  74126. this._scene.registerBeforeRender(this._tickCallback);
  74127. };
  74128. /**
  74129. * Disables the gravitational field.
  74130. */
  74131. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  74132. this._scene.unregisterBeforeRender(this._tickCallback);
  74133. };
  74134. /**
  74135. * Disposes the sphere.
  74136. * @param {bolean} force
  74137. */
  74138. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  74139. var _this = this;
  74140. if (force === void 0) { force = true; }
  74141. if (force) {
  74142. this._sphere.dispose();
  74143. }
  74144. else {
  74145. setTimeout(function () {
  74146. if (!_this._dataFetched) {
  74147. _this._sphere.dispose();
  74148. }
  74149. }, 0);
  74150. }
  74151. };
  74152. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  74153. // Since the params won't change, we fetch the event only once
  74154. if (this._sphere) {
  74155. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  74156. }
  74157. else {
  74158. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  74159. if (radialExplosionEvent) {
  74160. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  74161. }
  74162. }
  74163. };
  74164. return PhysicsGravitationalFieldEvent;
  74165. }());
  74166. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  74167. /***** Updraft *****/
  74168. var PhysicsUpdraftEvent = /** @class */ (function () {
  74169. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  74170. this._scene = _scene;
  74171. this._origin = _origin;
  74172. this._radius = _radius;
  74173. this._strength = _strength;
  74174. this._height = _height;
  74175. this._updraftMode = _updraftMode;
  74176. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  74177. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  74178. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  74179. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  74180. this._physicsEngine = this._scene.getPhysicsEngine();
  74181. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  74182. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  74183. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  74184. this._originDirection = this._origin.subtract(this._originTop).normalize();
  74185. }
  74186. this._tickCallback = this._tick.bind(this);
  74187. }
  74188. /**
  74189. * Returns the data related to the updraft event (cylinder).
  74190. * @returns {PhysicsUpdraftEventData}
  74191. */
  74192. PhysicsUpdraftEvent.prototype.getData = function () {
  74193. this._dataFetched = true;
  74194. return {
  74195. cylinder: this._cylinder,
  74196. };
  74197. };
  74198. /**
  74199. * Enables the updraft.
  74200. */
  74201. PhysicsUpdraftEvent.prototype.enable = function () {
  74202. this._tickCallback.call(this);
  74203. this._scene.registerBeforeRender(this._tickCallback);
  74204. };
  74205. /**
  74206. * Disables the cortex.
  74207. */
  74208. PhysicsUpdraftEvent.prototype.disable = function () {
  74209. this._scene.unregisterBeforeRender(this._tickCallback);
  74210. };
  74211. /**
  74212. * Disposes the sphere.
  74213. * @param {bolean} force
  74214. */
  74215. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  74216. var _this = this;
  74217. if (force === void 0) { force = true; }
  74218. if (force) {
  74219. this._cylinder.dispose();
  74220. }
  74221. else {
  74222. setTimeout(function () {
  74223. if (!_this._dataFetched) {
  74224. _this._cylinder.dispose();
  74225. }
  74226. }, 0);
  74227. }
  74228. };
  74229. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  74230. if (impostor.mass === 0) {
  74231. return null;
  74232. }
  74233. if (!this._intersectsWithCylinder(impostor)) {
  74234. return null;
  74235. }
  74236. var impostorObjectCenter = impostor.getObjectCenter();
  74237. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  74238. var direction = this._originDirection;
  74239. }
  74240. else {
  74241. var direction = impostorObjectCenter.subtract(this._originTop);
  74242. }
  74243. var multiplier = this._strength * -1;
  74244. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  74245. return { force: force, contactPoint: impostorObjectCenter };
  74246. };
  74247. PhysicsUpdraftEvent.prototype._tick = function () {
  74248. var _this = this;
  74249. this._physicsEngine.getImpostors().forEach(function (impostor) {
  74250. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  74251. if (!impostorForceAndContactPoint) {
  74252. return;
  74253. }
  74254. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  74255. });
  74256. };
  74257. /*** Helpers ***/
  74258. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  74259. if (!this._cylinder) {
  74260. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  74261. height: this._height,
  74262. diameter: this._radius * 2,
  74263. }, this._scene);
  74264. this._cylinder.isVisible = false;
  74265. }
  74266. };
  74267. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  74268. var impostorObject = impostor.object;
  74269. this._prepareCylinder();
  74270. this._cylinder.position = this._cylinderPosition;
  74271. return this._cylinder.intersectsMesh(impostorObject, true);
  74272. };
  74273. return PhysicsUpdraftEvent;
  74274. }());
  74275. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  74276. /***** Vortex *****/
  74277. var PhysicsVortexEvent = /** @class */ (function () {
  74278. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  74279. this._scene = _scene;
  74280. this._origin = _origin;
  74281. this._radius = _radius;
  74282. this._strength = _strength;
  74283. this._height = _height;
  74284. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  74285. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  74286. this._updraftMultiplier = 0.02;
  74287. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  74288. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  74289. this._physicsEngine = this._scene.getPhysicsEngine();
  74290. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  74291. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  74292. this._tickCallback = this._tick.bind(this);
  74293. }
  74294. /**
  74295. * Returns the data related to the vortex event (cylinder).
  74296. * @returns {PhysicsVortexEventData}
  74297. */
  74298. PhysicsVortexEvent.prototype.getData = function () {
  74299. this._dataFetched = true;
  74300. return {
  74301. cylinder: this._cylinder,
  74302. };
  74303. };
  74304. /**
  74305. * Enables the vortex.
  74306. */
  74307. PhysicsVortexEvent.prototype.enable = function () {
  74308. this._tickCallback.call(this);
  74309. this._scene.registerBeforeRender(this._tickCallback);
  74310. };
  74311. /**
  74312. * Disables the cortex.
  74313. */
  74314. PhysicsVortexEvent.prototype.disable = function () {
  74315. this._scene.unregisterBeforeRender(this._tickCallback);
  74316. };
  74317. /**
  74318. * Disposes the sphere.
  74319. * @param {bolean} force
  74320. */
  74321. PhysicsVortexEvent.prototype.dispose = function (force) {
  74322. var _this = this;
  74323. if (force === void 0) { force = true; }
  74324. if (force) {
  74325. this._cylinder.dispose();
  74326. }
  74327. else {
  74328. setTimeout(function () {
  74329. if (!_this._dataFetched) {
  74330. _this._cylinder.dispose();
  74331. }
  74332. }, 0);
  74333. }
  74334. };
  74335. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  74336. if (impostor.mass === 0) {
  74337. return null;
  74338. }
  74339. if (!this._intersectsWithCylinder(impostor)) {
  74340. return null;
  74341. }
  74342. if (impostor.object.getClassName() !== 'Mesh') {
  74343. return null;
  74344. }
  74345. var impostorObject = impostor.object;
  74346. var impostorObjectCenter = impostor.getObjectCenter();
  74347. 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)
  74348. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  74349. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  74350. var hit = ray.intersectsMesh(impostorObject);
  74351. var contactPoint = hit.pickedPoint;
  74352. if (!contactPoint) {
  74353. return null;
  74354. }
  74355. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  74356. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  74357. var directionToOrigin = contactPoint.normalize();
  74358. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  74359. directionToOrigin = directionToOrigin.negate();
  74360. }
  74361. // TODO: find a more physically based solution
  74362. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  74363. var forceX = directionToOrigin.x * this._strength / 8;
  74364. var forceY = directionToOrigin.y * this._updraftMultiplier;
  74365. var forceZ = directionToOrigin.z * this._strength / 8;
  74366. }
  74367. else {
  74368. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  74369. var forceY = this._originTop.y * this._updraftMultiplier;
  74370. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  74371. }
  74372. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  74373. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  74374. return { force: force, contactPoint: impostorObjectCenter };
  74375. };
  74376. PhysicsVortexEvent.prototype._tick = function () {
  74377. var _this = this;
  74378. this._physicsEngine.getImpostors().forEach(function (impostor) {
  74379. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  74380. if (!impostorForceAndContactPoint) {
  74381. return;
  74382. }
  74383. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  74384. });
  74385. };
  74386. /*** Helpers ***/
  74387. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  74388. if (!this._cylinder) {
  74389. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  74390. height: this._height,
  74391. diameter: this._radius * 2,
  74392. }, this._scene);
  74393. this._cylinder.isVisible = false;
  74394. }
  74395. };
  74396. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  74397. var impostorObject = impostor.object;
  74398. this._prepareCylinder();
  74399. this._cylinder.position = this._cylinderPosition;
  74400. return this._cylinder.intersectsMesh(impostorObject, true);
  74401. };
  74402. return PhysicsVortexEvent;
  74403. }());
  74404. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  74405. /***** Enums *****/
  74406. /**
  74407. * The strenght of the force in correspondence to the distance of the affected object
  74408. */
  74409. var PhysicsRadialImpulseFalloff;
  74410. (function (PhysicsRadialImpulseFalloff) {
  74411. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  74412. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear"; // impulse gets weaker if it's further from the origin
  74413. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  74414. /**
  74415. * The strenght of the force in correspondence to the distance of the affected object
  74416. */
  74417. var PhysicsUpdraftMode;
  74418. (function (PhysicsUpdraftMode) {
  74419. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  74420. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular"; // once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder
  74421. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  74422. })(BABYLON || (BABYLON = {}));
  74423. //# sourceMappingURL=babylon.physicsHelper.js.map
  74424. var BABYLON;
  74425. (function (BABYLON) {
  74426. var CannonJSPlugin = /** @class */ (function () {
  74427. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  74428. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  74429. if (iterations === void 0) { iterations = 10; }
  74430. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  74431. this.name = "CannonJSPlugin";
  74432. this._physicsMaterials = new Array();
  74433. this._fixedTimeStep = 1 / 60;
  74434. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  74435. this.BJSCANNON = typeof CANNON !== 'undefined' ? CANNON : (typeof require !== 'undefined' ? require('cannon') : undefined);
  74436. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  74437. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  74438. this._tmpPosition = BABYLON.Vector3.Zero();
  74439. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  74440. this._tmpUnityRotation = new BABYLON.Quaternion();
  74441. if (!this.isSupported()) {
  74442. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  74443. return;
  74444. }
  74445. this._extendNamespace();
  74446. this.world = new this.BJSCANNON.World();
  74447. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  74448. this.world.solver.iterations = iterations;
  74449. }
  74450. CannonJSPlugin.prototype.setGravity = function (gravity) {
  74451. this.world.gravity.copy(gravity);
  74452. };
  74453. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  74454. this._fixedTimeStep = timeStep;
  74455. };
  74456. CannonJSPlugin.prototype.getTimeStep = function () {
  74457. return this._fixedTimeStep;
  74458. };
  74459. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  74460. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  74461. };
  74462. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  74463. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  74464. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  74465. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  74466. };
  74467. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  74468. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  74469. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  74470. impostor.physicsBody.applyForce(impulse, worldPoint);
  74471. };
  74472. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  74473. //parent-child relationship. Does this impostor has a parent impostor?
  74474. if (impostor.parent) {
  74475. if (impostor.physicsBody) {
  74476. this.removePhysicsBody(impostor);
  74477. //TODO is that needed?
  74478. impostor.forceUpdate();
  74479. }
  74480. return;
  74481. }
  74482. //should a new body be created for this impostor?
  74483. if (impostor.isBodyInitRequired()) {
  74484. var shape = this._createShape(impostor);
  74485. //unregister events, if body is being changed
  74486. var oldBody = impostor.physicsBody;
  74487. if (oldBody) {
  74488. this.removePhysicsBody(impostor);
  74489. }
  74490. //create the body and material
  74491. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  74492. var bodyCreationObject = {
  74493. mass: impostor.getParam("mass"),
  74494. material: material
  74495. };
  74496. // A simple extend, in case native options were used.
  74497. var nativeOptions = impostor.getParam("nativeOptions");
  74498. for (var key in nativeOptions) {
  74499. if (nativeOptions.hasOwnProperty(key)) {
  74500. bodyCreationObject[key] = nativeOptions[key];
  74501. }
  74502. }
  74503. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  74504. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  74505. this.world.addEventListener("preStep", impostor.beforeStep);
  74506. this.world.addEventListener("postStep", impostor.afterStep);
  74507. impostor.physicsBody.addShape(shape);
  74508. this.world.add(impostor.physicsBody);
  74509. //try to keep the body moving in the right direction by taking old properties.
  74510. //Should be tested!
  74511. if (oldBody) {
  74512. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  74513. impostor.physicsBody[param].copy(oldBody[param]);
  74514. });
  74515. }
  74516. this._processChildMeshes(impostor);
  74517. }
  74518. //now update the body's transformation
  74519. this._updatePhysicsBodyTransformation(impostor);
  74520. };
  74521. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  74522. var _this = this;
  74523. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  74524. var currentRotation = mainImpostor.object.rotationQuaternion;
  74525. if (meshChildren.length) {
  74526. var processMesh = function (localPosition, mesh) {
  74527. if (!currentRotation || !mesh.rotationQuaternion) {
  74528. return;
  74529. }
  74530. var childImpostor = mesh.getPhysicsImpostor();
  74531. if (childImpostor) {
  74532. var parent = childImpostor.parent;
  74533. if (parent !== mainImpostor) {
  74534. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  74535. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  74536. if (childImpostor.physicsBody) {
  74537. _this.removePhysicsBody(childImpostor);
  74538. childImpostor.physicsBody = null;
  74539. }
  74540. childImpostor.parent = mainImpostor;
  74541. childImpostor.resetUpdateFlags();
  74542. 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));
  74543. //Add the mass of the children.
  74544. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  74545. }
  74546. }
  74547. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  74548. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  74549. };
  74550. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  74551. }
  74552. };
  74553. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  74554. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  74555. this.world.removeEventListener("preStep", impostor.beforeStep);
  74556. this.world.removeEventListener("postStep", impostor.afterStep);
  74557. this.world.remove(impostor.physicsBody);
  74558. };
  74559. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  74560. var mainBody = impostorJoint.mainImpostor.physicsBody;
  74561. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  74562. if (!mainBody || !connectedBody) {
  74563. return;
  74564. }
  74565. var constraint;
  74566. var jointData = impostorJoint.joint.jointData;
  74567. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  74568. var constraintData = {
  74569. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  74570. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  74571. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  74572. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  74573. maxForce: jointData.nativeParams.maxForce,
  74574. collideConnected: !!jointData.collision
  74575. };
  74576. switch (impostorJoint.joint.type) {
  74577. case BABYLON.PhysicsJoint.HingeJoint:
  74578. case BABYLON.PhysicsJoint.Hinge2Joint:
  74579. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  74580. break;
  74581. case BABYLON.PhysicsJoint.DistanceJoint:
  74582. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  74583. break;
  74584. case BABYLON.PhysicsJoint.SpringJoint:
  74585. var springData = jointData;
  74586. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  74587. restLength: springData.length,
  74588. stiffness: springData.stiffness,
  74589. damping: springData.damping,
  74590. localAnchorA: constraintData.pivotA,
  74591. localAnchorB: constraintData.pivotB
  74592. });
  74593. break;
  74594. case BABYLON.PhysicsJoint.LockJoint:
  74595. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  74596. break;
  74597. case BABYLON.PhysicsJoint.PointToPointJoint:
  74598. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  74599. default:
  74600. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  74601. break;
  74602. }
  74603. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  74604. constraint.collideConnected = !!jointData.collision;
  74605. impostorJoint.joint.physicsJoint = constraint;
  74606. //don't add spring as constraint, as it is not one.
  74607. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  74608. this.world.addConstraint(constraint);
  74609. }
  74610. else {
  74611. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  74612. constraint.applyForce();
  74613. });
  74614. }
  74615. };
  74616. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  74617. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  74618. };
  74619. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  74620. var index;
  74621. var mat;
  74622. for (index = 0; index < this._physicsMaterials.length; index++) {
  74623. mat = this._physicsMaterials[index];
  74624. if (mat.friction === friction && mat.restitution === restitution) {
  74625. return mat;
  74626. }
  74627. }
  74628. var currentMat = new this.BJSCANNON.Material(name);
  74629. currentMat.friction = friction;
  74630. currentMat.restitution = restitution;
  74631. this._physicsMaterials.push(currentMat);
  74632. return currentMat;
  74633. };
  74634. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  74635. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  74636. };
  74637. CannonJSPlugin.prototype._createShape = function (impostor) {
  74638. var object = impostor.object;
  74639. var returnValue;
  74640. var extendSize = impostor.getObjectExtendSize();
  74641. switch (impostor.type) {
  74642. case BABYLON.PhysicsImpostor.SphereImpostor:
  74643. var radiusX = extendSize.x;
  74644. var radiusY = extendSize.y;
  74645. var radiusZ = extendSize.z;
  74646. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  74647. break;
  74648. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  74649. case BABYLON.PhysicsImpostor.CylinderImpostor:
  74650. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  74651. break;
  74652. case BABYLON.PhysicsImpostor.BoxImpostor:
  74653. var box = extendSize.scale(0.5);
  74654. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  74655. break;
  74656. case BABYLON.PhysicsImpostor.PlaneImpostor:
  74657. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  74658. returnValue = new this.BJSCANNON.Plane();
  74659. break;
  74660. case BABYLON.PhysicsImpostor.MeshImpostor:
  74661. // should transform the vertex data to world coordinates!!
  74662. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  74663. var rawFaces = object.getIndices ? object.getIndices() : [];
  74664. if (!rawVerts)
  74665. return;
  74666. // get only scale! so the object could transform correctly.
  74667. var oldPosition = object.position.clone();
  74668. var oldRotation = object.rotation && object.rotation.clone();
  74669. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  74670. object.position.copyFromFloats(0, 0, 0);
  74671. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  74672. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  74673. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  74674. var transform = object.computeWorldMatrix(true);
  74675. // convert rawVerts to object space
  74676. var temp = new Array();
  74677. var index;
  74678. for (index = 0; index < rawVerts.length; index += 3) {
  74679. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  74680. }
  74681. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  74682. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  74683. //now set back the transformation!
  74684. object.position.copyFrom(oldPosition);
  74685. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  74686. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  74687. break;
  74688. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  74689. var oldPosition2 = object.position.clone();
  74690. var oldRotation2 = object.rotation && object.rotation.clone();
  74691. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  74692. object.position.copyFromFloats(0, 0, 0);
  74693. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  74694. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  74695. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  74696. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  74697. returnValue = this._createHeightmap(object);
  74698. object.position.copyFrom(oldPosition2);
  74699. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  74700. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  74701. object.computeWorldMatrix(true);
  74702. break;
  74703. case BABYLON.PhysicsImpostor.ParticleImpostor:
  74704. returnValue = new this.BJSCANNON.Particle();
  74705. break;
  74706. }
  74707. return returnValue;
  74708. };
  74709. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  74710. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  74711. var transform = object.computeWorldMatrix(true);
  74712. // convert rawVerts to object space
  74713. var temp = new Array();
  74714. var index;
  74715. for (index = 0; index < pos.length; index += 3) {
  74716. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  74717. }
  74718. pos = temp;
  74719. var matrix = new Array();
  74720. //For now pointDepth will not be used and will be automatically calculated.
  74721. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  74722. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  74723. var boundingInfo = object.getBoundingInfo();
  74724. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  74725. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  74726. var elementSize = dim * 2 / arraySize;
  74727. for (var i = 0; i < pos.length; i = i + 3) {
  74728. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  74729. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  74730. var y = -pos[i + 2] + minY;
  74731. if (!matrix[x]) {
  74732. matrix[x] = [];
  74733. }
  74734. if (!matrix[x][z]) {
  74735. matrix[x][z] = y;
  74736. }
  74737. matrix[x][z] = Math.max(y, matrix[x][z]);
  74738. }
  74739. for (var x = 0; x <= arraySize; ++x) {
  74740. if (!matrix[x]) {
  74741. var loc = 1;
  74742. while (!matrix[(x + loc) % arraySize]) {
  74743. loc++;
  74744. }
  74745. matrix[x] = matrix[(x + loc) % arraySize].slice();
  74746. //console.log("missing x", x);
  74747. }
  74748. for (var z = 0; z <= arraySize; ++z) {
  74749. if (!matrix[x][z]) {
  74750. var loc = 1;
  74751. var newValue;
  74752. while (newValue === undefined) {
  74753. newValue = matrix[x][(z + loc++) % arraySize];
  74754. }
  74755. matrix[x][z] = newValue;
  74756. }
  74757. }
  74758. }
  74759. var shape = new this.BJSCANNON.Heightfield(matrix, {
  74760. elementSize: elementSize
  74761. });
  74762. //For future reference, needed for body transformation
  74763. shape.minY = minY;
  74764. return shape;
  74765. };
  74766. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  74767. var object = impostor.object;
  74768. //make sure it is updated...
  74769. object.computeWorldMatrix && object.computeWorldMatrix(true);
  74770. // The delta between the mesh position and the mesh bounding box center
  74771. var bInfo = object.getBoundingInfo();
  74772. if (!bInfo)
  74773. return;
  74774. var center = impostor.getObjectCenter();
  74775. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  74776. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  74777. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  74778. this._tmpPosition.copyFrom(center);
  74779. var quaternion = object.rotationQuaternion;
  74780. if (!quaternion) {
  74781. return;
  74782. }
  74783. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  74784. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  74785. //-90 DEG in X, precalculated
  74786. quaternion = quaternion.multiply(this._minus90X);
  74787. //Invert! (Precalculated, 90 deg in X)
  74788. //No need to clone. this will never change.
  74789. impostor.setDeltaRotation(this._plus90X);
  74790. }
  74791. //If it is a heightfield, if should be centered.
  74792. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  74793. var mesh = object;
  74794. var boundingInfo = mesh.getBoundingInfo();
  74795. //calculate the correct body position:
  74796. var rotationQuaternion = mesh.rotationQuaternion;
  74797. mesh.rotationQuaternion = this._tmpUnityRotation;
  74798. mesh.computeWorldMatrix(true);
  74799. //get original center with no rotation
  74800. var c = center.clone();
  74801. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  74802. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  74803. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  74804. mesh.setPreTransformMatrix(p);
  74805. mesh.computeWorldMatrix(true);
  74806. //calculate the translation
  74807. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  74808. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  74809. //add it inverted to the delta
  74810. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  74811. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  74812. //rotation is back
  74813. mesh.rotationQuaternion = rotationQuaternion;
  74814. mesh.setPreTransformMatrix(oldPivot);
  74815. mesh.computeWorldMatrix(true);
  74816. }
  74817. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  74818. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  74819. //this._tmpPosition.copyFrom(object.position);
  74820. }
  74821. impostor.setDeltaPosition(this._tmpDeltaPosition);
  74822. //Now update the impostor object
  74823. impostor.physicsBody.position.copy(this._tmpPosition);
  74824. impostor.physicsBody.quaternion.copy(quaternion);
  74825. };
  74826. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  74827. impostor.object.position.copyFrom(impostor.physicsBody.position);
  74828. if (impostor.object.rotationQuaternion) {
  74829. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  74830. }
  74831. };
  74832. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  74833. impostor.physicsBody.position.copy(newPosition);
  74834. impostor.physicsBody.quaternion.copy(newRotation);
  74835. };
  74836. CannonJSPlugin.prototype.isSupported = function () {
  74837. return this.BJSCANNON !== undefined;
  74838. };
  74839. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  74840. impostor.physicsBody.velocity.copy(velocity);
  74841. };
  74842. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  74843. impostor.physicsBody.angularVelocity.copy(velocity);
  74844. };
  74845. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  74846. var v = impostor.physicsBody.velocity;
  74847. if (!v) {
  74848. return null;
  74849. }
  74850. return new BABYLON.Vector3(v.x, v.y, v.z);
  74851. };
  74852. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  74853. var v = impostor.physicsBody.angularVelocity;
  74854. if (!v) {
  74855. return null;
  74856. }
  74857. return new BABYLON.Vector3(v.x, v.y, v.z);
  74858. };
  74859. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  74860. impostor.physicsBody.mass = mass;
  74861. impostor.physicsBody.updateMassProperties();
  74862. };
  74863. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  74864. return impostor.physicsBody.mass;
  74865. };
  74866. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  74867. return impostor.physicsBody.material.friction;
  74868. };
  74869. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  74870. impostor.physicsBody.material.friction = friction;
  74871. };
  74872. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  74873. return impostor.physicsBody.material.restitution;
  74874. };
  74875. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  74876. impostor.physicsBody.material.restitution = restitution;
  74877. };
  74878. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  74879. impostor.physicsBody.sleep();
  74880. };
  74881. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  74882. impostor.physicsBody.wakeUp();
  74883. };
  74884. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  74885. joint.physicsJoint.distance = maxDistance;
  74886. };
  74887. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  74888. // if (!motorIndex) {
  74889. // joint.physicsJoint.enableMotor();
  74890. // }
  74891. // }
  74892. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  74893. // if (!motorIndex) {
  74894. // joint.physicsJoint.disableMotor();
  74895. // }
  74896. // }
  74897. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  74898. if (!motorIndex) {
  74899. joint.physicsJoint.enableMotor();
  74900. joint.physicsJoint.setMotorSpeed(speed);
  74901. if (maxForce) {
  74902. this.setLimit(joint, maxForce);
  74903. }
  74904. }
  74905. };
  74906. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  74907. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  74908. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  74909. };
  74910. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  74911. var body = impostor.physicsBody;
  74912. mesh.position.x = body.position.x;
  74913. mesh.position.y = body.position.y;
  74914. mesh.position.z = body.position.z;
  74915. if (mesh.rotationQuaternion) {
  74916. mesh.rotationQuaternion.x = body.quaternion.x;
  74917. mesh.rotationQuaternion.y = body.quaternion.y;
  74918. mesh.rotationQuaternion.z = body.quaternion.z;
  74919. mesh.rotationQuaternion.w = body.quaternion.w;
  74920. }
  74921. };
  74922. CannonJSPlugin.prototype.getRadius = function (impostor) {
  74923. var shape = impostor.physicsBody.shapes[0];
  74924. return shape.boundingSphereRadius;
  74925. };
  74926. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  74927. var shape = impostor.physicsBody.shapes[0];
  74928. result.x = shape.halfExtents.x * 2;
  74929. result.y = shape.halfExtents.y * 2;
  74930. result.z = shape.halfExtents.z * 2;
  74931. };
  74932. CannonJSPlugin.prototype.dispose = function () {
  74933. };
  74934. CannonJSPlugin.prototype._extendNamespace = function () {
  74935. //this will force cannon to execute at least one step when using interpolation
  74936. var step_tmp1 = new this.BJSCANNON.Vec3();
  74937. var Engine = this.BJSCANNON;
  74938. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  74939. maxSubSteps = maxSubSteps || 10;
  74940. timeSinceLastCalled = timeSinceLastCalled || 0;
  74941. if (timeSinceLastCalled === 0) {
  74942. this.internalStep(dt);
  74943. this.time += dt;
  74944. }
  74945. else {
  74946. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  74947. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  74948. var t0 = performance.now();
  74949. for (var i = 0; i !== internalSteps; i++) {
  74950. this.internalStep(dt);
  74951. if (performance.now() - t0 > dt * 1000) {
  74952. break;
  74953. }
  74954. }
  74955. this.time += timeSinceLastCalled;
  74956. var h = this.time % dt;
  74957. var h_div_dt = h / dt;
  74958. var interpvelo = step_tmp1;
  74959. var bodies = this.bodies;
  74960. for (var j = 0; j !== bodies.length; j++) {
  74961. var b = bodies[j];
  74962. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  74963. b.position.vsub(b.previousPosition, interpvelo);
  74964. interpvelo.scale(h_div_dt, interpvelo);
  74965. b.position.vadd(interpvelo, b.interpolatedPosition);
  74966. }
  74967. else {
  74968. b.interpolatedPosition.copy(b.position);
  74969. b.interpolatedQuaternion.copy(b.quaternion);
  74970. }
  74971. }
  74972. }
  74973. };
  74974. };
  74975. return CannonJSPlugin;
  74976. }());
  74977. BABYLON.CannonJSPlugin = CannonJSPlugin;
  74978. })(BABYLON || (BABYLON = {}));
  74979. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  74980. var BABYLON;
  74981. (function (BABYLON) {
  74982. var OimoJSPlugin = /** @class */ (function () {
  74983. function OimoJSPlugin(iterations) {
  74984. this.name = "OimoJSPlugin";
  74985. this._tmpImpostorsArray = [];
  74986. this._tmpPositionVector = BABYLON.Vector3.Zero();
  74987. this.BJSOIMO = typeof OIMO !== 'undefined' ? OIMO : (typeof require !== 'undefined' ? require('./Oimo') : undefined);
  74988. this.world = new this.BJSOIMO.World(1 / 60, 2, iterations, true);
  74989. this.world.worldscale(1);
  74990. this.world.clear();
  74991. //making sure no stats are calculated
  74992. this.world.isNoStat = true;
  74993. }
  74994. OimoJSPlugin.prototype.setGravity = function (gravity) {
  74995. this.world.gravity.copy(gravity);
  74996. };
  74997. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  74998. this.world.timeStep = timeStep;
  74999. };
  75000. OimoJSPlugin.prototype.getTimeStep = function () {
  75001. return this.world.timeStep;
  75002. };
  75003. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  75004. var _this = this;
  75005. impostors.forEach(function (impostor) {
  75006. impostor.beforeStep();
  75007. });
  75008. this.world.step();
  75009. impostors.forEach(function (impostor) {
  75010. impostor.afterStep();
  75011. //update the ordered impostors array
  75012. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  75013. });
  75014. //check for collisions
  75015. var contact = this.world.contacts;
  75016. while (contact !== null) {
  75017. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  75018. contact = contact.next;
  75019. continue;
  75020. }
  75021. //is this body colliding with any other? get the impostor
  75022. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  75023. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  75024. if (!mainImpostor || !collidingImpostor) {
  75025. contact = contact.next;
  75026. continue;
  75027. }
  75028. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  75029. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  75030. contact = contact.next;
  75031. }
  75032. };
  75033. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  75034. var mass = impostor.physicsBody.massInfo.mass;
  75035. impostor.physicsBody.applyImpulse(contactPoint.scale(this.BJSOIMO.INV_SCALE), force.scale(this.BJSOIMO.INV_SCALE * mass));
  75036. };
  75037. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  75038. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  75039. this.applyImpulse(impostor, force, contactPoint);
  75040. };
  75041. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  75042. var _this = this;
  75043. //parent-child relationship. Does this impostor has a parent impostor?
  75044. if (impostor.parent) {
  75045. if (impostor.physicsBody) {
  75046. this.removePhysicsBody(impostor);
  75047. //TODO is that needed?
  75048. impostor.forceUpdate();
  75049. }
  75050. return;
  75051. }
  75052. if (impostor.isBodyInitRequired()) {
  75053. var bodyConfig = {
  75054. name: impostor.uniqueId,
  75055. //Oimo must have mass, also for static objects.
  75056. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  75057. size: [],
  75058. type: [],
  75059. pos: [],
  75060. rot: [],
  75061. move: impostor.getParam("mass") !== 0,
  75062. //Supporting older versions of Oimo
  75063. world: this.world
  75064. };
  75065. var impostors = [impostor];
  75066. var addToArray = function (parent) {
  75067. if (!parent.getChildMeshes)
  75068. return;
  75069. parent.getChildMeshes().forEach(function (m) {
  75070. if (m.physicsImpostor) {
  75071. impostors.push(m.physicsImpostor);
  75072. //m.physicsImpostor._init();
  75073. }
  75074. });
  75075. };
  75076. addToArray(impostor.object);
  75077. var checkWithEpsilon_1 = function (value) {
  75078. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  75079. };
  75080. impostors.forEach(function (i) {
  75081. if (!impostor.object.rotationQuaternion) {
  75082. return;
  75083. }
  75084. //get the correct bounding box
  75085. var oldQuaternion = i.object.rotationQuaternion;
  75086. var rot = new _this.BJSOIMO.Euler().setFromQuaternion({
  75087. x: impostor.object.rotationQuaternion.x,
  75088. y: impostor.object.rotationQuaternion.y,
  75089. z: impostor.object.rotationQuaternion.z,
  75090. s: impostor.object.rotationQuaternion.w
  75091. });
  75092. var extendSize = i.getObjectExtendSize();
  75093. if (i === impostor) {
  75094. var center = impostor.getObjectCenter();
  75095. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  75096. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  75097. //Can also use Array.prototype.push.apply
  75098. bodyConfig.pos.push(center.x);
  75099. bodyConfig.pos.push(center.y);
  75100. bodyConfig.pos.push(center.z);
  75101. //tmp solution
  75102. bodyConfig.rot.push(rot.x / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  75103. bodyConfig.rot.push(rot.y / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  75104. bodyConfig.rot.push(rot.z / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  75105. }
  75106. else {
  75107. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  75108. bodyConfig.pos.push(localPosition.x);
  75109. bodyConfig.pos.push(localPosition.y);
  75110. bodyConfig.pos.push(localPosition.z);
  75111. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  75112. bodyConfig.rot.push(0);
  75113. bodyConfig.rot.push(0);
  75114. bodyConfig.rot.push(0);
  75115. }
  75116. // register mesh
  75117. switch (i.type) {
  75118. case BABYLON.PhysicsImpostor.ParticleImpostor:
  75119. BABYLON.Tools.Warn("No Particle support in this.BJSOIMO.js. using SphereImpostor instead");
  75120. case BABYLON.PhysicsImpostor.SphereImpostor:
  75121. var radiusX = extendSize.x;
  75122. var radiusY = extendSize.y;
  75123. var radiusZ = extendSize.z;
  75124. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  75125. bodyConfig.type.push('sphere');
  75126. //due to the way oimo works with compounds, add 3 times
  75127. bodyConfig.size.push(size);
  75128. bodyConfig.size.push(size);
  75129. bodyConfig.size.push(size);
  75130. break;
  75131. case BABYLON.PhysicsImpostor.CylinderImpostor:
  75132. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  75133. var sizeY = checkWithEpsilon_1(extendSize.y);
  75134. bodyConfig.type.push('cylinder');
  75135. bodyConfig.size.push(sizeX);
  75136. bodyConfig.size.push(sizeY);
  75137. //due to the way oimo works with compounds, add one more value.
  75138. bodyConfig.size.push(sizeY);
  75139. break;
  75140. case BABYLON.PhysicsImpostor.PlaneImpostor:
  75141. case BABYLON.PhysicsImpostor.BoxImpostor:
  75142. default:
  75143. var sizeX = checkWithEpsilon_1(extendSize.x);
  75144. var sizeY = checkWithEpsilon_1(extendSize.y);
  75145. var sizeZ = checkWithEpsilon_1(extendSize.z);
  75146. bodyConfig.type.push('box');
  75147. bodyConfig.size.push(sizeX);
  75148. bodyConfig.size.push(sizeY);
  75149. bodyConfig.size.push(sizeZ);
  75150. break;
  75151. }
  75152. //actually not needed, but hey...
  75153. i.object.rotationQuaternion = oldQuaternion;
  75154. });
  75155. impostor.physicsBody = new this.BJSOIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  75156. }
  75157. else {
  75158. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  75159. }
  75160. impostor.setDeltaPosition(this._tmpPositionVector);
  75161. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  75162. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  75163. };
  75164. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  75165. //impostor.physicsBody.dispose();
  75166. //Same as : (older oimo versions)
  75167. this.world.removeRigidBody(impostor.physicsBody);
  75168. };
  75169. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  75170. var mainBody = impostorJoint.mainImpostor.physicsBody;
  75171. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  75172. if (!mainBody || !connectedBody) {
  75173. return;
  75174. }
  75175. var jointData = impostorJoint.joint.jointData;
  75176. var options = jointData.nativeParams || {};
  75177. var type;
  75178. var nativeJointData = {
  75179. body1: mainBody,
  75180. body2: connectedBody,
  75181. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  75182. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  75183. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  75184. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  75185. min: options.min,
  75186. max: options.max,
  75187. collision: options.collision || jointData.collision,
  75188. spring: options.spring,
  75189. //supporting older version of Oimo
  75190. world: this.world
  75191. };
  75192. switch (impostorJoint.joint.type) {
  75193. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  75194. type = "jointBall";
  75195. break;
  75196. case BABYLON.PhysicsJoint.SpringJoint:
  75197. BABYLON.Tools.Warn("this.BJSOIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  75198. var springData = jointData;
  75199. nativeJointData.min = springData.length || nativeJointData.min;
  75200. //Max should also be set, just make sure it is at least min
  75201. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  75202. case BABYLON.PhysicsJoint.DistanceJoint:
  75203. type = "jointDistance";
  75204. nativeJointData.max = jointData.maxDistance;
  75205. break;
  75206. case BABYLON.PhysicsJoint.PrismaticJoint:
  75207. type = "jointPrisme";
  75208. break;
  75209. case BABYLON.PhysicsJoint.SliderJoint:
  75210. type = "jointSlide";
  75211. break;
  75212. case BABYLON.PhysicsJoint.WheelJoint:
  75213. type = "jointWheel";
  75214. break;
  75215. case BABYLON.PhysicsJoint.HingeJoint:
  75216. default:
  75217. type = "jointHinge";
  75218. break;
  75219. }
  75220. nativeJointData.type = type;
  75221. impostorJoint.joint.physicsJoint = new this.BJSOIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  75222. };
  75223. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  75224. //Bug in Oimo prevents us from disposing a joint in the playground
  75225. //joint.joint.physicsJoint.dispose();
  75226. //So we will bruteforce it!
  75227. try {
  75228. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  75229. }
  75230. catch (e) {
  75231. BABYLON.Tools.Warn(e);
  75232. }
  75233. };
  75234. OimoJSPlugin.prototype.isSupported = function () {
  75235. return this.BJSOIMO !== undefined;
  75236. };
  75237. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  75238. if (!impostor.physicsBody.sleeping) {
  75239. //TODO check that
  75240. if (impostor.physicsBody.shapes.next) {
  75241. var parentShape = this._getLastShape(impostor.physicsBody);
  75242. impostor.object.position.x = parentShape.position.x * this.BJSOIMO.WORLD_SCALE;
  75243. impostor.object.position.y = parentShape.position.y * this.BJSOIMO.WORLD_SCALE;
  75244. impostor.object.position.z = parentShape.position.z * this.BJSOIMO.WORLD_SCALE;
  75245. }
  75246. else {
  75247. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  75248. }
  75249. if (impostor.object.rotationQuaternion) {
  75250. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  75251. impostor.object.rotationQuaternion.normalize();
  75252. }
  75253. }
  75254. };
  75255. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  75256. var body = impostor.physicsBody;
  75257. body.position.init(newPosition.x * this.BJSOIMO.INV_SCALE, newPosition.y * this.BJSOIMO.INV_SCALE, newPosition.z * this.BJSOIMO.INV_SCALE);
  75258. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  75259. body.syncShapes();
  75260. body.awake();
  75261. };
  75262. OimoJSPlugin.prototype._getLastShape = function (body) {
  75263. var lastShape = body.shapes;
  75264. while (lastShape.next) {
  75265. lastShape = lastShape.next;
  75266. }
  75267. return lastShape;
  75268. };
  75269. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  75270. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  75271. };
  75272. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  75273. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  75274. };
  75275. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  75276. var v = impostor.physicsBody.linearVelocity;
  75277. if (!v) {
  75278. return null;
  75279. }
  75280. return new BABYLON.Vector3(v.x, v.y, v.z);
  75281. };
  75282. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  75283. var v = impostor.physicsBody.angularVelocity;
  75284. if (!v) {
  75285. return null;
  75286. }
  75287. return new BABYLON.Vector3(v.x, v.y, v.z);
  75288. };
  75289. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  75290. var staticBody = mass === 0;
  75291. //this will actually set the body's density and not its mass.
  75292. //But this is how oimo treats the mass variable.
  75293. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  75294. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  75295. };
  75296. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  75297. return impostor.physicsBody.shapes.density;
  75298. };
  75299. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  75300. return impostor.physicsBody.shapes.friction;
  75301. };
  75302. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  75303. impostor.physicsBody.shapes.friction = friction;
  75304. };
  75305. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  75306. return impostor.physicsBody.shapes.restitution;
  75307. };
  75308. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  75309. impostor.physicsBody.shapes.restitution = restitution;
  75310. };
  75311. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  75312. impostor.physicsBody.sleep();
  75313. };
  75314. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  75315. impostor.physicsBody.awake();
  75316. };
  75317. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  75318. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  75319. if (minDistance !== void 0) {
  75320. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  75321. }
  75322. };
  75323. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  75324. //TODO separate rotational and transational motors.
  75325. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  75326. if (motor) {
  75327. motor.setMotor(speed, maxForce);
  75328. }
  75329. };
  75330. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  75331. //TODO separate rotational and transational motors.
  75332. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  75333. if (motor) {
  75334. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  75335. }
  75336. };
  75337. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  75338. var body = impostor.physicsBody;
  75339. mesh.position.x = body.position.x;
  75340. mesh.position.y = body.position.y;
  75341. mesh.position.z = body.position.z;
  75342. if (mesh.rotationQuaternion) {
  75343. mesh.rotationQuaternion.x = body.orientation.x;
  75344. mesh.rotationQuaternion.y = body.orientation.y;
  75345. mesh.rotationQuaternion.z = body.orientation.z;
  75346. mesh.rotationQuaternion.w = body.orientation.s;
  75347. }
  75348. };
  75349. OimoJSPlugin.prototype.getRadius = function (impostor) {
  75350. return impostor.physicsBody.shapes.radius;
  75351. };
  75352. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  75353. var shape = impostor.physicsBody.shapes;
  75354. result.x = shape.halfWidth * 2;
  75355. result.y = shape.halfHeight * 2;
  75356. result.z = shape.halfDepth * 2;
  75357. };
  75358. OimoJSPlugin.prototype.dispose = function () {
  75359. this.world.clear();
  75360. };
  75361. return OimoJSPlugin;
  75362. }());
  75363. BABYLON.OimoJSPlugin = OimoJSPlugin;
  75364. })(BABYLON || (BABYLON = {}));
  75365. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  75366. var BABYLON;
  75367. (function (BABYLON) {
  75368. /*
  75369. * Based on jsTGALoader - Javascript loader for TGA file
  75370. * By Vincent Thibault
  75371. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  75372. */
  75373. var TGATools = /** @class */ (function () {
  75374. function TGATools() {
  75375. }
  75376. TGATools.GetTGAHeader = function (data) {
  75377. var offset = 0;
  75378. var header = {
  75379. id_length: data[offset++],
  75380. colormap_type: data[offset++],
  75381. image_type: data[offset++],
  75382. colormap_index: data[offset++] | data[offset++] << 8,
  75383. colormap_length: data[offset++] | data[offset++] << 8,
  75384. colormap_size: data[offset++],
  75385. origin: [
  75386. data[offset++] | data[offset++] << 8,
  75387. data[offset++] | data[offset++] << 8
  75388. ],
  75389. width: data[offset++] | data[offset++] << 8,
  75390. height: data[offset++] | data[offset++] << 8,
  75391. pixel_size: data[offset++],
  75392. flags: data[offset++]
  75393. };
  75394. return header;
  75395. };
  75396. TGATools.UploadContent = function (gl, data) {
  75397. // Not enough data to contain header ?
  75398. if (data.length < 19) {
  75399. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  75400. return;
  75401. }
  75402. // Read Header
  75403. var offset = 18;
  75404. var header = TGATools.GetTGAHeader(data);
  75405. // Assume it's a valid Targa file.
  75406. if (header.id_length + offset > data.length) {
  75407. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  75408. return;
  75409. }
  75410. // Skip not needed data
  75411. offset += header.id_length;
  75412. var use_rle = false;
  75413. var use_pal = false;
  75414. var use_grey = false;
  75415. // Get some informations.
  75416. switch (header.image_type) {
  75417. case TGATools._TYPE_RLE_INDEXED:
  75418. use_rle = true;
  75419. case TGATools._TYPE_INDEXED:
  75420. use_pal = true;
  75421. break;
  75422. case TGATools._TYPE_RLE_RGB:
  75423. use_rle = true;
  75424. case TGATools._TYPE_RGB:
  75425. // use_rgb = true;
  75426. break;
  75427. case TGATools._TYPE_RLE_GREY:
  75428. use_rle = true;
  75429. case TGATools._TYPE_GREY:
  75430. use_grey = true;
  75431. break;
  75432. }
  75433. var pixel_data;
  75434. // var numAlphaBits = header.flags & 0xf;
  75435. var pixel_size = header.pixel_size >> 3;
  75436. var pixel_total = header.width * header.height * pixel_size;
  75437. // Read palettes
  75438. var palettes;
  75439. if (use_pal) {
  75440. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  75441. }
  75442. // Read LRE
  75443. if (use_rle) {
  75444. pixel_data = new Uint8Array(pixel_total);
  75445. var c, count, i;
  75446. var localOffset = 0;
  75447. var pixels = new Uint8Array(pixel_size);
  75448. while (offset < pixel_total && localOffset < pixel_total) {
  75449. c = data[offset++];
  75450. count = (c & 0x7f) + 1;
  75451. // RLE pixels
  75452. if (c & 0x80) {
  75453. // Bind pixel tmp array
  75454. for (i = 0; i < pixel_size; ++i) {
  75455. pixels[i] = data[offset++];
  75456. }
  75457. // Copy pixel array
  75458. for (i = 0; i < count; ++i) {
  75459. pixel_data.set(pixels, localOffset + i * pixel_size);
  75460. }
  75461. localOffset += pixel_size * count;
  75462. }
  75463. else {
  75464. count *= pixel_size;
  75465. for (i = 0; i < count; ++i) {
  75466. pixel_data[localOffset + i] = data[offset++];
  75467. }
  75468. localOffset += count;
  75469. }
  75470. }
  75471. }
  75472. else {
  75473. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  75474. }
  75475. // Load to texture
  75476. var x_start, y_start, x_step, y_step, y_end, x_end;
  75477. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  75478. default:
  75479. case TGATools._ORIGIN_UL:
  75480. x_start = 0;
  75481. x_step = 1;
  75482. x_end = header.width;
  75483. y_start = 0;
  75484. y_step = 1;
  75485. y_end = header.height;
  75486. break;
  75487. case TGATools._ORIGIN_BL:
  75488. x_start = 0;
  75489. x_step = 1;
  75490. x_end = header.width;
  75491. y_start = header.height - 1;
  75492. y_step = -1;
  75493. y_end = -1;
  75494. break;
  75495. case TGATools._ORIGIN_UR:
  75496. x_start = header.width - 1;
  75497. x_step = -1;
  75498. x_end = -1;
  75499. y_start = 0;
  75500. y_step = 1;
  75501. y_end = header.height;
  75502. break;
  75503. case TGATools._ORIGIN_BR:
  75504. x_start = header.width - 1;
  75505. x_step = -1;
  75506. x_end = -1;
  75507. y_start = header.height - 1;
  75508. y_step = -1;
  75509. y_end = -1;
  75510. break;
  75511. }
  75512. // Load the specify method
  75513. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  75514. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  75515. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  75516. };
  75517. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  75518. var image = pixel_data, colormap = palettes;
  75519. var width = header.width, height = header.height;
  75520. var color, i = 0, x, y;
  75521. var imageData = new Uint8Array(width * height * 4);
  75522. for (y = y_start; y !== y_end; y += y_step) {
  75523. for (x = x_start; x !== x_end; x += x_step, i++) {
  75524. color = image[i];
  75525. imageData[(x + width * y) * 4 + 3] = 255;
  75526. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  75527. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  75528. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  75529. }
  75530. }
  75531. return imageData;
  75532. };
  75533. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  75534. var image = pixel_data;
  75535. var width = header.width, height = header.height;
  75536. var color, i = 0, x, y;
  75537. var imageData = new Uint8Array(width * height * 4);
  75538. for (y = y_start; y !== y_end; y += y_step) {
  75539. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  75540. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  75541. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  75542. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  75543. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  75544. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  75545. }
  75546. }
  75547. return imageData;
  75548. };
  75549. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  75550. var image = pixel_data;
  75551. var width = header.width, height = header.height;
  75552. var i = 0, x, y;
  75553. var imageData = new Uint8Array(width * height * 4);
  75554. for (y = y_start; y !== y_end; y += y_step) {
  75555. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  75556. imageData[(x + width * y) * 4 + 3] = 255;
  75557. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  75558. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  75559. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  75560. }
  75561. }
  75562. return imageData;
  75563. };
  75564. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  75565. var image = pixel_data;
  75566. var width = header.width, height = header.height;
  75567. var i = 0, x, y;
  75568. var imageData = new Uint8Array(width * height * 4);
  75569. for (y = y_start; y !== y_end; y += y_step) {
  75570. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  75571. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  75572. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  75573. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  75574. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  75575. }
  75576. }
  75577. return imageData;
  75578. };
  75579. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  75580. var image = pixel_data;
  75581. var width = header.width, height = header.height;
  75582. var color, i = 0, x, y;
  75583. var imageData = new Uint8Array(width * height * 4);
  75584. for (y = y_start; y !== y_end; y += y_step) {
  75585. for (x = x_start; x !== x_end; x += x_step, i++) {
  75586. color = image[i];
  75587. imageData[(x + width * y) * 4 + 0] = color;
  75588. imageData[(x + width * y) * 4 + 1] = color;
  75589. imageData[(x + width * y) * 4 + 2] = color;
  75590. imageData[(x + width * y) * 4 + 3] = 255;
  75591. }
  75592. }
  75593. return imageData;
  75594. };
  75595. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  75596. var image = pixel_data;
  75597. var width = header.width, height = header.height;
  75598. var i = 0, x, y;
  75599. var imageData = new Uint8Array(width * height * 4);
  75600. for (y = y_start; y !== y_end; y += y_step) {
  75601. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  75602. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  75603. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  75604. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  75605. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  75606. }
  75607. }
  75608. return imageData;
  75609. };
  75610. //private static _TYPE_NO_DATA = 0;
  75611. TGATools._TYPE_INDEXED = 1;
  75612. TGATools._TYPE_RGB = 2;
  75613. TGATools._TYPE_GREY = 3;
  75614. TGATools._TYPE_RLE_INDEXED = 9;
  75615. TGATools._TYPE_RLE_RGB = 10;
  75616. TGATools._TYPE_RLE_GREY = 11;
  75617. TGATools._ORIGIN_MASK = 0x30;
  75618. TGATools._ORIGIN_SHIFT = 0x04;
  75619. TGATools._ORIGIN_BL = 0x00;
  75620. TGATools._ORIGIN_BR = 0x01;
  75621. TGATools._ORIGIN_UL = 0x02;
  75622. TGATools._ORIGIN_UR = 0x03;
  75623. return TGATools;
  75624. }());
  75625. BABYLON.TGATools = TGATools;
  75626. })(BABYLON || (BABYLON = {}));
  75627. //# sourceMappingURL=babylon.tga.js.map
  75628. var BABYLON;
  75629. (function (BABYLON) {
  75630. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  75631. // All values and structures referenced from:
  75632. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  75633. var DDS_MAGIC = 0x20534444;
  75634. var
  75635. //DDSD_CAPS = 0x1,
  75636. //DDSD_HEIGHT = 0x2,
  75637. //DDSD_WIDTH = 0x4,
  75638. //DDSD_PITCH = 0x8,
  75639. //DDSD_PIXELFORMAT = 0x1000,
  75640. DDSD_MIPMAPCOUNT = 0x20000;
  75641. //DDSD_LINEARSIZE = 0x80000,
  75642. //DDSD_DEPTH = 0x800000;
  75643. // var DDSCAPS_COMPLEX = 0x8,
  75644. // DDSCAPS_MIPMAP = 0x400000,
  75645. // DDSCAPS_TEXTURE = 0x1000;
  75646. var DDSCAPS2_CUBEMAP = 0x200;
  75647. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  75648. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  75649. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  75650. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  75651. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  75652. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  75653. // DDSCAPS2_VOLUME = 0x200000;
  75654. var
  75655. //DDPF_ALPHAPIXELS = 0x1,
  75656. //DDPF_ALPHA = 0x2,
  75657. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  75658. //DDPF_YUV = 0x200,
  75659. DDPF_LUMINANCE = 0x20000;
  75660. function FourCCToInt32(value) {
  75661. return value.charCodeAt(0) +
  75662. (value.charCodeAt(1) << 8) +
  75663. (value.charCodeAt(2) << 16) +
  75664. (value.charCodeAt(3) << 24);
  75665. }
  75666. function Int32ToFourCC(value) {
  75667. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  75668. }
  75669. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  75670. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  75671. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  75672. var FOURCC_DX10 = FourCCToInt32("DX10");
  75673. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  75674. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  75675. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  75676. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  75677. var headerLengthInt = 31; // The header length in 32 bit ints
  75678. // Offsets into the header array
  75679. var off_magic = 0;
  75680. var off_size = 1;
  75681. var off_flags = 2;
  75682. var off_height = 3;
  75683. var off_width = 4;
  75684. var off_mipmapCount = 7;
  75685. var off_pfFlags = 20;
  75686. var off_pfFourCC = 21;
  75687. var off_RGBbpp = 22;
  75688. var off_RMask = 23;
  75689. var off_GMask = 24;
  75690. var off_BMask = 25;
  75691. var off_AMask = 26;
  75692. // var off_caps1 = 27;
  75693. var off_caps2 = 28;
  75694. // var off_caps3 = 29;
  75695. // var off_caps4 = 30;
  75696. var off_dxgiFormat = 32;
  75697. ;
  75698. var DDSTools = /** @class */ (function () {
  75699. function DDSTools() {
  75700. }
  75701. DDSTools.GetDDSInfo = function (arrayBuffer) {
  75702. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  75703. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  75704. var mipmapCount = 1;
  75705. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  75706. mipmapCount = Math.max(1, header[off_mipmapCount]);
  75707. }
  75708. var fourCC = header[off_pfFourCC];
  75709. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  75710. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  75711. switch (fourCC) {
  75712. case FOURCC_D3DFMT_R16G16B16A16F:
  75713. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  75714. break;
  75715. case FOURCC_D3DFMT_R32G32B32A32F:
  75716. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  75717. break;
  75718. case FOURCC_DX10:
  75719. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  75720. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  75721. break;
  75722. }
  75723. }
  75724. return {
  75725. width: header[off_width],
  75726. height: header[off_height],
  75727. mipmapCount: mipmapCount,
  75728. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  75729. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  75730. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  75731. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  75732. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  75733. dxgiFormat: dxgiFormat,
  75734. textureType: textureType
  75735. };
  75736. };
  75737. DDSTools._ToHalfFloat = function (value) {
  75738. if (!DDSTools._FloatView) {
  75739. DDSTools._FloatView = new Float32Array(1);
  75740. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  75741. }
  75742. DDSTools._FloatView[0] = value;
  75743. var x = DDSTools._Int32View[0];
  75744. var bits = (x >> 16) & 0x8000; /* Get the sign */
  75745. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  75746. var e = (x >> 23) & 0xff; /* Using int is faster here */
  75747. /* If zero, or denormal, or exponent underflows too much for a denormal
  75748. * half, return signed zero. */
  75749. if (e < 103) {
  75750. return bits;
  75751. }
  75752. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  75753. if (e > 142) {
  75754. bits |= 0x7c00;
  75755. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  75756. * not Inf, so make sure we set one mantissa bit too. */
  75757. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  75758. return bits;
  75759. }
  75760. /* If exponent underflows but not too much, return a denormal */
  75761. if (e < 113) {
  75762. m |= 0x0800;
  75763. /* Extra rounding may overflow and set mantissa to 0 and exponent
  75764. * to 1, which is OK. */
  75765. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  75766. return bits;
  75767. }
  75768. bits |= ((e - 112) << 10) | (m >> 1);
  75769. bits += m & 1;
  75770. return bits;
  75771. };
  75772. DDSTools._FromHalfFloat = function (value) {
  75773. var s = (value & 0x8000) >> 15;
  75774. var e = (value & 0x7C00) >> 10;
  75775. var f = value & 0x03FF;
  75776. if (e === 0) {
  75777. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  75778. }
  75779. else if (e == 0x1F) {
  75780. return f ? NaN : ((s ? -1 : 1) * Infinity);
  75781. }
  75782. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  75783. };
  75784. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  75785. var destArray = new Float32Array(dataLength);
  75786. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  75787. var index = 0;
  75788. for (var y = 0; y < height; y++) {
  75789. for (var x = 0; x < width; x++) {
  75790. var srcPos = (x + y * width) * 4;
  75791. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  75792. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  75793. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  75794. if (DDSTools.StoreLODInAlphaChannel) {
  75795. destArray[index + 3] = lod;
  75796. }
  75797. else {
  75798. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  75799. }
  75800. index += 4;
  75801. }
  75802. }
  75803. return destArray;
  75804. };
  75805. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  75806. if (DDSTools.StoreLODInAlphaChannel) {
  75807. var destArray = new Uint16Array(dataLength);
  75808. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  75809. var index = 0;
  75810. for (var y = 0; y < height; y++) {
  75811. for (var x = 0; x < width; x++) {
  75812. var srcPos = (x + y * width) * 4;
  75813. destArray[index] = srcData[srcPos];
  75814. destArray[index + 1] = srcData[srcPos + 1];
  75815. destArray[index + 2] = srcData[srcPos + 2];
  75816. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  75817. index += 4;
  75818. }
  75819. }
  75820. return destArray;
  75821. }
  75822. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  75823. };
  75824. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  75825. if (DDSTools.StoreLODInAlphaChannel) {
  75826. var destArray = new Float32Array(dataLength);
  75827. var srcData = new Float32Array(arrayBuffer, dataOffset);
  75828. var index = 0;
  75829. for (var y = 0; y < height; y++) {
  75830. for (var x = 0; x < width; x++) {
  75831. var srcPos = (x + y * width) * 4;
  75832. destArray[index] = srcData[srcPos];
  75833. destArray[index + 1] = srcData[srcPos + 1];
  75834. destArray[index + 2] = srcData[srcPos + 2];
  75835. destArray[index + 3] = lod;
  75836. index += 4;
  75837. }
  75838. }
  75839. return destArray;
  75840. }
  75841. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  75842. };
  75843. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  75844. var destArray = new Uint8Array(dataLength);
  75845. var srcData = new Float32Array(arrayBuffer, dataOffset);
  75846. var index = 0;
  75847. for (var y = 0; y < height; y++) {
  75848. for (var x = 0; x < width; x++) {
  75849. var srcPos = (x + y * width) * 4;
  75850. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  75851. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  75852. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  75853. if (DDSTools.StoreLODInAlphaChannel) {
  75854. destArray[index + 3] = lod;
  75855. }
  75856. else {
  75857. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  75858. }
  75859. index += 4;
  75860. }
  75861. }
  75862. return destArray;
  75863. };
  75864. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  75865. var destArray = new Uint8Array(dataLength);
  75866. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  75867. var index = 0;
  75868. for (var y = 0; y < height; y++) {
  75869. for (var x = 0; x < width; x++) {
  75870. var srcPos = (x + y * width) * 4;
  75871. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  75872. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  75873. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  75874. if (DDSTools.StoreLODInAlphaChannel) {
  75875. destArray[index + 3] = lod;
  75876. }
  75877. else {
  75878. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  75879. }
  75880. index += 4;
  75881. }
  75882. }
  75883. return destArray;
  75884. };
  75885. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  75886. var byteArray = new Uint8Array(dataLength);
  75887. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  75888. var index = 0;
  75889. for (var y = 0; y < height; y++) {
  75890. for (var x = 0; x < width; x++) {
  75891. var srcPos = (x + y * width) * 4;
  75892. byteArray[index] = srcData[srcPos + rOffset];
  75893. byteArray[index + 1] = srcData[srcPos + gOffset];
  75894. byteArray[index + 2] = srcData[srcPos + bOffset];
  75895. byteArray[index + 3] = srcData[srcPos + aOffset];
  75896. index += 4;
  75897. }
  75898. }
  75899. return byteArray;
  75900. };
  75901. DDSTools._ExtractLongWordOrder = function (value) {
  75902. if (value === 0 || value === 255 || value === -16777216) {
  75903. return 0;
  75904. }
  75905. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  75906. };
  75907. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  75908. var byteArray = new Uint8Array(dataLength);
  75909. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  75910. var index = 0;
  75911. for (var y = 0; y < height; y++) {
  75912. for (var x = 0; x < width; x++) {
  75913. var srcPos = (x + y * width) * 3;
  75914. byteArray[index] = srcData[srcPos + rOffset];
  75915. byteArray[index + 1] = srcData[srcPos + gOffset];
  75916. byteArray[index + 2] = srcData[srcPos + bOffset];
  75917. index += 3;
  75918. }
  75919. }
  75920. return byteArray;
  75921. };
  75922. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  75923. var byteArray = new Uint8Array(dataLength);
  75924. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  75925. var index = 0;
  75926. for (var y = 0; y < height; y++) {
  75927. for (var x = 0; x < width; x++) {
  75928. var srcPos = (x + y * width);
  75929. byteArray[index] = srcData[srcPos];
  75930. index++;
  75931. }
  75932. }
  75933. return byteArray;
  75934. };
  75935. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  75936. if (lodIndex === void 0) { lodIndex = -1; }
  75937. var ext = engine.getCaps().s3tc;
  75938. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  75939. var fourCC, width, height, dataLength = 0, dataOffset;
  75940. var byteArray, mipmapCount, mip;
  75941. var internalFormat = 0;
  75942. var format = 0;
  75943. var blockBytes = 1;
  75944. if (header[off_magic] !== DDS_MAGIC) {
  75945. BABYLON.Tools.Error("Invalid magic number in DDS header");
  75946. return;
  75947. }
  75948. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  75949. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  75950. return;
  75951. }
  75952. if (info.isCompressed && !ext) {
  75953. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  75954. return;
  75955. }
  75956. var bpp = header[off_RGBbpp];
  75957. dataOffset = header[off_size] + 4;
  75958. var computeFormats = false;
  75959. if (info.isFourCC) {
  75960. fourCC = header[off_pfFourCC];
  75961. switch (fourCC) {
  75962. case FOURCC_DXT1:
  75963. blockBytes = 8;
  75964. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  75965. break;
  75966. case FOURCC_DXT3:
  75967. blockBytes = 16;
  75968. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  75969. break;
  75970. case FOURCC_DXT5:
  75971. blockBytes = 16;
  75972. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  75973. break;
  75974. case FOURCC_D3DFMT_R16G16B16A16F:
  75975. computeFormats = true;
  75976. break;
  75977. case FOURCC_D3DFMT_R32G32B32A32F:
  75978. computeFormats = true;
  75979. break;
  75980. case FOURCC_DX10:
  75981. // There is an additionnal header so dataOffset need to be changed
  75982. dataOffset += 5 * 4; // 5 uints
  75983. var supported = false;
  75984. switch (info.dxgiFormat) {
  75985. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  75986. computeFormats = true;
  75987. supported = true;
  75988. break;
  75989. case DXGI_FORMAT_B8G8R8X8_UNORM:
  75990. info.isRGB = true;
  75991. info.isFourCC = false;
  75992. bpp = 32;
  75993. supported = true;
  75994. break;
  75995. }
  75996. if (supported) {
  75997. break;
  75998. }
  75999. default:
  76000. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  76001. return;
  76002. }
  76003. }
  76004. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  76005. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  76006. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  76007. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  76008. if (computeFormats) {
  76009. format = engine._getWebGLTextureType(info.textureType);
  76010. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  76011. }
  76012. mipmapCount = 1;
  76013. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  76014. mipmapCount = Math.max(1, header[off_mipmapCount]);
  76015. }
  76016. for (var face = 0; face < faces; face++) {
  76017. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face + (currentFace ? currentFace : 0));
  76018. width = header[off_width];
  76019. height = header[off_height];
  76020. for (mip = 0; mip < mipmapCount; ++mip) {
  76021. if (lodIndex === -1 || lodIndex === mip) {
  76022. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  76023. var i = (lodIndex === -1) ? mip : 0;
  76024. if (!info.isCompressed && info.isFourCC) {
  76025. dataLength = width * height * 4;
  76026. var floatArray = null;
  76027. if (engine.badOS || engine.badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) {
  76028. if (bpp === 128) {
  76029. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  76030. }
  76031. else if (bpp === 64) {
  76032. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  76033. }
  76034. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  76035. format = engine._getWebGLTextureType(info.textureType);
  76036. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  76037. }
  76038. else {
  76039. if (bpp === 128) {
  76040. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  76041. }
  76042. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  76043. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  76044. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  76045. format = engine._getWebGLTextureType(info.textureType);
  76046. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  76047. }
  76048. else {
  76049. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  76050. }
  76051. }
  76052. if (floatArray) {
  76053. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  76054. }
  76055. }
  76056. else if (info.isRGB) {
  76057. if (bpp === 24) {
  76058. dataLength = width * height * 3;
  76059. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  76060. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  76061. }
  76062. else {
  76063. dataLength = width * height * 4;
  76064. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  76065. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  76066. }
  76067. }
  76068. else if (info.isLuminance) {
  76069. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  76070. var unpaddedRowSize = width;
  76071. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  76072. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  76073. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  76074. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  76075. }
  76076. else {
  76077. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  76078. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  76079. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  76080. }
  76081. }
  76082. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  76083. width *= 0.5;
  76084. height *= 0.5;
  76085. width = Math.max(1.0, width);
  76086. height = Math.max(1.0, height);
  76087. }
  76088. if (currentFace !== undefined) {
  76089. // Loading a single face
  76090. break;
  76091. }
  76092. }
  76093. };
  76094. DDSTools.StoreLODInAlphaChannel = false;
  76095. return DDSTools;
  76096. }());
  76097. BABYLON.DDSTools = DDSTools;
  76098. })(BABYLON || (BABYLON = {}));
  76099. //# sourceMappingURL=babylon.dds.js.map
  76100. var BABYLON;
  76101. (function (BABYLON) {
  76102. /**
  76103. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  76104. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  76105. */
  76106. var KhronosTextureContainer = /** @class */ (function () {
  76107. /**
  76108. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  76109. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  76110. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  76111. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  76112. */
  76113. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  76114. this.arrayBuffer = arrayBuffer;
  76115. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  76116. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  76117. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  76118. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  76119. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  76120. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  76121. BABYLON.Tools.Error("texture missing KTX identifier");
  76122. return;
  76123. }
  76124. // load the reset of the header in native 32 bit int
  76125. var header = new Int32Array(this.arrayBuffer, 12, 13);
  76126. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  76127. var oppositeEndianess = header[0] === 0x01020304;
  76128. // read all the header elements in order they exist in the file, without modification (sans endainness)
  76129. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  76130. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  76131. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  76132. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  76133. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  76134. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  76135. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  76136. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  76137. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  76138. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  76139. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  76140. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  76141. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  76142. if (this.glType !== 0) {
  76143. BABYLON.Tools.Error("only compressed formats currently supported");
  76144. return;
  76145. }
  76146. else {
  76147. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  76148. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  76149. }
  76150. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  76151. BABYLON.Tools.Error("only 2D textures currently supported");
  76152. return;
  76153. }
  76154. if (this.numberOfArrayElements !== 0) {
  76155. BABYLON.Tools.Error("texture arrays not currently supported");
  76156. return;
  76157. }
  76158. if (this.numberOfFaces !== facesExpected) {
  76159. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  76160. return;
  76161. }
  76162. // we now have a completely validated file, so could use existence of loadType as success
  76163. // would need to make this more elaborate & adjust checks above to support more than one load type
  76164. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  76165. }
  76166. // not as fast hardware based, but will probably never need to use
  76167. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  76168. return ((val & 0xFF) << 24)
  76169. | ((val & 0xFF00) << 8)
  76170. | ((val >> 8) & 0xFF00)
  76171. | ((val >> 24) & 0xFF);
  76172. };
  76173. /**
  76174. * It is assumed that the texture has already been created & is currently bound
  76175. */
  76176. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  76177. switch (this.loadType) {
  76178. case KhronosTextureContainer.COMPRESSED_2D:
  76179. this._upload2DCompressedLevels(gl, loadMipmaps);
  76180. break;
  76181. case KhronosTextureContainer.TEX_2D:
  76182. case KhronosTextureContainer.COMPRESSED_3D:
  76183. case KhronosTextureContainer.TEX_3D:
  76184. }
  76185. };
  76186. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  76187. // initialize width & height for level 1
  76188. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  76189. var width = this.pixelWidth;
  76190. var height = this.pixelHeight;
  76191. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  76192. for (var level = 0; level < mipmapCount; level++) {
  76193. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  76194. for (var face = 0; face < this.numberOfFaces; face++) {
  76195. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  76196. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  76197. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  76198. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  76199. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  76200. }
  76201. width = Math.max(1.0, width * 0.5);
  76202. height = Math.max(1.0, height * 0.5);
  76203. }
  76204. };
  76205. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  76206. // load types
  76207. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  76208. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  76209. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  76210. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  76211. return KhronosTextureContainer;
  76212. }());
  76213. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  76214. })(BABYLON || (BABYLON = {}));
  76215. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  76216. var BABYLON;
  76217. (function (BABYLON) {
  76218. var Debug = /** @class */ (function () {
  76219. function Debug() {
  76220. }
  76221. Debug.AxesViewer = /** @class */ (function () {
  76222. function AxesViewer(scene, scaleLines) {
  76223. if (scaleLines === void 0) { scaleLines = 1; }
  76224. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  76225. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  76226. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  76227. this.scaleLines = 1;
  76228. this.scaleLines = scaleLines;
  76229. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  76230. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  76231. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  76232. this._xmesh.renderingGroupId = 2;
  76233. this._ymesh.renderingGroupId = 2;
  76234. this._zmesh.renderingGroupId = 2;
  76235. this._xmesh.material.checkReadyOnlyOnce = true;
  76236. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  76237. this._ymesh.material.checkReadyOnlyOnce = true;
  76238. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  76239. this._zmesh.material.checkReadyOnlyOnce = true;
  76240. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  76241. this.scene = scene;
  76242. }
  76243. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  76244. var scaleLines = this.scaleLines;
  76245. if (this._xmesh) {
  76246. this._xmesh.position.copyFrom(position);
  76247. }
  76248. if (this._ymesh) {
  76249. this._ymesh.position.copyFrom(position);
  76250. }
  76251. if (this._zmesh) {
  76252. this._zmesh.position.copyFrom(position);
  76253. }
  76254. var point2 = this._xline[1];
  76255. point2.x = xaxis.x * scaleLines;
  76256. point2.y = xaxis.y * scaleLines;
  76257. point2.z = xaxis.z * scaleLines;
  76258. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  76259. point2 = this._yline[1];
  76260. point2.x = yaxis.x * scaleLines;
  76261. point2.y = yaxis.y * scaleLines;
  76262. point2.z = yaxis.z * scaleLines;
  76263. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  76264. point2 = this._zline[1];
  76265. point2.x = zaxis.x * scaleLines;
  76266. point2.y = zaxis.y * scaleLines;
  76267. point2.z = zaxis.z * scaleLines;
  76268. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  76269. };
  76270. AxesViewer.prototype.dispose = function () {
  76271. if (this._xmesh) {
  76272. this._xmesh.dispose();
  76273. }
  76274. if (this._ymesh) {
  76275. this._ymesh.dispose();
  76276. }
  76277. if (this._zmesh) {
  76278. this._zmesh.dispose();
  76279. }
  76280. this._xmesh = null;
  76281. this._ymesh = null;
  76282. this._zmesh = null;
  76283. this.scene = null;
  76284. };
  76285. return AxesViewer;
  76286. }());
  76287. Debug.BoneAxesViewer = /** @class */ (function (_super) {
  76288. __extends(BoneAxesViewer, _super);
  76289. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  76290. if (scaleLines === void 0) { scaleLines = 1; }
  76291. var _this = _super.call(this, scene, scaleLines) || this;
  76292. _this.pos = BABYLON.Vector3.Zero();
  76293. _this.xaxis = BABYLON.Vector3.Zero();
  76294. _this.yaxis = BABYLON.Vector3.Zero();
  76295. _this.zaxis = BABYLON.Vector3.Zero();
  76296. _this.mesh = mesh;
  76297. _this.bone = bone;
  76298. return _this;
  76299. }
  76300. BoneAxesViewer.prototype.update = function () {
  76301. if (!this.mesh || !this.bone) {
  76302. return;
  76303. }
  76304. var bone = this.bone;
  76305. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  76306. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  76307. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  76308. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  76309. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  76310. };
  76311. BoneAxesViewer.prototype.dispose = function () {
  76312. if (this.mesh) {
  76313. this.mesh = null;
  76314. this.bone = null;
  76315. _super.prototype.dispose.call(this);
  76316. }
  76317. };
  76318. return BoneAxesViewer;
  76319. }(Debug.AxesViewer));
  76320. Debug.PhysicsViewer = /** @class */ (function () {
  76321. function PhysicsViewer(scene) {
  76322. this._impostors = [];
  76323. this._meshes = [];
  76324. this._numMeshes = 0;
  76325. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  76326. var physicEngine = this._scene.getPhysicsEngine();
  76327. if (physicEngine) {
  76328. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  76329. }
  76330. }
  76331. PhysicsViewer.prototype._updateDebugMeshes = function () {
  76332. var plugin = this._physicsEnginePlugin;
  76333. for (var i = 0; i < this._numMeshes; i++) {
  76334. var impostor = this._impostors[i];
  76335. if (!impostor) {
  76336. continue;
  76337. }
  76338. if (impostor.isDisposed) {
  76339. this.hideImpostor(this._impostors[i--]);
  76340. }
  76341. else {
  76342. var mesh = this._meshes[i];
  76343. if (mesh && plugin) {
  76344. plugin.syncMeshWithImpostor(mesh, impostor);
  76345. }
  76346. }
  76347. }
  76348. };
  76349. PhysicsViewer.prototype.showImpostor = function (impostor) {
  76350. if (!this._scene) {
  76351. return;
  76352. }
  76353. for (var i = 0; i < this._numMeshes; i++) {
  76354. if (this._impostors[i] == impostor) {
  76355. return;
  76356. }
  76357. }
  76358. var debugMesh = this._getDebugMesh(impostor, this._scene);
  76359. if (debugMesh) {
  76360. this._impostors[this._numMeshes] = impostor;
  76361. this._meshes[this._numMeshes] = debugMesh;
  76362. if (this._numMeshes === 0) {
  76363. this._renderFunction = this._updateDebugMeshes.bind(this);
  76364. this._scene.registerBeforeRender(this._renderFunction);
  76365. }
  76366. this._numMeshes++;
  76367. }
  76368. };
  76369. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  76370. if (!impostor || !this._scene) {
  76371. return;
  76372. }
  76373. var removed = false;
  76374. for (var i = 0; i < this._numMeshes; i++) {
  76375. if (this._impostors[i] == impostor) {
  76376. var mesh = this._meshes[i];
  76377. if (!mesh) {
  76378. continue;
  76379. }
  76380. this._scene.removeMesh(mesh);
  76381. mesh.dispose();
  76382. this._numMeshes--;
  76383. if (this._numMeshes > 0) {
  76384. this._meshes[i] = this._meshes[this._numMeshes];
  76385. this._impostors[i] = this._impostors[this._numMeshes];
  76386. this._meshes[this._numMeshes] = null;
  76387. this._impostors[this._numMeshes] = null;
  76388. }
  76389. else {
  76390. this._meshes[0] = null;
  76391. this._impostors[0] = null;
  76392. }
  76393. removed = true;
  76394. break;
  76395. }
  76396. }
  76397. if (removed && this._numMeshes === 0) {
  76398. this._scene.unregisterBeforeRender(this._renderFunction);
  76399. }
  76400. };
  76401. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  76402. if (!this._debugMaterial) {
  76403. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  76404. this._debugMaterial.wireframe = true;
  76405. }
  76406. return this._debugMaterial;
  76407. };
  76408. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  76409. if (!this._debugBoxMesh) {
  76410. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  76411. this._debugBoxMesh.renderingGroupId = 1;
  76412. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  76413. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  76414. scene.removeMesh(this._debugBoxMesh);
  76415. }
  76416. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  76417. };
  76418. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  76419. if (!this._debugSphereMesh) {
  76420. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  76421. this._debugSphereMesh.renderingGroupId = 1;
  76422. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  76423. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  76424. scene.removeMesh(this._debugSphereMesh);
  76425. }
  76426. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  76427. };
  76428. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  76429. var mesh = null;
  76430. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  76431. mesh = this._getDebugBoxMesh(scene);
  76432. impostor.getBoxSizeToRef(mesh.scaling);
  76433. }
  76434. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  76435. mesh = this._getDebugSphereMesh(scene);
  76436. var radius = impostor.getRadius();
  76437. mesh.scaling.x = radius * 2;
  76438. mesh.scaling.y = radius * 2;
  76439. mesh.scaling.z = radius * 2;
  76440. }
  76441. return mesh;
  76442. };
  76443. PhysicsViewer.prototype.dispose = function () {
  76444. for (var i = 0; i < this._numMeshes; i++) {
  76445. this.hideImpostor(this._impostors[i]);
  76446. }
  76447. if (this._debugBoxMesh) {
  76448. this._debugBoxMesh.dispose();
  76449. }
  76450. if (this._debugSphereMesh) {
  76451. this._debugSphereMesh.dispose();
  76452. }
  76453. if (this._debugMaterial) {
  76454. this._debugMaterial.dispose();
  76455. }
  76456. this._impostors.length = 0;
  76457. this._scene = null;
  76458. this._physicsEnginePlugin = null;
  76459. };
  76460. return PhysicsViewer;
  76461. }());
  76462. Debug.SkeletonViewer = /** @class */ (function () {
  76463. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  76464. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  76465. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  76466. this.skeleton = skeleton;
  76467. this.mesh = mesh;
  76468. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  76469. this.renderingGroupId = renderingGroupId;
  76470. this.color = BABYLON.Color3.White();
  76471. this._debugLines = new Array();
  76472. this._isEnabled = false;
  76473. this._scene = scene;
  76474. this.update();
  76475. this._renderFunction = this.update.bind(this);
  76476. }
  76477. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  76478. get: function () {
  76479. return this._isEnabled;
  76480. },
  76481. set: function (value) {
  76482. if (this._isEnabled === value) {
  76483. return;
  76484. }
  76485. this._isEnabled = value;
  76486. if (value) {
  76487. this._scene.registerBeforeRender(this._renderFunction);
  76488. }
  76489. else {
  76490. this._scene.unregisterBeforeRender(this._renderFunction);
  76491. }
  76492. },
  76493. enumerable: true,
  76494. configurable: true
  76495. });
  76496. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  76497. if (x === void 0) { x = 0; }
  76498. if (y === void 0) { y = 0; }
  76499. if (z === void 0) { z = 0; }
  76500. var tmat = BABYLON.Tmp.Matrix[0];
  76501. var parentBone = bone.getParent();
  76502. tmat.copyFrom(bone.getLocalMatrix());
  76503. if (x !== 0 || y !== 0 || z !== 0) {
  76504. var tmat2 = BABYLON.Tmp.Matrix[1];
  76505. BABYLON.Matrix.IdentityToRef(tmat2);
  76506. tmat2.m[12] = x;
  76507. tmat2.m[13] = y;
  76508. tmat2.m[14] = z;
  76509. tmat2.multiplyToRef(tmat, tmat);
  76510. }
  76511. if (parentBone) {
  76512. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  76513. }
  76514. tmat.multiplyToRef(meshMat, tmat);
  76515. position.x = tmat.m[12];
  76516. position.y = tmat.m[13];
  76517. position.z = tmat.m[14];
  76518. };
  76519. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  76520. var len = bones.length;
  76521. var meshPos = this.mesh.position;
  76522. for (var i = 0; i < len; i++) {
  76523. var bone = bones[i];
  76524. var points = this._debugLines[i];
  76525. if (!points) {
  76526. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  76527. this._debugLines[i] = points;
  76528. }
  76529. this._getBonePosition(points[0], bone, meshMat);
  76530. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  76531. points[0].subtractInPlace(meshPos);
  76532. points[1].subtractInPlace(meshPos);
  76533. }
  76534. };
  76535. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  76536. var len = bones.length;
  76537. var boneNum = 0;
  76538. var meshPos = this.mesh.position;
  76539. for (var i = len - 1; i >= 0; i--) {
  76540. var childBone = bones[i];
  76541. var parentBone = childBone.getParent();
  76542. if (!parentBone) {
  76543. continue;
  76544. }
  76545. var points = this._debugLines[boneNum];
  76546. if (!points) {
  76547. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  76548. this._debugLines[boneNum] = points;
  76549. }
  76550. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  76551. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  76552. points[0].subtractInPlace(meshPos);
  76553. points[1].subtractInPlace(meshPos);
  76554. boneNum++;
  76555. }
  76556. };
  76557. SkeletonViewer.prototype.update = function () {
  76558. if (this.autoUpdateBonesMatrices) {
  76559. this.skeleton.computeAbsoluteTransforms();
  76560. }
  76561. if (this.skeleton.bones[0].length === undefined) {
  76562. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  76563. }
  76564. else {
  76565. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  76566. }
  76567. if (!this._debugMesh) {
  76568. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  76569. this._debugMesh.renderingGroupId = this.renderingGroupId;
  76570. }
  76571. else {
  76572. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  76573. }
  76574. this._debugMesh.position.copyFrom(this.mesh.position);
  76575. this._debugMesh.color = this.color;
  76576. };
  76577. SkeletonViewer.prototype.dispose = function () {
  76578. if (this._debugMesh) {
  76579. this.isEnabled = false;
  76580. this._debugMesh.dispose();
  76581. this._debugMesh = null;
  76582. }
  76583. };
  76584. return SkeletonViewer;
  76585. }());
  76586. return Debug;
  76587. }());
  76588. BABYLON.Debug = Debug;
  76589. })(BABYLON || (BABYLON = {}));
  76590. //# sourceMappingURL=babylon.debugModules.js.map
  76591. var BABYLON;
  76592. (function (BABYLON) {
  76593. var RayHelper = /** @class */ (function () {
  76594. function RayHelper(ray) {
  76595. this.ray = ray;
  76596. }
  76597. RayHelper.CreateAndShow = function (ray, scene, color) {
  76598. var helper = new RayHelper(ray);
  76599. helper.show(scene, color);
  76600. return helper;
  76601. };
  76602. RayHelper.prototype.show = function (scene, color) {
  76603. if (!this._renderFunction && this.ray) {
  76604. var ray = this.ray;
  76605. this._renderFunction = this._render.bind(this);
  76606. this._scene = scene;
  76607. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  76608. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  76609. if (this._renderFunction) {
  76610. this._scene.registerBeforeRender(this._renderFunction);
  76611. }
  76612. }
  76613. if (color && this._renderLine) {
  76614. this._renderLine.color.copyFrom(color);
  76615. }
  76616. };
  76617. RayHelper.prototype.hide = function () {
  76618. if (this._renderFunction && this._scene) {
  76619. this._scene.unregisterBeforeRender(this._renderFunction);
  76620. this._scene = null;
  76621. this._renderFunction = null;
  76622. if (this._renderLine) {
  76623. this._renderLine.dispose();
  76624. this._renderLine = null;
  76625. }
  76626. this._renderPoints = [];
  76627. }
  76628. };
  76629. RayHelper.prototype._render = function () {
  76630. var ray = this.ray;
  76631. if (!ray) {
  76632. return;
  76633. }
  76634. var point = this._renderPoints[1];
  76635. var len = Math.min(ray.length, 1000000);
  76636. point.copyFrom(ray.direction);
  76637. point.scaleInPlace(len);
  76638. point.addInPlace(ray.origin);
  76639. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  76640. };
  76641. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  76642. this._attachedToMesh = mesh;
  76643. var ray = this.ray;
  76644. if (!ray) {
  76645. return;
  76646. }
  76647. if (!ray.direction) {
  76648. ray.direction = BABYLON.Vector3.Zero();
  76649. }
  76650. if (!ray.origin) {
  76651. ray.origin = BABYLON.Vector3.Zero();
  76652. }
  76653. if (length) {
  76654. ray.length = length;
  76655. }
  76656. if (!meshSpaceOrigin) {
  76657. meshSpaceOrigin = BABYLON.Vector3.Zero();
  76658. }
  76659. if (!meshSpaceDirection) {
  76660. // -1 so that this will work with Mesh.lookAt
  76661. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  76662. }
  76663. if (!this._meshSpaceDirection) {
  76664. this._meshSpaceDirection = meshSpaceDirection.clone();
  76665. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  76666. }
  76667. else {
  76668. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  76669. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  76670. }
  76671. if (!this._updateToMeshFunction) {
  76672. this._updateToMeshFunction = this._updateToMesh.bind(this);
  76673. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  76674. }
  76675. this._updateToMesh();
  76676. };
  76677. RayHelper.prototype.detachFromMesh = function () {
  76678. if (this._attachedToMesh) {
  76679. if (this._updateToMeshFunction) {
  76680. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  76681. }
  76682. this._attachedToMesh = null;
  76683. this._updateToMeshFunction = null;
  76684. }
  76685. };
  76686. RayHelper.prototype._updateToMesh = function () {
  76687. var ray = this.ray;
  76688. if (!this._attachedToMesh || !ray) {
  76689. return;
  76690. }
  76691. if (this._attachedToMesh._isDisposed) {
  76692. this.detachFromMesh();
  76693. return;
  76694. }
  76695. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  76696. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  76697. };
  76698. RayHelper.prototype.dispose = function () {
  76699. this.hide();
  76700. this.detachFromMesh();
  76701. this.ray = null;
  76702. };
  76703. return RayHelper;
  76704. }());
  76705. BABYLON.RayHelper = RayHelper;
  76706. })(BABYLON || (BABYLON = {}));
  76707. //# sourceMappingURL=babylon.rayHelper.js.map
  76708. var BABYLON;
  76709. (function (BABYLON) {
  76710. // load the inspector using require, if not present in the global namespace.
  76711. var DebugLayer = /** @class */ (function () {
  76712. function DebugLayer(scene) {
  76713. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  76714. this._scene = scene;
  76715. // load inspector using require, if it doesn't exist on the global namespace.
  76716. }
  76717. /** Creates the inspector window. */
  76718. DebugLayer.prototype._createInspector = function (config) {
  76719. if (config === void 0) { config = {}; }
  76720. var popup = config.popup || false;
  76721. var initialTab = config.initialTab || 0;
  76722. var parentElement = config.parentElement || null;
  76723. if (!this._inspector) {
  76724. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  76725. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  76726. } // else nothing to do,; instance is already existing
  76727. };
  76728. DebugLayer.prototype.isVisible = function () {
  76729. if (!this._inspector) {
  76730. return false;
  76731. }
  76732. return true;
  76733. };
  76734. DebugLayer.prototype.hide = function () {
  76735. if (this._inspector) {
  76736. try {
  76737. this._inspector.dispose();
  76738. }
  76739. catch (e) {
  76740. // If the inspector has been removed directly from the inspector tool
  76741. }
  76742. this._inspector = null;
  76743. }
  76744. };
  76745. DebugLayer.prototype.show = function (config) {
  76746. if (config === void 0) { config = {}; }
  76747. if (typeof this.BJSINSPECTOR == 'undefined') {
  76748. // Load inspector and add it to the DOM
  76749. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  76750. }
  76751. else {
  76752. // Otherwise creates the inspector
  76753. this._createInspector(config);
  76754. }
  76755. };
  76756. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  76757. return DebugLayer;
  76758. }());
  76759. BABYLON.DebugLayer = DebugLayer;
  76760. })(BABYLON || (BABYLON = {}));
  76761. //# sourceMappingURL=babylon.debugLayer.js.map
  76762. var BABYLON;
  76763. (function (BABYLON) {
  76764. var BoundingBoxRenderer = /** @class */ (function () {
  76765. function BoundingBoxRenderer(scene) {
  76766. this.frontColor = new BABYLON.Color3(1, 1, 1);
  76767. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  76768. this.showBackLines = true;
  76769. this.renderList = new BABYLON.SmartArray(32);
  76770. this._vertexBuffers = {};
  76771. this._scene = scene;
  76772. }
  76773. BoundingBoxRenderer.prototype._prepareRessources = function () {
  76774. if (this._colorShader) {
  76775. return;
  76776. }
  76777. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  76778. attributes: [BABYLON.VertexBuffer.PositionKind],
  76779. uniforms: ["world", "viewProjection", "color"]
  76780. });
  76781. var engine = this._scene.getEngine();
  76782. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  76783. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  76784. this._createIndexBuffer();
  76785. };
  76786. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  76787. var engine = this._scene.getEngine();
  76788. 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]);
  76789. };
  76790. BoundingBoxRenderer.prototype._rebuild = function () {
  76791. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  76792. if (vb) {
  76793. vb._rebuild();
  76794. }
  76795. this._createIndexBuffer();
  76796. };
  76797. BoundingBoxRenderer.prototype.reset = function () {
  76798. this.renderList.reset();
  76799. };
  76800. BoundingBoxRenderer.prototype.render = function () {
  76801. if (this.renderList.length === 0) {
  76802. return;
  76803. }
  76804. this._prepareRessources();
  76805. if (!this._colorShader.isReady()) {
  76806. return;
  76807. }
  76808. var engine = this._scene.getEngine();
  76809. engine.setDepthWrite(false);
  76810. this._colorShader._preBind();
  76811. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  76812. var boundingBox = this.renderList.data[boundingBoxIndex];
  76813. var min = boundingBox.minimum;
  76814. var max = boundingBox.maximum;
  76815. var diff = max.subtract(min);
  76816. var median = min.add(diff.scale(0.5));
  76817. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  76818. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  76819. .multiply(boundingBox.getWorldMatrix());
  76820. // VBOs
  76821. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  76822. if (this.showBackLines) {
  76823. // Back
  76824. engine.setDepthFunctionToGreaterOrEqual();
  76825. this._scene.resetCachedMaterial();
  76826. this._colorShader.setColor4("color", this.backColor.toColor4());
  76827. this._colorShader.bind(worldMatrix);
  76828. // Draw order
  76829. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  76830. }
  76831. // Front
  76832. engine.setDepthFunctionToLess();
  76833. this._scene.resetCachedMaterial();
  76834. this._colorShader.setColor4("color", this.frontColor.toColor4());
  76835. this._colorShader.bind(worldMatrix);
  76836. // Draw order
  76837. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  76838. }
  76839. this._colorShader.unbind();
  76840. engine.setDepthFunctionToLessOrEqual();
  76841. engine.setDepthWrite(true);
  76842. };
  76843. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  76844. this._prepareRessources();
  76845. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  76846. return;
  76847. }
  76848. var engine = this._scene.getEngine();
  76849. engine.setDepthWrite(false);
  76850. engine.setColorWrite(false);
  76851. this._colorShader._preBind();
  76852. var boundingBox = mesh._boundingInfo.boundingBox;
  76853. var min = boundingBox.minimum;
  76854. var max = boundingBox.maximum;
  76855. var diff = max.subtract(min);
  76856. var median = min.add(diff.scale(0.5));
  76857. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  76858. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  76859. .multiply(boundingBox.getWorldMatrix());
  76860. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  76861. engine.setDepthFunctionToLess();
  76862. this._scene.resetCachedMaterial();
  76863. this._colorShader.bind(worldMatrix);
  76864. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  76865. this._colorShader.unbind();
  76866. engine.setDepthFunctionToLessOrEqual();
  76867. engine.setDepthWrite(true);
  76868. engine.setColorWrite(true);
  76869. };
  76870. BoundingBoxRenderer.prototype.dispose = function () {
  76871. if (!this._colorShader) {
  76872. return;
  76873. }
  76874. this.renderList.dispose();
  76875. this._colorShader.dispose();
  76876. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  76877. if (buffer) {
  76878. buffer.dispose();
  76879. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  76880. }
  76881. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  76882. };
  76883. return BoundingBoxRenderer;
  76884. }());
  76885. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  76886. })(BABYLON || (BABYLON = {}));
  76887. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  76888. var BABYLON;
  76889. (function (BABYLON) {
  76890. var MorphTarget = /** @class */ (function () {
  76891. function MorphTarget(name, influence) {
  76892. if (influence === void 0) { influence = 0; }
  76893. this.name = name;
  76894. this.animations = new Array();
  76895. this._positions = null;
  76896. this._normals = null;
  76897. this._tangents = null;
  76898. this.onInfluenceChanged = new BABYLON.Observable();
  76899. this.influence = influence;
  76900. }
  76901. Object.defineProperty(MorphTarget.prototype, "influence", {
  76902. get: function () {
  76903. return this._influence;
  76904. },
  76905. set: function (influence) {
  76906. if (this._influence === influence) {
  76907. return;
  76908. }
  76909. var previous = this._influence;
  76910. this._influence = influence;
  76911. if (this.onInfluenceChanged.hasObservers) {
  76912. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  76913. }
  76914. },
  76915. enumerable: true,
  76916. configurable: true
  76917. });
  76918. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  76919. get: function () {
  76920. return !!this._positions;
  76921. },
  76922. enumerable: true,
  76923. configurable: true
  76924. });
  76925. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  76926. get: function () {
  76927. return !!this._normals;
  76928. },
  76929. enumerable: true,
  76930. configurable: true
  76931. });
  76932. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  76933. get: function () {
  76934. return !!this._tangents;
  76935. },
  76936. enumerable: true,
  76937. configurable: true
  76938. });
  76939. MorphTarget.prototype.setPositions = function (data) {
  76940. this._positions = data;
  76941. };
  76942. MorphTarget.prototype.getPositions = function () {
  76943. return this._positions;
  76944. };
  76945. MorphTarget.prototype.setNormals = function (data) {
  76946. this._normals = data;
  76947. };
  76948. MorphTarget.prototype.getNormals = function () {
  76949. return this._normals;
  76950. };
  76951. MorphTarget.prototype.setTangents = function (data) {
  76952. this._tangents = data;
  76953. };
  76954. MorphTarget.prototype.getTangents = function () {
  76955. return this._tangents;
  76956. };
  76957. /**
  76958. * Serializes the current target into a Serialization object.
  76959. * Returns the serialized object.
  76960. */
  76961. MorphTarget.prototype.serialize = function () {
  76962. var serializationObject = {};
  76963. serializationObject.name = this.name;
  76964. serializationObject.influence = this.influence;
  76965. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  76966. if (this.hasNormals) {
  76967. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  76968. }
  76969. if (this.hasTangents) {
  76970. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  76971. }
  76972. // Animations
  76973. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  76974. return serializationObject;
  76975. };
  76976. // Statics
  76977. MorphTarget.Parse = function (serializationObject) {
  76978. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  76979. result.setPositions(serializationObject.positions);
  76980. if (serializationObject.normals) {
  76981. result.setNormals(serializationObject.normals);
  76982. }
  76983. if (serializationObject.tangents) {
  76984. result.setTangents(serializationObject.tangents);
  76985. }
  76986. // Animations
  76987. if (serializationObject.animations) {
  76988. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  76989. var parsedAnimation = serializationObject.animations[animationIndex];
  76990. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  76991. }
  76992. }
  76993. return result;
  76994. };
  76995. MorphTarget.FromMesh = function (mesh, name, influence) {
  76996. if (!name) {
  76997. name = mesh.name;
  76998. }
  76999. var result = new MorphTarget(name, influence);
  77000. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  77001. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  77002. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  77003. }
  77004. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  77005. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  77006. }
  77007. return result;
  77008. };
  77009. return MorphTarget;
  77010. }());
  77011. BABYLON.MorphTarget = MorphTarget;
  77012. })(BABYLON || (BABYLON = {}));
  77013. //# sourceMappingURL=babylon.morphTarget.js.map
  77014. var BABYLON;
  77015. (function (BABYLON) {
  77016. var MorphTargetManager = /** @class */ (function () {
  77017. function MorphTargetManager(scene) {
  77018. if (scene === void 0) { scene = null; }
  77019. this._targets = new Array();
  77020. this._targetObservable = new Array();
  77021. this._activeTargets = new BABYLON.SmartArray(16);
  77022. this._supportsNormals = false;
  77023. this._supportsTangents = false;
  77024. this._vertexCount = 0;
  77025. this._uniqueId = 0;
  77026. this._tempInfluences = new Array();
  77027. if (!scene) {
  77028. scene = BABYLON.Engine.LastCreatedScene;
  77029. }
  77030. this._scene = scene;
  77031. if (this._scene) {
  77032. this._scene.morphTargetManagers.push(this);
  77033. this._uniqueId = this._scene.getUniqueId();
  77034. }
  77035. }
  77036. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  77037. get: function () {
  77038. return this._uniqueId;
  77039. },
  77040. enumerable: true,
  77041. configurable: true
  77042. });
  77043. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  77044. get: function () {
  77045. return this._vertexCount;
  77046. },
  77047. enumerable: true,
  77048. configurable: true
  77049. });
  77050. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  77051. get: function () {
  77052. return this._supportsNormals;
  77053. },
  77054. enumerable: true,
  77055. configurable: true
  77056. });
  77057. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  77058. get: function () {
  77059. return this._supportsTangents;
  77060. },
  77061. enumerable: true,
  77062. configurable: true
  77063. });
  77064. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  77065. get: function () {
  77066. return this._targets.length;
  77067. },
  77068. enumerable: true,
  77069. configurable: true
  77070. });
  77071. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  77072. get: function () {
  77073. return this._activeTargets.length;
  77074. },
  77075. enumerable: true,
  77076. configurable: true
  77077. });
  77078. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  77079. get: function () {
  77080. return this._influences;
  77081. },
  77082. enumerable: true,
  77083. configurable: true
  77084. });
  77085. MorphTargetManager.prototype.getActiveTarget = function (index) {
  77086. return this._activeTargets.data[index];
  77087. };
  77088. MorphTargetManager.prototype.getTarget = function (index) {
  77089. return this._targets[index];
  77090. };
  77091. MorphTargetManager.prototype.addTarget = function (target) {
  77092. var _this = this;
  77093. this._targets.push(target);
  77094. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  77095. _this._syncActiveTargets(needUpdate);
  77096. }));
  77097. this._syncActiveTargets(true);
  77098. };
  77099. MorphTargetManager.prototype.removeTarget = function (target) {
  77100. var index = this._targets.indexOf(target);
  77101. if (index >= 0) {
  77102. this._targets.splice(index, 1);
  77103. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  77104. this._syncActiveTargets(true);
  77105. }
  77106. };
  77107. /**
  77108. * Serializes the current manager into a Serialization object.
  77109. * Returns the serialized object.
  77110. */
  77111. MorphTargetManager.prototype.serialize = function () {
  77112. var serializationObject = {};
  77113. serializationObject.id = this.uniqueId;
  77114. serializationObject.targets = [];
  77115. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  77116. var target = _a[_i];
  77117. serializationObject.targets.push(target.serialize());
  77118. }
  77119. return serializationObject;
  77120. };
  77121. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  77122. var influenceCount = 0;
  77123. this._activeTargets.reset();
  77124. this._supportsNormals = true;
  77125. this._supportsTangents = true;
  77126. this._vertexCount = 0;
  77127. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  77128. var target = _a[_i];
  77129. this._activeTargets.push(target);
  77130. this._tempInfluences[influenceCount++] = target.influence;
  77131. var positions = target.getPositions();
  77132. if (positions) {
  77133. this._supportsNormals = this._supportsNormals && target.hasNormals;
  77134. this._supportsTangents = this._supportsTangents && target.hasTangents;
  77135. var vertexCount = positions.length / 3;
  77136. if (this._vertexCount === 0) {
  77137. this._vertexCount = vertexCount;
  77138. }
  77139. else if (this._vertexCount !== vertexCount) {
  77140. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  77141. return;
  77142. }
  77143. }
  77144. }
  77145. if (!this._influences || this._influences.length !== influenceCount) {
  77146. this._influences = new Float32Array(influenceCount);
  77147. }
  77148. for (var index = 0; index < influenceCount; index++) {
  77149. this._influences[index] = this._tempInfluences[index];
  77150. }
  77151. if (needUpdate && this._scene) {
  77152. // Flag meshes as dirty to resync with the active targets
  77153. for (var _b = 0, _c = this._scene.meshes; _b < _c.length; _b++) {
  77154. var mesh = _c[_b];
  77155. if (mesh.morphTargetManager === this) {
  77156. mesh._syncGeometryWithMorphTargetManager();
  77157. }
  77158. }
  77159. }
  77160. };
  77161. // Statics
  77162. MorphTargetManager.Parse = function (serializationObject, scene) {
  77163. var result = new MorphTargetManager(scene);
  77164. result._uniqueId = serializationObject.id;
  77165. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  77166. var targetData = _a[_i];
  77167. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  77168. }
  77169. return result;
  77170. };
  77171. return MorphTargetManager;
  77172. }());
  77173. BABYLON.MorphTargetManager = MorphTargetManager;
  77174. })(BABYLON || (BABYLON = {}));
  77175. //# sourceMappingURL=babylon.morphTargetManager.js.map
  77176. var BABYLON;
  77177. (function (BABYLON) {
  77178. var Octree = /** @class */ (function () {
  77179. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  77180. if (maxDepth === void 0) { maxDepth = 2; }
  77181. this.maxDepth = maxDepth;
  77182. this.dynamicContent = new Array();
  77183. this._maxBlockCapacity = maxBlockCapacity || 64;
  77184. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  77185. this._creationFunc = creationFunc;
  77186. }
  77187. // Methods
  77188. Octree.prototype.update = function (worldMin, worldMax, entries) {
  77189. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  77190. };
  77191. Octree.prototype.addMesh = function (entry) {
  77192. for (var index = 0; index < this.blocks.length; index++) {
  77193. var block = this.blocks[index];
  77194. block.addEntry(entry);
  77195. }
  77196. };
  77197. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  77198. this._selectionContent.reset();
  77199. for (var index = 0; index < this.blocks.length; index++) {
  77200. var block = this.blocks[index];
  77201. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  77202. }
  77203. if (allowDuplicate) {
  77204. this._selectionContent.concat(this.dynamicContent);
  77205. }
  77206. else {
  77207. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  77208. }
  77209. return this._selectionContent;
  77210. };
  77211. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  77212. this._selectionContent.reset();
  77213. for (var index = 0; index < this.blocks.length; index++) {
  77214. var block = this.blocks[index];
  77215. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  77216. }
  77217. if (allowDuplicate) {
  77218. this._selectionContent.concat(this.dynamicContent);
  77219. }
  77220. else {
  77221. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  77222. }
  77223. return this._selectionContent;
  77224. };
  77225. Octree.prototype.intersectsRay = function (ray) {
  77226. this._selectionContent.reset();
  77227. for (var index = 0; index < this.blocks.length; index++) {
  77228. var block = this.blocks[index];
  77229. block.intersectsRay(ray, this._selectionContent);
  77230. }
  77231. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  77232. return this._selectionContent;
  77233. };
  77234. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  77235. target.blocks = new Array();
  77236. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  77237. // Segmenting space
  77238. for (var x = 0; x < 2; x++) {
  77239. for (var y = 0; y < 2; y++) {
  77240. for (var z = 0; z < 2; z++) {
  77241. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  77242. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  77243. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  77244. block.addEntries(entries);
  77245. target.blocks.push(block);
  77246. }
  77247. }
  77248. }
  77249. };
  77250. Octree.CreationFuncForMeshes = function (entry, block) {
  77251. var boundingInfo = entry.getBoundingInfo();
  77252. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  77253. block.entries.push(entry);
  77254. }
  77255. };
  77256. Octree.CreationFuncForSubMeshes = function (entry, block) {
  77257. var boundingInfo = entry.getBoundingInfo();
  77258. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  77259. block.entries.push(entry);
  77260. }
  77261. };
  77262. return Octree;
  77263. }());
  77264. BABYLON.Octree = Octree;
  77265. })(BABYLON || (BABYLON = {}));
  77266. //# sourceMappingURL=babylon.octree.js.map
  77267. var BABYLON;
  77268. (function (BABYLON) {
  77269. var OctreeBlock = /** @class */ (function () {
  77270. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  77271. this.entries = new Array();
  77272. this._boundingVectors = new Array();
  77273. this._capacity = capacity;
  77274. this._depth = depth;
  77275. this._maxDepth = maxDepth;
  77276. this._creationFunc = creationFunc;
  77277. this._minPoint = minPoint;
  77278. this._maxPoint = maxPoint;
  77279. this._boundingVectors.push(minPoint.clone());
  77280. this._boundingVectors.push(maxPoint.clone());
  77281. this._boundingVectors.push(minPoint.clone());
  77282. this._boundingVectors[2].x = maxPoint.x;
  77283. this._boundingVectors.push(minPoint.clone());
  77284. this._boundingVectors[3].y = maxPoint.y;
  77285. this._boundingVectors.push(minPoint.clone());
  77286. this._boundingVectors[4].z = maxPoint.z;
  77287. this._boundingVectors.push(maxPoint.clone());
  77288. this._boundingVectors[5].z = minPoint.z;
  77289. this._boundingVectors.push(maxPoint.clone());
  77290. this._boundingVectors[6].x = minPoint.x;
  77291. this._boundingVectors.push(maxPoint.clone());
  77292. this._boundingVectors[7].y = minPoint.y;
  77293. }
  77294. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  77295. // Property
  77296. get: function () {
  77297. return this._capacity;
  77298. },
  77299. enumerable: true,
  77300. configurable: true
  77301. });
  77302. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  77303. get: function () {
  77304. return this._minPoint;
  77305. },
  77306. enumerable: true,
  77307. configurable: true
  77308. });
  77309. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  77310. get: function () {
  77311. return this._maxPoint;
  77312. },
  77313. enumerable: true,
  77314. configurable: true
  77315. });
  77316. // Methods
  77317. OctreeBlock.prototype.addEntry = function (entry) {
  77318. if (this.blocks) {
  77319. for (var index = 0; index < this.blocks.length; index++) {
  77320. var block = this.blocks[index];
  77321. block.addEntry(entry);
  77322. }
  77323. return;
  77324. }
  77325. this._creationFunc(entry, this);
  77326. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  77327. this.createInnerBlocks();
  77328. }
  77329. };
  77330. OctreeBlock.prototype.addEntries = function (entries) {
  77331. for (var index = 0; index < entries.length; index++) {
  77332. var mesh = entries[index];
  77333. this.addEntry(mesh);
  77334. }
  77335. };
  77336. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  77337. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  77338. if (this.blocks) {
  77339. for (var index = 0; index < this.blocks.length; index++) {
  77340. var block = this.blocks[index];
  77341. block.select(frustumPlanes, selection, allowDuplicate);
  77342. }
  77343. return;
  77344. }
  77345. if (allowDuplicate) {
  77346. selection.concat(this.entries);
  77347. }
  77348. else {
  77349. selection.concatWithNoDuplicate(this.entries);
  77350. }
  77351. }
  77352. };
  77353. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  77354. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  77355. if (this.blocks) {
  77356. for (var index = 0; index < this.blocks.length; index++) {
  77357. var block = this.blocks[index];
  77358. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  77359. }
  77360. return;
  77361. }
  77362. if (allowDuplicate) {
  77363. selection.concat(this.entries);
  77364. }
  77365. else {
  77366. selection.concatWithNoDuplicate(this.entries);
  77367. }
  77368. }
  77369. };
  77370. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  77371. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  77372. if (this.blocks) {
  77373. for (var index = 0; index < this.blocks.length; index++) {
  77374. var block = this.blocks[index];
  77375. block.intersectsRay(ray, selection);
  77376. }
  77377. return;
  77378. }
  77379. selection.concatWithNoDuplicate(this.entries);
  77380. }
  77381. };
  77382. OctreeBlock.prototype.createInnerBlocks = function () {
  77383. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  77384. };
  77385. return OctreeBlock;
  77386. }());
  77387. BABYLON.OctreeBlock = OctreeBlock;
  77388. })(BABYLON || (BABYLON = {}));
  77389. //# sourceMappingURL=babylon.octreeBlock.js.map
  77390. var BABYLON;
  77391. (function (BABYLON) {
  77392. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  77393. __extends(VRDistortionCorrectionPostProcess, _super);
  77394. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  77395. var _this = _super.call(this, name, "vrDistortionCorrection", [
  77396. 'LensCenter',
  77397. 'Scale',
  77398. 'ScaleIn',
  77399. 'HmdWarpParam'
  77400. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  77401. _this._isRightEye = isRightEye;
  77402. _this._distortionFactors = vrMetrics.distortionK;
  77403. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  77404. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  77405. _this.adaptScaleToCurrentViewport = true;
  77406. _this.onSizeChangedObservable.add(function () {
  77407. _this.aspectRatio = _this.width * .5 / _this.height;
  77408. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  77409. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  77410. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  77411. });
  77412. _this.onApplyObservable.add(function (effect) {
  77413. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  77414. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  77415. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  77416. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  77417. });
  77418. return _this;
  77419. }
  77420. return VRDistortionCorrectionPostProcess;
  77421. }(BABYLON.PostProcess));
  77422. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  77423. })(BABYLON || (BABYLON = {}));
  77424. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  77425. var BABYLON;
  77426. (function (BABYLON) {
  77427. var AnaglyphPostProcess = /** @class */ (function (_super) {
  77428. __extends(AnaglyphPostProcess, _super);
  77429. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  77430. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  77431. _this._passedProcess = rigCameras[0]._rigPostProcess;
  77432. _this.onApplyObservable.add(function (effect) {
  77433. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  77434. });
  77435. return _this;
  77436. }
  77437. return AnaglyphPostProcess;
  77438. }(BABYLON.PostProcess));
  77439. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  77440. })(BABYLON || (BABYLON = {}));
  77441. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  77442. var BABYLON;
  77443. (function (BABYLON) {
  77444. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  77445. __extends(StereoscopicInterlacePostProcess, _super);
  77446. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  77447. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  77448. _this._passedProcess = rigCameras[0]._rigPostProcess;
  77449. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  77450. _this.onSizeChangedObservable.add(function () {
  77451. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  77452. });
  77453. _this.onApplyObservable.add(function (effect) {
  77454. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  77455. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  77456. });
  77457. return _this;
  77458. }
  77459. return StereoscopicInterlacePostProcess;
  77460. }(BABYLON.PostProcess));
  77461. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  77462. })(BABYLON || (BABYLON = {}));
  77463. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  77464. var BABYLON;
  77465. (function (BABYLON) {
  77466. /**
  77467. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  77468. * Screen rotation is taken into account.
  77469. */
  77470. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  77471. function FreeCameraDeviceOrientationInput() {
  77472. var _this = this;
  77473. this._screenOrientationAngle = 0;
  77474. this._screenQuaternion = new BABYLON.Quaternion();
  77475. this._alpha = 0;
  77476. this._beta = 0;
  77477. this._gamma = 0;
  77478. this._orientationChanged = function () {
  77479. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  77480. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  77481. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  77482. };
  77483. this._deviceOrientation = function (evt) {
  77484. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  77485. _this._beta = evt.beta !== null ? evt.beta : 0;
  77486. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  77487. };
  77488. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  77489. this._orientationChanged();
  77490. }
  77491. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  77492. get: function () {
  77493. return this._camera;
  77494. },
  77495. set: function (camera) {
  77496. this._camera = camera;
  77497. if (this._camera != null && !this._camera.rotationQuaternion) {
  77498. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  77499. }
  77500. },
  77501. enumerable: true,
  77502. configurable: true
  77503. });
  77504. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  77505. window.addEventListener("orientationchange", this._orientationChanged);
  77506. window.addEventListener("deviceorientation", this._deviceOrientation);
  77507. //In certain cases, the attach control is called AFTER orientation was changed,
  77508. //So this is needed.
  77509. this._orientationChanged();
  77510. };
  77511. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  77512. window.removeEventListener("orientationchange", this._orientationChanged);
  77513. window.removeEventListener("deviceorientation", this._deviceOrientation);
  77514. };
  77515. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  77516. //if no device orientation provided, don't update the rotation.
  77517. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  77518. if (!this._alpha)
  77519. return;
  77520. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  77521. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  77522. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  77523. //Mirror on XY Plane
  77524. this._camera.rotationQuaternion.z *= -1;
  77525. this._camera.rotationQuaternion.w *= -1;
  77526. };
  77527. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  77528. return "FreeCameraDeviceOrientationInput";
  77529. };
  77530. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  77531. return "deviceOrientation";
  77532. };
  77533. return FreeCameraDeviceOrientationInput;
  77534. }());
  77535. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  77536. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  77537. })(BABYLON || (BABYLON = {}));
  77538. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  77539. var BABYLON;
  77540. (function (BABYLON) {
  77541. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  77542. function ArcRotateCameraVRDeviceOrientationInput() {
  77543. this.alphaCorrection = 1;
  77544. this.betaCorrection = 1;
  77545. this.gammaCorrection = 1;
  77546. this._alpha = 0;
  77547. this._gamma = 0;
  77548. this._dirty = false;
  77549. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  77550. }
  77551. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  77552. this.camera.attachControl(element, noPreventDefault);
  77553. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  77554. };
  77555. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  77556. if (evt.alpha !== null) {
  77557. this._alpha = +evt.alpha | 0;
  77558. }
  77559. if (evt.gamma !== null) {
  77560. this._gamma = +evt.gamma | 0;
  77561. }
  77562. this._dirty = true;
  77563. };
  77564. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  77565. if (this._dirty) {
  77566. this._dirty = false;
  77567. if (this._gamma < 0) {
  77568. this._gamma = 180 + this._gamma;
  77569. }
  77570. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  77571. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  77572. }
  77573. };
  77574. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  77575. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  77576. };
  77577. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  77578. return "ArcRotateCameraVRDeviceOrientationInput";
  77579. };
  77580. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  77581. return "VRDeviceOrientation";
  77582. };
  77583. return ArcRotateCameraVRDeviceOrientationInput;
  77584. }());
  77585. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  77586. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  77587. })(BABYLON || (BABYLON = {}));
  77588. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  77589. var BABYLON;
  77590. (function (BABYLON) {
  77591. var VRCameraMetrics = /** @class */ (function () {
  77592. function VRCameraMetrics() {
  77593. this.compensateDistortion = true;
  77594. }
  77595. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  77596. get: function () {
  77597. return this.hResolution / (2 * this.vResolution);
  77598. },
  77599. enumerable: true,
  77600. configurable: true
  77601. });
  77602. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  77603. get: function () {
  77604. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  77605. },
  77606. enumerable: true,
  77607. configurable: true
  77608. });
  77609. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  77610. get: function () {
  77611. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  77612. var h = (4 * meters) / this.hScreenSize;
  77613. return BABYLON.Matrix.Translation(h, 0, 0);
  77614. },
  77615. enumerable: true,
  77616. configurable: true
  77617. });
  77618. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  77619. get: function () {
  77620. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  77621. var h = (4 * meters) / this.hScreenSize;
  77622. return BABYLON.Matrix.Translation(-h, 0, 0);
  77623. },
  77624. enumerable: true,
  77625. configurable: true
  77626. });
  77627. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  77628. get: function () {
  77629. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  77630. },
  77631. enumerable: true,
  77632. configurable: true
  77633. });
  77634. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  77635. get: function () {
  77636. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  77637. },
  77638. enumerable: true,
  77639. configurable: true
  77640. });
  77641. VRCameraMetrics.GetDefault = function () {
  77642. var result = new VRCameraMetrics();
  77643. result.hResolution = 1280;
  77644. result.vResolution = 800;
  77645. result.hScreenSize = 0.149759993;
  77646. result.vScreenSize = 0.0935999975;
  77647. result.vScreenCenter = 0.0467999987;
  77648. result.eyeToScreenDistance = 0.0410000011;
  77649. result.lensSeparationDistance = 0.0635000020;
  77650. result.interpupillaryDistance = 0.0640000030;
  77651. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  77652. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  77653. result.postProcessScaleFactor = 1.714605507808412;
  77654. result.lensCenterOffset = 0.151976421;
  77655. return result;
  77656. };
  77657. return VRCameraMetrics;
  77658. }());
  77659. BABYLON.VRCameraMetrics = VRCameraMetrics;
  77660. })(BABYLON || (BABYLON = {}));
  77661. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  77662. var BABYLON;
  77663. (function (BABYLON) {
  77664. /**
  77665. * This represents a WebVR camera.
  77666. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  77667. * @example http://doc.babylonjs.com/how_to/webvr_camera
  77668. */
  77669. var WebVRFreeCamera = /** @class */ (function (_super) {
  77670. __extends(WebVRFreeCamera, _super);
  77671. /**
  77672. * Instantiates a WebVRFreeCamera.
  77673. * @param name The name of the WebVRFreeCamera
  77674. * @param position The starting anchor position for the camera
  77675. * @param scene The scene the camera belongs to
  77676. * @param webVROptions a set of customizable options for the webVRCamera
  77677. */
  77678. function WebVRFreeCamera(name, position, scene, webVROptions) {
  77679. if (webVROptions === void 0) { webVROptions = {}; }
  77680. var _this = _super.call(this, name, position, scene) || this;
  77681. _this.webVROptions = webVROptions;
  77682. /**
  77683. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  77684. */
  77685. _this._vrDevice = null;
  77686. /**
  77687. * The rawPose of the vrDevice.
  77688. */
  77689. _this.rawPose = null;
  77690. _this._specsVersion = "1.1";
  77691. _this._attached = false;
  77692. _this._descendants = [];
  77693. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  77694. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  77695. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  77696. _this._standingMatrix = null;
  77697. /**
  77698. * Represents device position in babylon space.
  77699. */
  77700. _this.devicePosition = BABYLON.Vector3.Zero();
  77701. /**
  77702. * Represents device rotation in babylon space.
  77703. */
  77704. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  77705. /**
  77706. * The scale of the device to be used when translating from device space to babylon space.
  77707. */
  77708. _this.deviceScaleFactor = 1;
  77709. _this._deviceToWorld = BABYLON.Matrix.Identity();
  77710. _this._worldToDevice = BABYLON.Matrix.Identity();
  77711. /**
  77712. * References to the webVR controllers for the vrDevice.
  77713. */
  77714. _this.controllers = [];
  77715. /**
  77716. * Emits an event when a controller is attached.
  77717. */
  77718. _this.onControllersAttachedObservable = new BABYLON.Observable();
  77719. /**
  77720. * Emits an event when a controller's mesh has been loaded;
  77721. */
  77722. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  77723. /**
  77724. * If the rig cameras be used as parent instead of this camera.
  77725. */
  77726. _this.rigParenting = true;
  77727. _this._defaultHeight = undefined;
  77728. _this._workingVector = BABYLON.Vector3.Zero();
  77729. _this._oneVector = BABYLON.Vector3.One();
  77730. _this._workingMatrix = BABYLON.Matrix.Identity();
  77731. _this._cache.position = BABYLON.Vector3.Zero();
  77732. if (webVROptions.defaultHeight) {
  77733. _this._defaultHeight = webVROptions.defaultHeight;
  77734. _this.position.y = _this._defaultHeight;
  77735. }
  77736. _this.minZ = 0.1;
  77737. //legacy support - the compensation boolean was removed.
  77738. if (arguments.length === 5) {
  77739. _this.webVROptions = arguments[4];
  77740. }
  77741. // default webVR options
  77742. if (_this.webVROptions.trackPosition == undefined) {
  77743. _this.webVROptions.trackPosition = true;
  77744. }
  77745. if (_this.webVROptions.controllerMeshes == undefined) {
  77746. _this.webVROptions.controllerMeshes = true;
  77747. }
  77748. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  77749. _this.webVROptions.defaultLightingOnControllers = true;
  77750. }
  77751. _this.rotationQuaternion = new BABYLON.Quaternion();
  77752. if (_this.webVROptions && _this.webVROptions.positionScale) {
  77753. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  77754. }
  77755. //enable VR
  77756. var engine = _this.getEngine();
  77757. _this._onVREnabled = function (success) { if (success) {
  77758. _this.initControllers();
  77759. } };
  77760. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  77761. engine.initWebVR().add(function (event) {
  77762. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  77763. return;
  77764. }
  77765. _this._vrDevice = event.vrDisplay;
  77766. //reset the rig parameters.
  77767. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  77768. if (_this._attached) {
  77769. _this.getEngine().enableVR();
  77770. }
  77771. });
  77772. if (typeof (VRFrameData) !== "undefined")
  77773. _this._frameData = new VRFrameData();
  77774. /**
  77775. * The idea behind the following lines:
  77776. * objects that have the camera as parent should actually have the rig cameras as a parent.
  77777. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  77778. * the second will not show it correctly.
  77779. *
  77780. * To solve this - each object that has the camera as parent will be added to a protected array.
  77781. * When the rig camera renders, it will take this array and set all of those to be its children.
  77782. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  77783. * Amazing!
  77784. */
  77785. scene.onBeforeCameraRenderObservable.add(function (camera) {
  77786. if (camera.parent === _this && _this.rigParenting) {
  77787. _this._descendants = _this.getDescendants(true, function (n) {
  77788. // don't take the cameras or the controllers!
  77789. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  77790. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  77791. return !isController && !isRigCamera;
  77792. });
  77793. _this._descendants.forEach(function (node) {
  77794. node.parent = camera;
  77795. });
  77796. }
  77797. });
  77798. scene.onAfterCameraRenderObservable.add(function (camera) {
  77799. if (camera.parent === _this && _this.rigParenting) {
  77800. _this._descendants.forEach(function (node) {
  77801. node.parent = _this;
  77802. });
  77803. }
  77804. });
  77805. return _this;
  77806. }
  77807. /**
  77808. * Gets the device distance from the ground.
  77809. * @returns the distance from the vrDevice to ground in device space. If standing matrix is not supported for the vrDevice 0 is returned.
  77810. */
  77811. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  77812. if (this._standingMatrix && this._defaultHeight === undefined) {
  77813. // Add standing matrix offset to get real offset from ground in room
  77814. this._standingMatrix.getTranslationToRef(this._workingVector);
  77815. return this._deviceRoomPosition.y + this._workingVector.y;
  77816. }
  77817. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  77818. return this._defaultHeight || 0;
  77819. };
  77820. /**
  77821. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  77822. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  77823. */
  77824. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  77825. var _this = this;
  77826. if (callback === void 0) { callback = function (bool) { }; }
  77827. // Use standing matrix if available
  77828. if (!navigator || !navigator.getVRDisplays) {
  77829. callback(false);
  77830. }
  77831. else {
  77832. navigator.getVRDisplays().then(function (displays) {
  77833. if (!displays || !displays[0] || !displays[0].stageParameters || !displays[0].stageParameters.sittingToStandingTransform) {
  77834. callback(false);
  77835. }
  77836. else {
  77837. _this._standingMatrix = new BABYLON.Matrix();
  77838. BABYLON.Matrix.FromFloat32ArrayToRefScaled(displays[0].stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  77839. if (!_this.getScene().useRightHandedSystem) {
  77840. [2, 6, 8, 9, 14].forEach(function (num) {
  77841. if (_this._standingMatrix) {
  77842. _this._standingMatrix.m[num] *= -1;
  77843. }
  77844. });
  77845. }
  77846. callback(true);
  77847. }
  77848. });
  77849. }
  77850. };
  77851. /**
  77852. * Disposes the camera
  77853. */
  77854. WebVRFreeCamera.prototype.dispose = function () {
  77855. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  77856. _super.prototype.dispose.call(this);
  77857. };
  77858. /**
  77859. * Gets a vrController by name.
  77860. * @param name The name of the controller to retreive
  77861. * @returns the controller matching the name specified or null if not found
  77862. */
  77863. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  77864. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  77865. var gp = _a[_i];
  77866. if (gp.hand === name) {
  77867. return gp;
  77868. }
  77869. }
  77870. return null;
  77871. };
  77872. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  77873. /**
  77874. * The controller corrisponding to the users left hand.
  77875. */
  77876. get: function () {
  77877. if (!this._leftController) {
  77878. this._leftController = this.getControllerByName("left");
  77879. }
  77880. return this._leftController;
  77881. },
  77882. enumerable: true,
  77883. configurable: true
  77884. });
  77885. ;
  77886. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  77887. /**
  77888. * The controller corrisponding to the users right hand.
  77889. */
  77890. get: function () {
  77891. if (!this._rightController) {
  77892. this._rightController = this.getControllerByName("right");
  77893. }
  77894. return this._rightController;
  77895. },
  77896. enumerable: true,
  77897. configurable: true
  77898. });
  77899. ;
  77900. /**
  77901. * Casts a ray forward from the vrCamera's gaze.
  77902. * @param length Length of the ray (default: 100)
  77903. * @returns the ray corrisponding to the gaze
  77904. */
  77905. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  77906. if (length === void 0) { length = 100; }
  77907. if (this.leftCamera) {
  77908. // Use left eye to avoid computation to compute center on every call
  77909. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  77910. }
  77911. else {
  77912. return _super.prototype.getForwardRay.call(this, length);
  77913. }
  77914. };
  77915. /**
  77916. * Updates the camera based on device's frame data
  77917. */
  77918. WebVRFreeCamera.prototype._checkInputs = function () {
  77919. if (this._vrDevice && this._vrDevice.isPresenting) {
  77920. this._vrDevice.getFrameData(this._frameData);
  77921. this.updateFromDevice(this._frameData.pose);
  77922. }
  77923. _super.prototype._checkInputs.call(this);
  77924. };
  77925. /**
  77926. * Updates the poseControlled values based on the input device pose.
  77927. * @param poseData Pose coming from the device
  77928. */
  77929. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  77930. if (poseData && poseData.orientation) {
  77931. this.rawPose = poseData;
  77932. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  77933. if (this.getScene().useRightHandedSystem) {
  77934. this._deviceRoomRotationQuaternion.z *= -1;
  77935. this._deviceRoomRotationQuaternion.w *= -1;
  77936. }
  77937. if (this.webVROptions.trackPosition && this.rawPose.position) {
  77938. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  77939. if (this.getScene().useRightHandedSystem) {
  77940. this._deviceRoomPosition.z *= -1;
  77941. }
  77942. }
  77943. }
  77944. };
  77945. /**
  77946. * WebVR's attach control will start broadcasting frames to the device.
  77947. * Note that in certain browsers (chrome for example) this function must be called
  77948. * within a user-interaction callback. Example:
  77949. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  77950. *
  77951. * @param element html element to attach the vrDevice to
  77952. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  77953. */
  77954. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  77955. _super.prototype.attachControl.call(this, element, noPreventDefault);
  77956. this._attached = true;
  77957. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  77958. if (this._vrDevice) {
  77959. this.getEngine().enableVR();
  77960. }
  77961. };
  77962. /**
  77963. * Detaches the camera from the html element and disables VR
  77964. *
  77965. * @param element html element to detach from
  77966. */
  77967. WebVRFreeCamera.prototype.detachControl = function (element) {
  77968. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  77969. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  77970. _super.prototype.detachControl.call(this, element);
  77971. this._attached = false;
  77972. this.getEngine().disableVR();
  77973. };
  77974. /**
  77975. * @returns the name of this class
  77976. */
  77977. WebVRFreeCamera.prototype.getClassName = function () {
  77978. return "WebVRFreeCamera";
  77979. };
  77980. /**
  77981. * Calls resetPose on the vrDisplay
  77982. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  77983. */
  77984. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  77985. //uses the vrDisplay's "resetPose()".
  77986. //pitch and roll won't be affected.
  77987. this._vrDevice.resetPose();
  77988. };
  77989. /**
  77990. * Updates the rig cameras (left and right eye)
  77991. */
  77992. WebVRFreeCamera.prototype._updateRigCameras = function () {
  77993. var camLeft = this._rigCameras[0];
  77994. var camRight = this._rigCameras[1];
  77995. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  77996. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  77997. camLeft.position.copyFrom(this._deviceRoomPosition);
  77998. camRight.position.copyFrom(this._deviceRoomPosition);
  77999. };
  78000. /**
  78001. * Updates the cached values of the camera
  78002. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  78003. */
  78004. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  78005. var _this = this;
  78006. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  78007. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  78008. if (!this.updateCacheCalled) {
  78009. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  78010. this.updateCacheCalled = true;
  78011. this.update();
  78012. }
  78013. // Set working vector to the device position in room space rotated by the new rotation
  78014. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  78015. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  78016. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  78017. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  78018. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  78019. // Add translation from anchor position
  78020. this._deviceToWorld.getTranslationToRef(this._workingVector);
  78021. this._workingVector.addInPlace(this.position);
  78022. this._workingVector.subtractInPlace(this._cache.position);
  78023. this._deviceToWorld.setTranslation(this._workingVector);
  78024. // Set an inverted matrix to be used when updating the camera
  78025. this._deviceToWorld.invertToRef(this._worldToDevice);
  78026. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  78027. this.controllers.forEach(function (controller) {
  78028. controller._deviceToWorld = _this._deviceToWorld;
  78029. controller.update();
  78030. });
  78031. }
  78032. if (!ignoreParentClass) {
  78033. _super.prototype._updateCache.call(this);
  78034. }
  78035. this.updateCacheCalled = false;
  78036. };
  78037. /**
  78038. * Updates the current device position and rotation in the babylon world
  78039. */
  78040. WebVRFreeCamera.prototype.update = function () {
  78041. // Get current device position in babylon world
  78042. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  78043. // Get current device rotation in babylon world
  78044. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  78045. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  78046. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  78047. _super.prototype.update.call(this);
  78048. };
  78049. /**
  78050. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  78051. * @returns an identity matrix
  78052. */
  78053. WebVRFreeCamera.prototype._getViewMatrix = function () {
  78054. return BABYLON.Matrix.Identity();
  78055. };
  78056. /**
  78057. * This function is called by the two RIG cameras.
  78058. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  78059. */
  78060. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  78061. var _this = this;
  78062. //WebVR 1.1
  78063. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  78064. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  78065. if (!this.getScene().useRightHandedSystem) {
  78066. [2, 6, 8, 9, 14].forEach(function (num) {
  78067. _this._webvrViewMatrix.m[num] *= -1;
  78068. });
  78069. }
  78070. // update the camera rotation matrix
  78071. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  78072. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  78073. // Computing target and final matrix
  78074. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  78075. var parentCamera = this._cameraRigParams["parentCamera"];
  78076. // should the view matrix be updated with scale and position offset?
  78077. if (parentCamera.deviceScaleFactor !== 1) {
  78078. this._webvrViewMatrix.invert();
  78079. // scale the position, if set
  78080. if (parentCamera.deviceScaleFactor) {
  78081. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  78082. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  78083. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  78084. }
  78085. this._webvrViewMatrix.invert();
  78086. }
  78087. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  78088. return this._webvrViewMatrix;
  78089. };
  78090. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  78091. var _this = this;
  78092. var parentCamera = this.parent;
  78093. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  78094. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  78095. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  78096. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  78097. //babylon compatible matrix
  78098. if (!this.getScene().useRightHandedSystem) {
  78099. [8, 9, 10, 11].forEach(function (num) {
  78100. _this._projectionMatrix.m[num] *= -1;
  78101. });
  78102. }
  78103. return this._projectionMatrix;
  78104. };
  78105. /**
  78106. * Initializes the controllers and their meshes
  78107. */
  78108. WebVRFreeCamera.prototype.initControllers = function () {
  78109. var _this = this;
  78110. this.controllers = [];
  78111. var manager = this.getScene().gamepadManager;
  78112. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  78113. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  78114. var webVrController = gamepad;
  78115. if (webVrController.defaultModel) {
  78116. webVrController.defaultModel.setEnabled(false);
  78117. }
  78118. if (webVrController.hand === "right") {
  78119. _this._rightController = null;
  78120. }
  78121. if (webVrController.hand === "left") {
  78122. _this._rightController = null;
  78123. }
  78124. var controllerIndex = _this.controllers.indexOf(webVrController);
  78125. if (controllerIndex !== -1) {
  78126. _this.controllers.splice(controllerIndex, 1);
  78127. }
  78128. }
  78129. });
  78130. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  78131. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  78132. var webVrController_1 = gamepad;
  78133. webVrController_1._deviceToWorld = _this._deviceToWorld;
  78134. if (_this.webVROptions.controllerMeshes) {
  78135. if (webVrController_1.defaultModel) {
  78136. webVrController_1.defaultModel.setEnabled(true);
  78137. }
  78138. else {
  78139. // Load the meshes
  78140. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  78141. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  78142. if (_this.webVROptions.defaultLightingOnControllers) {
  78143. if (!_this._lightOnControllers) {
  78144. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  78145. }
  78146. var activateLightOnSubMeshes_1 = function (mesh, light) {
  78147. var children = mesh.getChildren();
  78148. if (children.length !== 0) {
  78149. children.forEach(function (mesh) {
  78150. light.includedOnlyMeshes.push(mesh);
  78151. activateLightOnSubMeshes_1(mesh, light);
  78152. });
  78153. }
  78154. };
  78155. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  78156. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  78157. }
  78158. });
  78159. }
  78160. }
  78161. webVrController_1.attachToPoseControlledCamera(_this);
  78162. // since this is async - sanity check. Is the controller already stored?
  78163. if (_this.controllers.indexOf(webVrController_1) === -1) {
  78164. //add to the controllers array
  78165. _this.controllers.push(webVrController_1);
  78166. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  78167. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  78168. // So we're overriding setting left & right manually to be sure
  78169. var firstViveWandDetected = false;
  78170. for (var i = 0; i < _this.controllers.length; i++) {
  78171. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  78172. if (!firstViveWandDetected) {
  78173. firstViveWandDetected = true;
  78174. _this.controllers[i].hand = "left";
  78175. }
  78176. else {
  78177. _this.controllers[i].hand = "right";
  78178. }
  78179. }
  78180. }
  78181. //did we find enough controllers? Great! let the developer know.
  78182. if (_this.controllers.length >= 2) {
  78183. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  78184. }
  78185. }
  78186. }
  78187. });
  78188. };
  78189. return WebVRFreeCamera;
  78190. }(BABYLON.FreeCamera));
  78191. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  78192. })(BABYLON || (BABYLON = {}));
  78193. //# sourceMappingURL=babylon.webVRCamera.js.map
  78194. var BABYLON;
  78195. (function (BABYLON) {
  78196. // We're mainly based on the logic defined into the FreeCamera code
  78197. /**
  78198. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  78199. * being tilted forward or back and left or right.
  78200. */
  78201. var DeviceOrientationCamera = /** @class */ (function (_super) {
  78202. __extends(DeviceOrientationCamera, _super);
  78203. /**
  78204. * Creates a new device orientation camera. @see DeviceOrientationCamera
  78205. * @param name The name of the camera
  78206. * @param position The start position camera
  78207. * @param scene The scene the camera belongs to
  78208. */
  78209. function DeviceOrientationCamera(name, position, scene) {
  78210. var _this = _super.call(this, name, position, scene) || this;
  78211. _this._quaternionCache = new BABYLON.Quaternion();
  78212. _this.inputs.addDeviceOrientation();
  78213. return _this;
  78214. }
  78215. /**
  78216. * Gets the current instance class name ("DeviceOrientationCamera").
  78217. * This helps avoiding instanceof at run time.
  78218. * @returns the class name
  78219. */
  78220. DeviceOrientationCamera.prototype.getClassName = function () {
  78221. return "DeviceOrientationCamera";
  78222. };
  78223. /**
  78224. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  78225. */
  78226. DeviceOrientationCamera.prototype._checkInputs = function () {
  78227. _super.prototype._checkInputs.call(this);
  78228. this._quaternionCache.copyFrom(this.rotationQuaternion);
  78229. if (this._initialQuaternion) {
  78230. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  78231. }
  78232. };
  78233. /**
  78234. * Reset the camera to its default orientation on the specified axis only.
  78235. * @param axis The axis to reset
  78236. */
  78237. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  78238. var _this = this;
  78239. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  78240. //can only work if this camera has a rotation quaternion already.
  78241. if (!this.rotationQuaternion)
  78242. return;
  78243. if (!this._initialQuaternion) {
  78244. this._initialQuaternion = new BABYLON.Quaternion();
  78245. }
  78246. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  78247. ['x', 'y', 'z'].forEach(function (axisName) {
  78248. if (!axis[axisName]) {
  78249. _this._initialQuaternion[axisName] = 0;
  78250. }
  78251. else {
  78252. _this._initialQuaternion[axisName] *= -1;
  78253. }
  78254. });
  78255. this._initialQuaternion.normalize();
  78256. //force rotation update
  78257. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  78258. };
  78259. return DeviceOrientationCamera;
  78260. }(BABYLON.FreeCamera));
  78261. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  78262. })(BABYLON || (BABYLON = {}));
  78263. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  78264. var BABYLON;
  78265. (function (BABYLON) {
  78266. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  78267. __extends(VRDeviceOrientationFreeCamera, _super);
  78268. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  78269. if (compensateDistortion === void 0) { compensateDistortion = true; }
  78270. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  78271. var _this = _super.call(this, name, position, scene) || this;
  78272. vrCameraMetrics.compensateDistortion = compensateDistortion;
  78273. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  78274. return _this;
  78275. }
  78276. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  78277. return "VRDeviceOrientationFreeCamera";
  78278. };
  78279. return VRDeviceOrientationFreeCamera;
  78280. }(BABYLON.DeviceOrientationCamera));
  78281. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  78282. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  78283. __extends(VRDeviceOrientationGamepadCamera, _super);
  78284. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  78285. if (compensateDistortion === void 0) { compensateDistortion = true; }
  78286. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  78287. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  78288. _this.inputs.addGamepad();
  78289. return _this;
  78290. }
  78291. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  78292. return "VRDeviceOrientationGamepadCamera";
  78293. };
  78294. return VRDeviceOrientationGamepadCamera;
  78295. }(VRDeviceOrientationFreeCamera));
  78296. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  78297. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  78298. __extends(VRDeviceOrientationArcRotateCamera, _super);
  78299. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  78300. if (compensateDistortion === void 0) { compensateDistortion = true; }
  78301. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  78302. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  78303. vrCameraMetrics.compensateDistortion = compensateDistortion;
  78304. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  78305. _this.inputs.addVRDeviceOrientation();
  78306. return _this;
  78307. }
  78308. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  78309. return "VRDeviceOrientationArcRotateCamera";
  78310. };
  78311. return VRDeviceOrientationArcRotateCamera;
  78312. }(BABYLON.ArcRotateCamera));
  78313. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  78314. })(BABYLON || (BABYLON = {}));
  78315. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  78316. var BABYLON;
  78317. (function (BABYLON) {
  78318. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  78319. __extends(AnaglyphFreeCamera, _super);
  78320. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  78321. var _this = _super.call(this, name, position, scene) || this;
  78322. _this.interaxialDistance = interaxialDistance;
  78323. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  78324. return _this;
  78325. }
  78326. AnaglyphFreeCamera.prototype.getClassName = function () {
  78327. return "AnaglyphFreeCamera";
  78328. };
  78329. return AnaglyphFreeCamera;
  78330. }(BABYLON.FreeCamera));
  78331. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  78332. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  78333. __extends(AnaglyphArcRotateCamera, _super);
  78334. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  78335. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  78336. _this.interaxialDistance = interaxialDistance;
  78337. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  78338. return _this;
  78339. }
  78340. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  78341. return "AnaglyphArcRotateCamera";
  78342. };
  78343. return AnaglyphArcRotateCamera;
  78344. }(BABYLON.ArcRotateCamera));
  78345. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  78346. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  78347. __extends(AnaglyphGamepadCamera, _super);
  78348. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  78349. var _this = _super.call(this, name, position, scene) || this;
  78350. _this.interaxialDistance = interaxialDistance;
  78351. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  78352. return _this;
  78353. }
  78354. AnaglyphGamepadCamera.prototype.getClassName = function () {
  78355. return "AnaglyphGamepadCamera";
  78356. };
  78357. return AnaglyphGamepadCamera;
  78358. }(BABYLON.GamepadCamera));
  78359. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  78360. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  78361. __extends(AnaglyphUniversalCamera, _super);
  78362. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  78363. var _this = _super.call(this, name, position, scene) || this;
  78364. _this.interaxialDistance = interaxialDistance;
  78365. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  78366. return _this;
  78367. }
  78368. AnaglyphUniversalCamera.prototype.getClassName = function () {
  78369. return "AnaglyphUniversalCamera";
  78370. };
  78371. return AnaglyphUniversalCamera;
  78372. }(BABYLON.UniversalCamera));
  78373. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  78374. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  78375. __extends(StereoscopicFreeCamera, _super);
  78376. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  78377. var _this = _super.call(this, name, position, scene) || this;
  78378. _this.interaxialDistance = interaxialDistance;
  78379. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  78380. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  78381. return _this;
  78382. }
  78383. StereoscopicFreeCamera.prototype.getClassName = function () {
  78384. return "StereoscopicFreeCamera";
  78385. };
  78386. return StereoscopicFreeCamera;
  78387. }(BABYLON.FreeCamera));
  78388. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  78389. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  78390. __extends(StereoscopicArcRotateCamera, _super);
  78391. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  78392. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  78393. _this.interaxialDistance = interaxialDistance;
  78394. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  78395. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  78396. return _this;
  78397. }
  78398. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  78399. return "StereoscopicArcRotateCamera";
  78400. };
  78401. return StereoscopicArcRotateCamera;
  78402. }(BABYLON.ArcRotateCamera));
  78403. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  78404. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  78405. __extends(StereoscopicGamepadCamera, _super);
  78406. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  78407. var _this = _super.call(this, name, position, scene) || this;
  78408. _this.interaxialDistance = interaxialDistance;
  78409. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  78410. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  78411. return _this;
  78412. }
  78413. StereoscopicGamepadCamera.prototype.getClassName = function () {
  78414. return "StereoscopicGamepadCamera";
  78415. };
  78416. return StereoscopicGamepadCamera;
  78417. }(BABYLON.GamepadCamera));
  78418. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  78419. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  78420. __extends(StereoscopicUniversalCamera, _super);
  78421. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  78422. var _this = _super.call(this, name, position, scene) || this;
  78423. _this.interaxialDistance = interaxialDistance;
  78424. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  78425. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  78426. return _this;
  78427. }
  78428. StereoscopicUniversalCamera.prototype.getClassName = function () {
  78429. return "StereoscopicUniversalCamera";
  78430. };
  78431. return StereoscopicUniversalCamera;
  78432. }(BABYLON.UniversalCamera));
  78433. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  78434. })(BABYLON || (BABYLON = {}));
  78435. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  78436. var BABYLON;
  78437. (function (BABYLON) {
  78438. /**
  78439. * Helps to quickly add VR support to an existing scene.
  78440. * See http://doc.babylonjs.com/how_to/webvr_helper
  78441. */
  78442. var VRExperienceHelper = /** @class */ (function () {
  78443. /**
  78444. * Instantiates a VRExperienceHelper.
  78445. * Helps to quickly add VR support to an existing scene.
  78446. * @param scene The scene the VRExperienceHelper belongs to.
  78447. * @param webVROptions Options to modify the vr experience helper's behavior.
  78448. */
  78449. function VRExperienceHelper(scene, /** Options to modify the vr experience helper's behavior. */ webVROptions) {
  78450. if (webVROptions === void 0) { webVROptions = {}; }
  78451. var _this = this;
  78452. this.webVROptions = webVROptions;
  78453. // Can the system support WebVR, even if a headset isn't plugged in?
  78454. this._webVRsupported = false;
  78455. // If WebVR is supported, is a headset plugged in and are we ready to present?
  78456. this._webVRready = false;
  78457. // Are we waiting for the requestPresent callback to complete?
  78458. this._webVRrequesting = false;
  78459. // Are we presenting to the headset right now?
  78460. this._webVRpresenting = false;
  78461. // Are we presenting in the fullscreen fallback?
  78462. this._fullscreenVRpresenting = false;
  78463. /**
  78464. * Observable raised when entering VR.
  78465. */
  78466. this.onEnteringVRObservable = new BABYLON.Observable();
  78467. /**
  78468. * Observable raised when exiting VR.
  78469. */
  78470. this.onExitingVRObservable = new BABYLON.Observable();
  78471. /**
  78472. * Observable raised when controller mesh is loaded.
  78473. */
  78474. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  78475. this._useCustomVRButton = false;
  78476. this._teleportationRequested = false;
  78477. this._teleportationEnabledOnLeftController = false;
  78478. this._teleportationEnabledOnRightController = false;
  78479. this._interactionsEnabledOnLeftController = false;
  78480. this._interactionsEnabledOnRightController = false;
  78481. this._leftControllerReady = false;
  78482. this._rightControllerReady = false;
  78483. this._floorMeshesCollection = [];
  78484. this._teleportationAllowed = false;
  78485. this._rotationAllowed = true;
  78486. this._teleportationRequestInitiated = false;
  78487. this._teleportationBackRequestInitiated = false;
  78488. this.teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  78489. this._rotationRightAsked = false;
  78490. this._rotationLeftAsked = false;
  78491. this._isDefaultTeleportationTarget = true;
  78492. this._teleportationFillColor = "#444444";
  78493. this._teleportationBorderColor = "#FFFFFF";
  78494. this._rotationAngle = 0;
  78495. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  78496. this._padSensibilityUp = 0.65;
  78497. this._padSensibilityDown = 0.35;
  78498. /**
  78499. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  78500. */
  78501. this.onNewMeshSelected = new BABYLON.Observable();
  78502. /**
  78503. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  78504. */
  78505. this.onNewMeshPicked = new BABYLON.Observable();
  78506. /**
  78507. * Observable raised before camera teleportation
  78508. */
  78509. this.onBeforeCameraTeleport = new BABYLON.Observable();
  78510. /**
  78511. * Observable raised after camera teleportation
  78512. */
  78513. this.onAfterCameraTeleport = new BABYLON.Observable();
  78514. /**
  78515. * Observable raised when current selected mesh gets unselected
  78516. */
  78517. this.onSelectedMeshUnselected = new BABYLON.Observable();
  78518. /**
  78519. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  78520. */
  78521. this.teleportationEnabled = true;
  78522. this._pointerDownOnMeshAsked = false;
  78523. this._isActionableMesh = false;
  78524. this._teleportationInitialized = false;
  78525. this._interactionsEnabled = false;
  78526. this._interactionsRequested = false;
  78527. this._displayGaze = true;
  78528. this._displayLaserPointer = true;
  78529. this._dpadPressed = true;
  78530. this._onResize = function () {
  78531. _this.moveButtonToBottomRight();
  78532. if (_this._fullscreenVRpresenting && _this._webVRready) {
  78533. _this.exitVR();
  78534. }
  78535. };
  78536. this._onFullscreenChange = function () {
  78537. if (document.fullscreen !== undefined) {
  78538. _this._fullscreenVRpresenting = document.fullscreen;
  78539. }
  78540. else if (document.mozFullScreen !== undefined) {
  78541. _this._fullscreenVRpresenting = document.mozFullScreen;
  78542. }
  78543. else if (document.webkitIsFullScreen !== undefined) {
  78544. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  78545. }
  78546. else if (document.msIsFullScreen !== undefined) {
  78547. _this._fullscreenVRpresenting = document.msIsFullScreen;
  78548. }
  78549. if (!_this._fullscreenVRpresenting && _this._canvas) {
  78550. _this.exitVR();
  78551. if (!_this._useCustomVRButton) {
  78552. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  78553. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  78554. }
  78555. }
  78556. };
  78557. this.beforeRender = function () {
  78558. _this._castRayAndSelectObject();
  78559. };
  78560. this._onNewGamepadConnected = function (gamepad) {
  78561. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  78562. if (gamepad.leftStick) {
  78563. gamepad.onleftstickchanged(function (stickValues) {
  78564. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  78565. // Listening to classic/xbox gamepad only if no VR controller is active
  78566. if ((!_this._leftLaserPointer && !_this._rightLaserPointer) ||
  78567. ((_this._leftLaserPointer && !_this._leftLaserPointer.isVisible) &&
  78568. (_this._rightLaserPointer && !_this._rightLaserPointer.isVisible))) {
  78569. _this._checkTeleportWithRay(stickValues);
  78570. _this._checkTeleportBackwards(stickValues);
  78571. }
  78572. }
  78573. });
  78574. }
  78575. if (gamepad.rightStick) {
  78576. gamepad.onrightstickchanged(function (stickValues) {
  78577. if (_this._teleportationInitialized) {
  78578. _this._checkRotate(stickValues);
  78579. }
  78580. });
  78581. }
  78582. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  78583. gamepad.onbuttondown(function (buttonPressed) {
  78584. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  78585. _this._selectionPointerDown();
  78586. }
  78587. });
  78588. gamepad.onbuttonup(function (buttonPressed) {
  78589. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  78590. _this._selectionPointerUp();
  78591. }
  78592. });
  78593. }
  78594. }
  78595. else {
  78596. var webVRController = gamepad;
  78597. _this._tryEnableInteractionOnController(webVRController);
  78598. }
  78599. };
  78600. // 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
  78601. this._tryEnableInteractionOnController = function (webVRController) {
  78602. if (webVRController.hand === "left") {
  78603. _this._leftControllerReady = true;
  78604. if (_this._interactionsRequested && !_this._interactionsEnabledOnLeftController) {
  78605. _this._enableInteractionOnController(webVRController);
  78606. }
  78607. if (_this._teleportationRequested && !_this._teleportationEnabledOnLeftController) {
  78608. _this._enableTeleportationOnController(webVRController);
  78609. }
  78610. }
  78611. if (webVRController.hand === "right") {
  78612. _this._rightControllerReady = true;
  78613. if (_this._interactionsRequested && !_this._interactionsEnabledOnRightController) {
  78614. _this._enableInteractionOnController(webVRController);
  78615. }
  78616. if (_this._teleportationRequested && !_this._teleportationEnabledOnRightController) {
  78617. _this._enableTeleportationOnController(webVRController);
  78618. }
  78619. }
  78620. };
  78621. this._onNewGamepadDisconnected = function (gamepad) {
  78622. if (gamepad instanceof BABYLON.WebVRController) {
  78623. if (gamepad.hand === "left") {
  78624. _this._interactionsEnabledOnLeftController = false;
  78625. _this._teleportationEnabledOnLeftController = false;
  78626. _this._leftControllerReady = false;
  78627. if (_this._leftLaserPointer) {
  78628. _this._leftLaserPointer.dispose();
  78629. }
  78630. }
  78631. if (gamepad.hand === "right") {
  78632. _this._interactionsEnabledOnRightController = false;
  78633. _this._teleportationEnabledOnRightController = false;
  78634. _this._rightControllerReady = false;
  78635. if (_this._rightLaserPointer) {
  78636. _this._rightLaserPointer.dispose();
  78637. }
  78638. }
  78639. }
  78640. };
  78641. this._workingVector = BABYLON.Vector3.Zero();
  78642. this._workingQuaternion = BABYLON.Quaternion.Identity();
  78643. this._workingMatrix = BABYLON.Matrix.Identity();
  78644. this._scene = scene;
  78645. this._canvas = scene.getEngine().getRenderingCanvas();
  78646. // Parse options
  78647. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  78648. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  78649. }
  78650. if (webVROptions.createDeviceOrientationCamera === undefined) {
  78651. webVROptions.createDeviceOrientationCamera = true;
  78652. }
  78653. if (webVROptions.defaultHeight === undefined) {
  78654. webVROptions.defaultHeight = 1.7;
  78655. }
  78656. if (webVROptions.useCustomVRButton) {
  78657. this._useCustomVRButton = true;
  78658. if (webVROptions.customVRButton) {
  78659. this._btnVR = webVROptions.customVRButton;
  78660. }
  78661. }
  78662. if (webVROptions.rayLength) {
  78663. this._rayLength = webVROptions.rayLength;
  78664. }
  78665. this._defaultHeight = webVROptions.defaultHeight;
  78666. // Set position
  78667. if (this._scene.activeCamera) {
  78668. this._position = this._scene.activeCamera.position.clone();
  78669. }
  78670. else {
  78671. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  78672. }
  78673. // Set non-vr camera
  78674. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  78675. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  78676. // Copy data from existing camera
  78677. if (this._scene.activeCamera) {
  78678. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  78679. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  78680. // Set rotation from previous camera
  78681. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  78682. var targetCamera = this._scene.activeCamera;
  78683. if (targetCamera.rotationQuaternion) {
  78684. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  78685. }
  78686. else {
  78687. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  78688. }
  78689. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  78690. }
  78691. }
  78692. this._scene.activeCamera = this._deviceOrientationCamera;
  78693. if (this._canvas) {
  78694. this._scene.activeCamera.attachControl(this._canvas);
  78695. }
  78696. }
  78697. else {
  78698. this._existingCamera = this._scene.activeCamera;
  78699. }
  78700. // Create VR cameras
  78701. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  78702. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  78703. }
  78704. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  78705. this._webVRCamera.useStandingMatrix();
  78706. // Create default button
  78707. if (!this._useCustomVRButton) {
  78708. this._btnVR = document.createElement("BUTTON");
  78709. this._btnVR.className = "babylonVRicon";
  78710. this._btnVR.id = "babylonVRiconbtn";
  78711. this._btnVR.title = "Click to switch to VR";
  78712. 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) }";
  78713. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  78714. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  78715. // css += ".babylonVRicon.vrdisplaysupported { }";
  78716. // css += ".babylonVRicon.vrdisplayready { }";
  78717. // css += ".babylonVRicon.vrdisplayrequesting { }";
  78718. var style = document.createElement('style');
  78719. style.appendChild(document.createTextNode(css));
  78720. document.getElementsByTagName('head')[0].appendChild(style);
  78721. this.moveButtonToBottomRight();
  78722. }
  78723. // VR button click event
  78724. if (this._btnVR) {
  78725. this._btnVR.addEventListener("click", function () {
  78726. if (!_this.isInVRMode) {
  78727. _this.enterVR();
  78728. }
  78729. else {
  78730. _this.exitVR();
  78731. }
  78732. });
  78733. }
  78734. // Window events
  78735. window.addEventListener("resize", this._onResize);
  78736. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  78737. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  78738. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  78739. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  78740. // Display vr button when headset is connected
  78741. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  78742. this.displayVRButton();
  78743. }
  78744. else {
  78745. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  78746. if (e.vrDisplay) {
  78747. _this.displayVRButton();
  78748. }
  78749. });
  78750. }
  78751. // Exiting VR mode using 'ESC' key on desktop
  78752. this._onKeyDown = function (event) {
  78753. if (event.keyCode === 27 && _this.isInVRMode) {
  78754. _this.exitVR();
  78755. }
  78756. };
  78757. document.addEventListener("keydown", this._onKeyDown);
  78758. // Exiting VR mode double tapping the touch screen
  78759. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  78760. if (_this.isInVRMode) {
  78761. _this.exitVR();
  78762. if (_this._fullscreenVRpresenting) {
  78763. _this._scene.getEngine().switchFullscreen(true);
  78764. }
  78765. }
  78766. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  78767. // Listen for WebVR display changes
  78768. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  78769. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  78770. this._onVRRequestPresentStart = function () {
  78771. _this._webVRrequesting = true;
  78772. _this.updateButtonVisibility();
  78773. };
  78774. this._onVRRequestPresentComplete = function (success) {
  78775. _this._webVRrequesting = false;
  78776. _this.updateButtonVisibility();
  78777. };
  78778. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  78779. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  78780. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  78781. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  78782. scene.onDisposeObservable.add(function () {
  78783. _this.dispose();
  78784. });
  78785. // Gamepad connection events
  78786. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  78787. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  78788. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  78789. this.updateButtonVisibility();
  78790. //create easing functions
  78791. this._circleEase = new BABYLON.CircleEase();
  78792. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  78793. }
  78794. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  78795. /** Return this.onEnteringVRObservable
  78796. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  78797. */
  78798. get: function () {
  78799. return this.onEnteringVRObservable;
  78800. },
  78801. enumerable: true,
  78802. configurable: true
  78803. });
  78804. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  78805. /** Return this.onExitingVRObservable
  78806. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  78807. */
  78808. get: function () {
  78809. return this.onExitingVRObservable;
  78810. },
  78811. enumerable: true,
  78812. configurable: true
  78813. });
  78814. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  78815. /** Return this.onControllerMeshLoadedObservable
  78816. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  78817. */
  78818. get: function () {
  78819. return this.onControllerMeshLoadedObservable;
  78820. },
  78821. enumerable: true,
  78822. configurable: true
  78823. });
  78824. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  78825. /**
  78826. * The mesh used to display where the user is going to teleport.
  78827. */
  78828. get: function () {
  78829. return this._teleportationTarget;
  78830. },
  78831. /**
  78832. * Sets the mesh to be used to display where the user is going to teleport.
  78833. */
  78834. set: function (value) {
  78835. if (value) {
  78836. value.name = "teleportationTarget";
  78837. this._isDefaultTeleportationTarget = false;
  78838. this._teleportationTarget = value;
  78839. }
  78840. },
  78841. enumerable: true,
  78842. configurable: true
  78843. });
  78844. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  78845. /**
  78846. * The mesh used to display where the user is selecting.
  78847. */
  78848. get: function () {
  78849. return this._gazeTracker;
  78850. },
  78851. /**
  78852. * Sets the mesh to be used to display where the user is selecting.
  78853. */
  78854. set: function (value) {
  78855. if (value) {
  78856. this._gazeTracker = value;
  78857. this._gazeTracker.bakeCurrentTransformIntoVertices();
  78858. this._gazeTracker.isPickable = false;
  78859. this._gazeTracker.isVisible = false;
  78860. }
  78861. },
  78862. enumerable: true,
  78863. configurable: true
  78864. });
  78865. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  78866. /**
  78867. * If the ray of the gaze should be displayed.
  78868. */
  78869. get: function () {
  78870. return this._displayGaze;
  78871. },
  78872. /**
  78873. * Sets if the ray of the gaze should be displayed.
  78874. */
  78875. set: function (value) {
  78876. this._displayGaze = value;
  78877. if (!value) {
  78878. this._gazeTracker.isVisible = false;
  78879. }
  78880. },
  78881. enumerable: true,
  78882. configurable: true
  78883. });
  78884. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  78885. /**
  78886. * If the ray of the LaserPointer should be displayed.
  78887. */
  78888. get: function () {
  78889. return this._displayLaserPointer;
  78890. },
  78891. /**
  78892. * Sets if the ray of the LaserPointer should be displayed.
  78893. */
  78894. set: function (value) {
  78895. this._displayLaserPointer = value;
  78896. if (!value) {
  78897. if (this._rightLaserPointer) {
  78898. this._rightLaserPointer.isVisible = false;
  78899. }
  78900. if (this._leftLaserPointer) {
  78901. this._leftLaserPointer.isVisible = false;
  78902. }
  78903. }
  78904. else {
  78905. if (this._rightLaserPointer) {
  78906. this._rightLaserPointer.isVisible = true;
  78907. }
  78908. else if (this._leftLaserPointer) {
  78909. this._leftLaserPointer.isVisible = true;
  78910. }
  78911. }
  78912. },
  78913. enumerable: true,
  78914. configurable: true
  78915. });
  78916. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  78917. /**
  78918. * The deviceOrientationCamera used as the camera when not in VR.
  78919. */
  78920. get: function () {
  78921. return this._deviceOrientationCamera;
  78922. },
  78923. enumerable: true,
  78924. configurable: true
  78925. });
  78926. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  78927. /**
  78928. * Based on the current WebVR support, returns the current VR camera used.
  78929. */
  78930. get: function () {
  78931. if (this._webVRready) {
  78932. return this._webVRCamera;
  78933. }
  78934. else {
  78935. return this._scene.activeCamera;
  78936. }
  78937. },
  78938. enumerable: true,
  78939. configurable: true
  78940. });
  78941. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  78942. /**
  78943. * The webVRCamera which is used when in VR.
  78944. */
  78945. get: function () {
  78946. return this._webVRCamera;
  78947. },
  78948. enumerable: true,
  78949. configurable: true
  78950. });
  78951. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  78952. /**
  78953. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  78954. */
  78955. get: function () {
  78956. return this._vrDeviceOrientationCamera;
  78957. },
  78958. enumerable: true,
  78959. configurable: true
  78960. });
  78961. // Raised when one of the controller has loaded successfully its associated default mesh
  78962. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  78963. this._tryEnableInteractionOnController(webVRController);
  78964. try {
  78965. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  78966. }
  78967. catch (err) {
  78968. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  78969. }
  78970. };
  78971. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  78972. /**
  78973. * Gets a value indicating if we are currently in VR mode.
  78974. */
  78975. get: function () {
  78976. return this._webVRpresenting || this._fullscreenVRpresenting;
  78977. },
  78978. enumerable: true,
  78979. configurable: true
  78980. });
  78981. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  78982. var vrDisplay = this._scene.getEngine().getVRDevice();
  78983. if (vrDisplay) {
  78984. var wasPresenting = this._webVRpresenting;
  78985. // A VR display is connected
  78986. this._webVRpresenting = vrDisplay.isPresenting;
  78987. if (wasPresenting && !this._webVRpresenting)
  78988. this.exitVR();
  78989. }
  78990. else {
  78991. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  78992. }
  78993. this.updateButtonVisibility();
  78994. };
  78995. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  78996. this._webVRsupported = eventArgs.vrSupported;
  78997. this._webVRready = !!eventArgs.vrDisplay;
  78998. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  78999. this.updateButtonVisibility();
  79000. };
  79001. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  79002. if (this._canvas && !this._useCustomVRButton) {
  79003. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  79004. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  79005. }
  79006. };
  79007. VRExperienceHelper.prototype.displayVRButton = function () {
  79008. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  79009. document.body.appendChild(this._btnVR);
  79010. this._btnVRDisplayed = true;
  79011. }
  79012. };
  79013. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  79014. if (!this._btnVR || this._useCustomVRButton) {
  79015. return;
  79016. }
  79017. this._btnVR.className = "babylonVRicon";
  79018. if (this.isInVRMode) {
  79019. this._btnVR.className += " vrdisplaypresenting";
  79020. }
  79021. else {
  79022. if (this._webVRready)
  79023. this._btnVR.className += " vrdisplayready";
  79024. if (this._webVRsupported)
  79025. this._btnVR.className += " vrdisplaysupported";
  79026. if (this._webVRrequesting)
  79027. this._btnVR.className += " vrdisplayrequesting";
  79028. }
  79029. };
  79030. /**
  79031. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  79032. * Otherwise, will use the fullscreen API.
  79033. */
  79034. VRExperienceHelper.prototype.enterVR = function () {
  79035. if (this.onEnteringVRObservable) {
  79036. try {
  79037. this.onEnteringVRObservable.notifyObservers(this);
  79038. }
  79039. catch (err) {
  79040. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  79041. }
  79042. }
  79043. if (this._scene.activeCamera) {
  79044. this._position = this._scene.activeCamera.position.clone();
  79045. // make sure that we return to the last active camera
  79046. this._existingCamera = this._scene.activeCamera;
  79047. }
  79048. if (this._webVRrequesting)
  79049. return;
  79050. // If WebVR is supported and a headset is connected
  79051. if (this._webVRready) {
  79052. if (!this._webVRpresenting) {
  79053. this._webVRCamera.position = this._position;
  79054. this._scene.activeCamera = this._webVRCamera;
  79055. }
  79056. }
  79057. else if (this._vrDeviceOrientationCamera) {
  79058. this._vrDeviceOrientationCamera.position = this._position;
  79059. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  79060. this._scene.getEngine().switchFullscreen(true);
  79061. this.updateButtonVisibility();
  79062. }
  79063. if (this._scene.activeCamera && this._canvas) {
  79064. this._scene.activeCamera.attachControl(this._canvas);
  79065. }
  79066. if (this._interactionsEnabled) {
  79067. this._scene.registerBeforeRender(this.beforeRender);
  79068. }
  79069. };
  79070. /**
  79071. * Attempt to exit VR, or fullscreen.
  79072. */
  79073. VRExperienceHelper.prototype.exitVR = function () {
  79074. if (this.onExitingVRObservable) {
  79075. try {
  79076. this.onExitingVRObservable.notifyObservers(this);
  79077. }
  79078. catch (err) {
  79079. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  79080. }
  79081. }
  79082. if (this._webVRpresenting) {
  79083. this._scene.getEngine().disableVR();
  79084. }
  79085. if (this._scene.activeCamera) {
  79086. this._position = this._scene.activeCamera.position.clone();
  79087. }
  79088. if (this._deviceOrientationCamera) {
  79089. this._deviceOrientationCamera.position = this._position;
  79090. this._scene.activeCamera = this._deviceOrientationCamera;
  79091. if (this._canvas) {
  79092. this._scene.activeCamera.attachControl(this._canvas);
  79093. }
  79094. }
  79095. else if (this._existingCamera) {
  79096. this._existingCamera.position = this._position;
  79097. this._scene.activeCamera = this._existingCamera;
  79098. }
  79099. this.updateButtonVisibility();
  79100. if (this._interactionsEnabled) {
  79101. this._scene.unregisterBeforeRender(this.beforeRender);
  79102. }
  79103. };
  79104. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  79105. /**
  79106. * The position of the vr experience helper.
  79107. */
  79108. get: function () {
  79109. return this._position;
  79110. },
  79111. /**
  79112. * Sets the position of the vr experience helper.
  79113. */
  79114. set: function (value) {
  79115. this._position = value;
  79116. if (this._scene.activeCamera) {
  79117. this._scene.activeCamera.position = value;
  79118. }
  79119. },
  79120. enumerable: true,
  79121. configurable: true
  79122. });
  79123. /**
  79124. * Enables controllers and user interactions suck as selecting and object or clicking on an object.
  79125. */
  79126. VRExperienceHelper.prototype.enableInteractions = function () {
  79127. var _this = this;
  79128. if (!this._interactionsEnabled) {
  79129. this._interactionsRequested = true;
  79130. if (this._leftControllerReady && this._webVRCamera.leftController) {
  79131. this._enableInteractionOnController(this._webVRCamera.leftController);
  79132. }
  79133. if (this._rightControllerReady && this._webVRCamera.rightController) {
  79134. this._enableInteractionOnController(this._webVRCamera.rightController);
  79135. }
  79136. if (!this._gazeTracker) {
  79137. this._createGazeTracker();
  79138. }
  79139. this.raySelectionPredicate = function (mesh) {
  79140. return mesh.isVisible;
  79141. };
  79142. this.meshSelectionPredicate = function (mesh) {
  79143. return true;
  79144. };
  79145. this._raySelectionPredicate = function (mesh) {
  79146. if (_this._isTeleportationFloor(mesh) || (mesh != _this._gazeTracker
  79147. && mesh.name.indexOf("teleportationTarget") === -1
  79148. && mesh.name.indexOf("torusTeleportation") === -1
  79149. && mesh.name.indexOf("laserPointer") === -1)) {
  79150. return _this.raySelectionPredicate(mesh);
  79151. }
  79152. return false;
  79153. };
  79154. this._interactionsEnabled = true;
  79155. }
  79156. };
  79157. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  79158. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  79159. if (this._floorMeshesCollection[i].id === mesh.id) {
  79160. return true;
  79161. }
  79162. }
  79163. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  79164. return true;
  79165. }
  79166. return false;
  79167. };
  79168. /**
  79169. * Adds a floor mesh to be used for teleportation.
  79170. * @param floorMesh the mesh to be used for teleportation.
  79171. */
  79172. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  79173. if (!this._floorMeshesCollection) {
  79174. return;
  79175. }
  79176. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  79177. return;
  79178. }
  79179. this._floorMeshesCollection.push(floorMesh);
  79180. };
  79181. /**
  79182. * Removes a floor mesh from being used for teleportation.
  79183. * @param floorMesh the mesh to be removed.
  79184. */
  79185. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  79186. if (!this._floorMeshesCollection) {
  79187. return;
  79188. }
  79189. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  79190. if (meshIndex !== -1) {
  79191. this._floorMeshesCollection.splice(meshIndex, 1);
  79192. }
  79193. };
  79194. /**
  79195. * Enables interactions and teleportation using the VR controllers and gaze.
  79196. * @param vrTeleportationOptions options to modify teleportation behavior.
  79197. */
  79198. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  79199. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  79200. if (!this._teleportationInitialized) {
  79201. this._teleportationRequested = true;
  79202. this.enableInteractions();
  79203. if (vrTeleportationOptions.floorMeshName) {
  79204. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  79205. }
  79206. if (vrTeleportationOptions.floorMeshes) {
  79207. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  79208. }
  79209. if (this._leftControllerReady && this._webVRCamera.leftController) {
  79210. this._enableTeleportationOnController(this._webVRCamera.leftController);
  79211. }
  79212. if (this._rightControllerReady && this._webVRCamera.rightController) {
  79213. this._enableTeleportationOnController(this._webVRCamera.rightController);
  79214. }
  79215. // Creates an image processing post process for the vignette not relying
  79216. // on the main scene configuration for image processing to reduce setup and spaces
  79217. // (gamma/linear) conflicts.
  79218. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  79219. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  79220. imageProcessingConfiguration.vignetteEnabled = true;
  79221. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  79222. this._webVRCamera.detachPostProcess(this._postProcessMove);
  79223. this._passProcessMove = new BABYLON.PassPostProcess("pass", 1.0, this._webVRCamera);
  79224. this._teleportationInitialized = true;
  79225. if (this._isDefaultTeleportationTarget) {
  79226. this._createTeleportationCircles();
  79227. }
  79228. }
  79229. };
  79230. VRExperienceHelper.prototype._enableInteractionOnController = function (webVRController) {
  79231. var _this = this;
  79232. var controllerMesh = webVRController.mesh;
  79233. if (controllerMesh) {
  79234. var makeNotPick = function (root) {
  79235. root.name += " laserPointer";
  79236. root.getChildMeshes().forEach(function (c) {
  79237. makeNotPick(c);
  79238. });
  79239. };
  79240. makeNotPick(controllerMesh);
  79241. var childMeshes = controllerMesh.getChildMeshes();
  79242. for (var i = 0; i < childMeshes.length; i++) {
  79243. if (childMeshes[i].name && childMeshes[i].name.indexOf("POINTING_POSE") >= 0) {
  79244. controllerMesh = childMeshes[i];
  79245. break;
  79246. }
  79247. }
  79248. var laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, this._scene, false);
  79249. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", this._scene);
  79250. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  79251. laserPointerMaterial.alpha = 0.6;
  79252. laserPointer.material = laserPointerMaterial;
  79253. laserPointer.rotation.x = Math.PI / 2;
  79254. laserPointer.parent = controllerMesh;
  79255. laserPointer.position.z = -0.5;
  79256. laserPointer.isVisible = false;
  79257. if (webVRController.hand === "left") {
  79258. this._leftLaserPointer = laserPointer;
  79259. this._interactionsEnabledOnLeftController = true;
  79260. if (!this._rightLaserPointer) {
  79261. this._leftLaserPointer.isVisible = true;
  79262. }
  79263. }
  79264. else {
  79265. this._rightLaserPointer = laserPointer;
  79266. this._interactionsEnabledOnRightController = true;
  79267. if (!this._leftLaserPointer) {
  79268. this._rightLaserPointer.isVisible = true;
  79269. }
  79270. }
  79271. webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  79272. // Enabling / disabling laserPointer
  79273. if (_this._displayLaserPointer && stateObject.value === 1) {
  79274. laserPointer.isVisible = !laserPointer.isVisible;
  79275. // Laser pointer can only be active on left or right, not both at the same time
  79276. if (webVRController.hand === "left" && _this._rightLaserPointer) {
  79277. _this._rightLaserPointer.isVisible = false;
  79278. }
  79279. else if (_this._leftLaserPointer) {
  79280. _this._leftLaserPointer.isVisible = false;
  79281. }
  79282. }
  79283. });
  79284. webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  79285. if (!_this._pointerDownOnMeshAsked) {
  79286. if (stateObject.value > _this._padSensibilityUp) {
  79287. _this._selectionPointerDown();
  79288. }
  79289. }
  79290. else if (stateObject.value < _this._padSensibilityDown) {
  79291. _this._selectionPointerUp();
  79292. }
  79293. });
  79294. }
  79295. };
  79296. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, webVRController) {
  79297. if (webVRController === void 0) { webVRController = null; }
  79298. if (!this._teleportationRequestInitiated) {
  79299. if (stateObject.y < -this._padSensibilityUp && this._dpadPressed) {
  79300. if (webVRController) {
  79301. // If laser pointer wasn't enabled yet
  79302. if (this._displayLaserPointer && webVRController.hand === "left" && this._leftLaserPointer) {
  79303. this._leftLaserPointer.isVisible = true;
  79304. if (this._rightLaserPointer) {
  79305. this._rightLaserPointer.isVisible = false;
  79306. }
  79307. }
  79308. else if (this._displayLaserPointer && this._rightLaserPointer) {
  79309. this._rightLaserPointer.isVisible = true;
  79310. if (this._leftLaserPointer) {
  79311. this._leftLaserPointer.isVisible = false;
  79312. }
  79313. }
  79314. }
  79315. this._teleportationRequestInitiated = true;
  79316. }
  79317. }
  79318. else {
  79319. // Listening to the proper controller values changes to confirm teleportation
  79320. if (webVRController == null
  79321. || (webVRController.hand === "left" && this._leftLaserPointer && this._leftLaserPointer.isVisible)
  79322. || (webVRController.hand === "right" && this._rightLaserPointer && this._rightLaserPointer.isVisible)) {
  79323. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  79324. if (this._teleportationAllowed) {
  79325. this._teleportationAllowed = false;
  79326. this._teleportCamera();
  79327. }
  79328. this._teleportationRequestInitiated = false;
  79329. }
  79330. }
  79331. }
  79332. };
  79333. VRExperienceHelper.prototype._selectionPointerDown = function () {
  79334. this._pointerDownOnMeshAsked = true;
  79335. if (this._currentMeshSelected && this._currentHit) {
  79336. this._scene.simulatePointerDown(this._currentHit);
  79337. }
  79338. };
  79339. VRExperienceHelper.prototype._selectionPointerUp = function () {
  79340. if (this._currentMeshSelected && this._currentHit) {
  79341. this._scene.simulatePointerUp(this._currentHit);
  79342. }
  79343. this._pointerDownOnMeshAsked = false;
  79344. };
  79345. VRExperienceHelper.prototype._checkRotate = function (stateObject) {
  79346. // Only rotate when user is not currently selecting a teleportation location
  79347. if (this._teleportationRequestInitiated) {
  79348. return;
  79349. }
  79350. if (!this._rotationLeftAsked) {
  79351. if (stateObject.x < -this._padSensibilityUp && this._dpadPressed) {
  79352. this._rotationLeftAsked = true;
  79353. if (this._rotationAllowed) {
  79354. this._rotateCamera(false);
  79355. }
  79356. }
  79357. }
  79358. else {
  79359. if (stateObject.x > -this._padSensibilityDown) {
  79360. this._rotationLeftAsked = false;
  79361. }
  79362. }
  79363. if (!this._rotationRightAsked) {
  79364. if (stateObject.x > this._padSensibilityUp && this._dpadPressed) {
  79365. this._rotationRightAsked = true;
  79366. if (this._rotationAllowed) {
  79367. this._rotateCamera(true);
  79368. }
  79369. }
  79370. }
  79371. else {
  79372. if (stateObject.x < this._padSensibilityDown) {
  79373. this._rotationRightAsked = false;
  79374. }
  79375. }
  79376. };
  79377. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject) {
  79378. // Only teleport backwards when user is not currently selecting a teleportation location
  79379. if (this._teleportationRequestInitiated) {
  79380. return;
  79381. }
  79382. // Teleport backwards
  79383. if (stateObject.y > this._padSensibilityUp && this._dpadPressed) {
  79384. if (!this._teleportationBackRequestInitiated) {
  79385. if (!this.currentVRCamera) {
  79386. return;
  79387. }
  79388. // Get rotation and position of the current camera
  79389. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  79390. var position = this.currentVRCamera.position;
  79391. // If the camera has device position, use that instead
  79392. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  79393. rotation = this.currentVRCamera.deviceRotationQuaternion;
  79394. position = this.currentVRCamera.devicePosition;
  79395. }
  79396. // Get matrix with only the y rotation of the device rotation
  79397. rotation.toEulerAnglesToRef(this._workingVector);
  79398. this._workingVector.z = 0;
  79399. this._workingVector.x = 0;
  79400. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  79401. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  79402. // Rotate backwards ray by device rotation to cast at the ground behind the user
  79403. BABYLON.Vector3.TransformCoordinatesToRef(this.teleportBackwardsVector, this._workingMatrix, this._workingVector);
  79404. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  79405. var ray = new BABYLON.Ray(position, this._workingVector);
  79406. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  79407. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  79408. this._teleportCamera(hit.pickedPoint);
  79409. }
  79410. this._teleportationBackRequestInitiated = true;
  79411. }
  79412. }
  79413. else {
  79414. this._teleportationBackRequestInitiated = false;
  79415. }
  79416. };
  79417. VRExperienceHelper.prototype._enableTeleportationOnController = function (webVRController) {
  79418. var _this = this;
  79419. var controllerMesh = webVRController.mesh;
  79420. if (controllerMesh) {
  79421. if (webVRController.hand === "left") {
  79422. if (!this._interactionsEnabledOnLeftController) {
  79423. this._enableInteractionOnController(webVRController);
  79424. }
  79425. this._teleportationEnabledOnLeftController = true;
  79426. }
  79427. else {
  79428. if (!this._interactionsEnabledOnRightController) {
  79429. this._enableInteractionOnController(webVRController);
  79430. }
  79431. this._teleportationEnabledOnRightController = true;
  79432. }
  79433. if (webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  79434. this._dpadPressed = false;
  79435. webVRController.onPadStateChangedObservable.add(function (stateObject) {
  79436. _this._dpadPressed = stateObject.pressed;
  79437. if (!_this._dpadPressed) {
  79438. _this._rotationLeftAsked = false;
  79439. _this._rotationRightAsked = false;
  79440. _this._teleportationBackRequestInitiated = false;
  79441. }
  79442. });
  79443. }
  79444. webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  79445. if (_this.teleportationEnabled) {
  79446. _this._checkTeleportBackwards(stateObject);
  79447. _this._checkTeleportWithRay(stateObject, webVRController);
  79448. }
  79449. _this._checkRotate(stateObject);
  79450. });
  79451. }
  79452. };
  79453. // Gaze support used to point to teleport or to interact with an object
  79454. VRExperienceHelper.prototype._createGazeTracker = function () {
  79455. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, this._scene, false);
  79456. this._gazeTracker.bakeCurrentTransformIntoVertices();
  79457. this._gazeTracker.isPickable = false;
  79458. this._gazeTracker.isVisible = false;
  79459. var targetMat = new BABYLON.StandardMaterial("targetMat", this._scene);
  79460. targetMat.specularColor = BABYLON.Color3.Black();
  79461. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  79462. targetMat.backFaceCulling = false;
  79463. this._gazeTracker.material = targetMat;
  79464. };
  79465. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  79466. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  79467. this._teleportationTarget.isPickable = false;
  79468. var length = 512;
  79469. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  79470. dynamicTexture.hasAlpha = true;
  79471. var context = dynamicTexture.getContext();
  79472. var centerX = length / 2;
  79473. var centerY = length / 2;
  79474. var radius = 200;
  79475. context.beginPath();
  79476. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  79477. context.fillStyle = this._teleportationFillColor;
  79478. context.fill();
  79479. context.lineWidth = 10;
  79480. context.strokeStyle = this._teleportationBorderColor;
  79481. context.stroke();
  79482. context.closePath();
  79483. dynamicTexture.update();
  79484. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  79485. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  79486. this._teleportationTarget.material = teleportationCircleMaterial;
  79487. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  79488. torus.isPickable = false;
  79489. torus.parent = this._teleportationTarget;
  79490. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  79491. var keys = [];
  79492. keys.push({
  79493. frame: 0,
  79494. value: 0
  79495. });
  79496. keys.push({
  79497. frame: 30,
  79498. value: 0.4
  79499. });
  79500. keys.push({
  79501. frame: 60,
  79502. value: 0
  79503. });
  79504. animationInnerCircle.setKeys(keys);
  79505. var easingFunction = new BABYLON.SineEase();
  79506. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  79507. animationInnerCircle.setEasingFunction(easingFunction);
  79508. torus.animations = [];
  79509. torus.animations.push(animationInnerCircle);
  79510. this._scene.beginAnimation(torus, 0, 60, true);
  79511. this._hideTeleportationTarget();
  79512. };
  79513. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  79514. if (this._teleportationInitialized) {
  79515. this._teleportationTarget.isVisible = true;
  79516. if (this._isDefaultTeleportationTarget) {
  79517. this._teleportationTarget.getChildren()[0].isVisible = true;
  79518. }
  79519. }
  79520. };
  79521. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  79522. if (this._teleportationInitialized) {
  79523. this._teleportationTarget.isVisible = false;
  79524. if (this._isDefaultTeleportationTarget) {
  79525. this._teleportationTarget.getChildren()[0].isVisible = false;
  79526. }
  79527. }
  79528. };
  79529. VRExperienceHelper.prototype._rotateCamera = function (right) {
  79530. var _this = this;
  79531. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  79532. return;
  79533. }
  79534. if (right) {
  79535. this._rotationAngle++;
  79536. }
  79537. else {
  79538. this._rotationAngle--;
  79539. }
  79540. this.currentVRCamera.animations = [];
  79541. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  79542. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  79543. var animationRotationKeys = [];
  79544. animationRotationKeys.push({
  79545. frame: 0,
  79546. value: this.currentVRCamera.rotationQuaternion
  79547. });
  79548. animationRotationKeys.push({
  79549. frame: 6,
  79550. value: target
  79551. });
  79552. animationRotation.setKeys(animationRotationKeys);
  79553. animationRotation.setEasingFunction(this._circleEase);
  79554. this.currentVRCamera.animations.push(animationRotation);
  79555. this._postProcessMove.animations = [];
  79556. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  79557. var vignetteWeightKeys = [];
  79558. vignetteWeightKeys.push({
  79559. frame: 0,
  79560. value: 0
  79561. });
  79562. vignetteWeightKeys.push({
  79563. frame: 3,
  79564. value: 4
  79565. });
  79566. vignetteWeightKeys.push({
  79567. frame: 6,
  79568. value: 0
  79569. });
  79570. animationPP.setKeys(vignetteWeightKeys);
  79571. animationPP.setEasingFunction(this._circleEase);
  79572. this._postProcessMove.animations.push(animationPP);
  79573. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  79574. var vignetteStretchKeys = [];
  79575. vignetteStretchKeys.push({
  79576. frame: 0,
  79577. value: 0
  79578. });
  79579. vignetteStretchKeys.push({
  79580. frame: 3,
  79581. value: 10
  79582. });
  79583. vignetteStretchKeys.push({
  79584. frame: 6,
  79585. value: 0
  79586. });
  79587. animationPP2.setKeys(vignetteStretchKeys);
  79588. animationPP2.setEasingFunction(this._circleEase);
  79589. this._postProcessMove.animations.push(animationPP2);
  79590. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  79591. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  79592. this._webVRCamera.attachPostProcess(this._postProcessMove);
  79593. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  79594. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  79595. });
  79596. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  79597. };
  79598. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit) {
  79599. if (hit.pickedPoint) {
  79600. this._teleportationAllowed = true;
  79601. if (this._teleportationRequestInitiated) {
  79602. this._displayTeleportationTarget();
  79603. }
  79604. else {
  79605. this._hideTeleportationTarget();
  79606. }
  79607. this._haloCenter.copyFrom(hit.pickedPoint);
  79608. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  79609. var pickNormal = hit.getNormal(true, false);
  79610. if (pickNormal) {
  79611. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  79612. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  79613. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  79614. }
  79615. this._teleportationTarget.position.y += 0.1;
  79616. }
  79617. };
  79618. VRExperienceHelper.prototype._teleportCamera = function (location) {
  79619. var _this = this;
  79620. if (location === void 0) { location = null; }
  79621. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  79622. return;
  79623. }
  79624. if (!location) {
  79625. location = this._haloCenter;
  79626. }
  79627. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  79628. // offset of the headset from the anchor.
  79629. if (this.webVRCamera.leftCamera) {
  79630. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  79631. this._workingVector.subtractInPlace(this.webVRCamera.position);
  79632. location.subtractToRef(this._workingVector, this._workingVector);
  79633. }
  79634. else {
  79635. this._workingVector.copyFrom(location);
  79636. }
  79637. // Add height to account for user's height offset
  79638. if (this.isInVRMode) {
  79639. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround();
  79640. }
  79641. else {
  79642. this._workingVector.y += this._defaultHeight;
  79643. }
  79644. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  79645. // Create animation from the camera's position to the new location
  79646. this.currentVRCamera.animations = [];
  79647. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  79648. var animationCameraTeleportationKeys = [{
  79649. frame: 0,
  79650. value: this.currentVRCamera.position
  79651. },
  79652. {
  79653. frame: 11,
  79654. value: this._workingVector
  79655. }
  79656. ];
  79657. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  79658. animationCameraTeleportation.setEasingFunction(this._circleEase);
  79659. this.currentVRCamera.animations.push(animationCameraTeleportation);
  79660. this._postProcessMove.animations = [];
  79661. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  79662. var vignetteWeightKeys = [];
  79663. vignetteWeightKeys.push({
  79664. frame: 0,
  79665. value: 0
  79666. });
  79667. vignetteWeightKeys.push({
  79668. frame: 5,
  79669. value: 8
  79670. });
  79671. vignetteWeightKeys.push({
  79672. frame: 11,
  79673. value: 0
  79674. });
  79675. animationPP.setKeys(vignetteWeightKeys);
  79676. this._postProcessMove.animations.push(animationPP);
  79677. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  79678. var vignetteStretchKeys = [];
  79679. vignetteStretchKeys.push({
  79680. frame: 0,
  79681. value: 0
  79682. });
  79683. vignetteStretchKeys.push({
  79684. frame: 5,
  79685. value: 10
  79686. });
  79687. vignetteStretchKeys.push({
  79688. frame: 11,
  79689. value: 0
  79690. });
  79691. animationPP2.setKeys(vignetteStretchKeys);
  79692. this._postProcessMove.animations.push(animationPP2);
  79693. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  79694. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  79695. this._webVRCamera.attachPostProcess(this._postProcessMove);
  79696. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  79697. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  79698. });
  79699. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  79700. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  79701. });
  79702. };
  79703. VRExperienceHelper.prototype._castRayAndSelectObject = function () {
  79704. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  79705. return;
  79706. }
  79707. var ray;
  79708. if (this._leftLaserPointer && this._leftLaserPointer.isVisible && this.currentVRCamera.leftController) {
  79709. ray = this.currentVRCamera.leftController.getForwardRay(this._rayLength);
  79710. }
  79711. else if (this._rightLaserPointer && this._rightLaserPointer.isVisible && this.currentVRCamera.rightController) {
  79712. ray = this.currentVRCamera.rightController.getForwardRay(this._rayLength);
  79713. }
  79714. else {
  79715. ray = this.currentVRCamera.getForwardRay(this._rayLength);
  79716. }
  79717. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  79718. // Moving the gazeTracker on the mesh face targetted
  79719. if (hit && hit.pickedPoint) {
  79720. if (this._displayGaze) {
  79721. var multiplier = 1;
  79722. this._gazeTracker.isVisible = true;
  79723. if (this._isActionableMesh) {
  79724. multiplier = 3;
  79725. }
  79726. this._gazeTracker.scaling.x = hit.distance * multiplier;
  79727. this._gazeTracker.scaling.y = hit.distance * multiplier;
  79728. this._gazeTracker.scaling.z = hit.distance * multiplier;
  79729. var pickNormal = hit.getNormal();
  79730. // To avoid z-fighting
  79731. var deltaFighting = 0.002;
  79732. if (pickNormal) {
  79733. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  79734. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  79735. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._gazeTracker.rotation);
  79736. }
  79737. this._gazeTracker.position.copyFrom(hit.pickedPoint);
  79738. if (this._gazeTracker.position.x < 0) {
  79739. this._gazeTracker.position.x += deltaFighting;
  79740. }
  79741. else {
  79742. this._gazeTracker.position.x -= deltaFighting;
  79743. }
  79744. if (this._gazeTracker.position.y < 0) {
  79745. this._gazeTracker.position.y += deltaFighting;
  79746. }
  79747. else {
  79748. this._gazeTracker.position.y -= deltaFighting;
  79749. }
  79750. if (this._gazeTracker.position.z < 0) {
  79751. this._gazeTracker.position.z += deltaFighting;
  79752. }
  79753. else {
  79754. this._gazeTracker.position.z -= deltaFighting;
  79755. }
  79756. }
  79757. // Changing the size of the laser pointer based on the distance from the targetted point
  79758. if (this._rightLaserPointer && this._rightLaserPointer.isVisible) {
  79759. this._rightLaserPointer.scaling.y = hit.distance;
  79760. this._rightLaserPointer.position.z = -hit.distance / 2;
  79761. }
  79762. if (this._leftLaserPointer && this._leftLaserPointer.isVisible) {
  79763. this._leftLaserPointer.scaling.y = hit.distance;
  79764. this._leftLaserPointer.position.z = -hit.distance / 2;
  79765. }
  79766. }
  79767. else {
  79768. this._gazeTracker.isVisible = false;
  79769. }
  79770. if (hit && hit.pickedMesh) {
  79771. this._currentHit = hit;
  79772. if (this._pointerDownOnMeshAsked) {
  79773. this._scene.simulatePointerMove(this._currentHit);
  79774. }
  79775. // The object selected is the floor, we're in a teleportation scenario
  79776. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  79777. // Moving the teleportation area to this targetted point
  79778. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  79779. if (this._currentMeshSelected && !this._isTeleportationFloor(this._currentMeshSelected)) {
  79780. this._notifySelectedMeshUnselected();
  79781. }
  79782. this._currentMeshSelected = null;
  79783. this._moveTeleportationSelectorTo(hit);
  79784. return;
  79785. }
  79786. // If not, we're in a selection scenario
  79787. this._hideTeleportationTarget();
  79788. this._teleportationAllowed = false;
  79789. if (hit.pickedMesh !== this._currentMeshSelected) {
  79790. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  79791. this.onNewMeshPicked.notifyObservers(hit);
  79792. this._currentMeshSelected = hit.pickedMesh;
  79793. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  79794. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  79795. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  79796. this._isActionableMesh = true;
  79797. }
  79798. else {
  79799. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  79800. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  79801. this._isActionableMesh = false;
  79802. }
  79803. try {
  79804. this.onNewMeshSelected.notifyObservers(this._currentMeshSelected);
  79805. }
  79806. catch (err) {
  79807. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  79808. }
  79809. }
  79810. else {
  79811. this._notifySelectedMeshUnselected();
  79812. this._currentMeshSelected = null;
  79813. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  79814. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  79815. }
  79816. }
  79817. }
  79818. else {
  79819. this._currentHit = null;
  79820. this._notifySelectedMeshUnselected();
  79821. this._currentMeshSelected = null;
  79822. this._teleportationAllowed = false;
  79823. this._hideTeleportationTarget();
  79824. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  79825. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  79826. }
  79827. };
  79828. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function () {
  79829. if (this._currentMeshSelected) {
  79830. this.onSelectedMeshUnselected.notifyObservers(this._currentMeshSelected);
  79831. }
  79832. };
  79833. /**
  79834. * Sets the color of the laser ray from the vr controllers.
  79835. * @param color new color for the ray.
  79836. */
  79837. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  79838. if (this._leftLaserPointer && this._leftLaserPointer.material) {
  79839. this._leftLaserPointer.material.emissiveColor = color;
  79840. }
  79841. if (this._rightLaserPointer && this._rightLaserPointer.material) {
  79842. this._rightLaserPointer.material.emissiveColor = color;
  79843. }
  79844. };
  79845. /**
  79846. * Sets the color of the ray from the vr headsets gaze.
  79847. * @param color new color for the ray.
  79848. */
  79849. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  79850. if (this._gazeTracker.material) {
  79851. this._gazeTracker.material.emissiveColor = color;
  79852. }
  79853. };
  79854. /**
  79855. * Exits VR and disposes of the vr experience helper
  79856. */
  79857. VRExperienceHelper.prototype.dispose = function () {
  79858. if (this.isInVRMode) {
  79859. this.exitVR();
  79860. }
  79861. if (this._passProcessMove) {
  79862. this._passProcessMove.dispose();
  79863. }
  79864. if (this._postProcessMove) {
  79865. this._postProcessMove.dispose();
  79866. }
  79867. if (this._webVRCamera) {
  79868. this._webVRCamera.dispose();
  79869. }
  79870. if (this._vrDeviceOrientationCamera) {
  79871. this._vrDeviceOrientationCamera.dispose();
  79872. }
  79873. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  79874. document.body.removeChild(this._btnVR);
  79875. }
  79876. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  79877. this._deviceOrientationCamera.dispose();
  79878. }
  79879. if (this._gazeTracker) {
  79880. this._gazeTracker.dispose();
  79881. }
  79882. if (this._teleportationTarget) {
  79883. this._teleportationTarget.dispose();
  79884. }
  79885. this._floorMeshesCollection = [];
  79886. document.removeEventListener("keydown", this._onKeyDown);
  79887. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  79888. window.removeEventListener("resize", this._onResize);
  79889. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  79890. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  79891. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  79892. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  79893. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  79894. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  79895. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  79896. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  79897. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  79898. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  79899. this._scene.unregisterBeforeRender(this.beforeRender);
  79900. };
  79901. /**
  79902. * Gets the name of the VRExperienceHelper class
  79903. * @returns "VRExperienceHelper"
  79904. */
  79905. VRExperienceHelper.prototype.getClassName = function () {
  79906. return "VRExperienceHelper";
  79907. };
  79908. return VRExperienceHelper;
  79909. }());
  79910. BABYLON.VRExperienceHelper = VRExperienceHelper;
  79911. })(BABYLON || (BABYLON = {}));
  79912. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  79913. // Mainly based on these 2 articles :
  79914. // 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
  79915. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  79916. var BABYLON;
  79917. (function (BABYLON) {
  79918. var JoystickAxis;
  79919. (function (JoystickAxis) {
  79920. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  79921. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  79922. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  79923. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  79924. var VirtualJoystick = /** @class */ (function () {
  79925. function VirtualJoystick(leftJoystick) {
  79926. var _this = this;
  79927. if (leftJoystick) {
  79928. this._leftJoystick = true;
  79929. }
  79930. else {
  79931. this._leftJoystick = false;
  79932. }
  79933. VirtualJoystick._globalJoystickIndex++;
  79934. // By default left & right arrow keys are moving the X
  79935. // and up & down keys are moving the Y
  79936. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  79937. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  79938. this.reverseLeftRight = false;
  79939. this.reverseUpDown = false;
  79940. // collections of pointers
  79941. this._touches = new BABYLON.StringDictionary();
  79942. this.deltaPosition = BABYLON.Vector3.Zero();
  79943. this._joystickSensibility = 25;
  79944. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  79945. this._onResize = function (evt) {
  79946. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  79947. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  79948. if (VirtualJoystick.vjCanvas) {
  79949. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  79950. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  79951. }
  79952. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  79953. };
  79954. // injecting a canvas element on top of the canvas 3D game
  79955. if (!VirtualJoystick.vjCanvas) {
  79956. window.addEventListener("resize", this._onResize, false);
  79957. VirtualJoystick.vjCanvas = document.createElement("canvas");
  79958. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  79959. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  79960. VirtualJoystick.vjCanvas.width = window.innerWidth;
  79961. VirtualJoystick.vjCanvas.height = window.innerHeight;
  79962. VirtualJoystick.vjCanvas.style.width = "100%";
  79963. VirtualJoystick.vjCanvas.style.height = "100%";
  79964. VirtualJoystick.vjCanvas.style.position = "absolute";
  79965. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  79966. VirtualJoystick.vjCanvas.style.top = "0px";
  79967. VirtualJoystick.vjCanvas.style.left = "0px";
  79968. VirtualJoystick.vjCanvas.style.zIndex = "5";
  79969. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  79970. // Support for jQuery PEP polyfill
  79971. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  79972. var context = VirtualJoystick.vjCanvas.getContext('2d');
  79973. if (!context) {
  79974. throw new Error("Unable to create canvas for virtual joystick");
  79975. }
  79976. VirtualJoystick.vjCanvasContext = context;
  79977. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  79978. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  79979. document.body.appendChild(VirtualJoystick.vjCanvas);
  79980. }
  79981. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  79982. this.pressed = false;
  79983. // default joystick color
  79984. this._joystickColor = "cyan";
  79985. this._joystickPointerID = -1;
  79986. // current joystick position
  79987. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  79988. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  79989. // origin joystick position
  79990. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  79991. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  79992. this._onPointerDownHandlerRef = function (evt) {
  79993. _this._onPointerDown(evt);
  79994. };
  79995. this._onPointerMoveHandlerRef = function (evt) {
  79996. _this._onPointerMove(evt);
  79997. };
  79998. this._onPointerUpHandlerRef = function (evt) {
  79999. _this._onPointerUp(evt);
  80000. };
  80001. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  80002. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  80003. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  80004. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  80005. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  80006. evt.preventDefault(); // Disables system menu
  80007. }, false);
  80008. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  80009. }
  80010. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  80011. this._joystickSensibility = newJoystickSensibility;
  80012. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  80013. };
  80014. VirtualJoystick.prototype._onPointerDown = function (e) {
  80015. var positionOnScreenCondition;
  80016. e.preventDefault();
  80017. if (this._leftJoystick === true) {
  80018. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  80019. }
  80020. else {
  80021. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  80022. }
  80023. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  80024. // First contact will be dedicated to the virtual joystick
  80025. this._joystickPointerID = e.pointerId;
  80026. this._joystickPointerStartPos.x = e.clientX;
  80027. this._joystickPointerStartPos.y = e.clientY;
  80028. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  80029. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  80030. this._deltaJoystickVector.x = 0;
  80031. this._deltaJoystickVector.y = 0;
  80032. this.pressed = true;
  80033. this._touches.add(e.pointerId.toString(), e);
  80034. }
  80035. else {
  80036. // You can only trigger the action buttons with a joystick declared
  80037. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  80038. this._action();
  80039. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  80040. }
  80041. }
  80042. };
  80043. VirtualJoystick.prototype._onPointerMove = function (e) {
  80044. // If the current pointer is the one associated to the joystick (first touch contact)
  80045. if (this._joystickPointerID == e.pointerId) {
  80046. this._joystickPointerPos.x = e.clientX;
  80047. this._joystickPointerPos.y = e.clientY;
  80048. this._deltaJoystickVector = this._joystickPointerPos.clone();
  80049. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  80050. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  80051. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  80052. switch (this._axisTargetedByLeftAndRight) {
  80053. case JoystickAxis.X:
  80054. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  80055. break;
  80056. case JoystickAxis.Y:
  80057. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  80058. break;
  80059. case JoystickAxis.Z:
  80060. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  80061. break;
  80062. }
  80063. var directionUpDown = this.reverseUpDown ? 1 : -1;
  80064. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  80065. switch (this._axisTargetedByUpAndDown) {
  80066. case JoystickAxis.X:
  80067. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  80068. break;
  80069. case JoystickAxis.Y:
  80070. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  80071. break;
  80072. case JoystickAxis.Z:
  80073. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  80074. break;
  80075. }
  80076. }
  80077. else {
  80078. var data = this._touches.get(e.pointerId.toString());
  80079. if (data) {
  80080. data.x = e.clientX;
  80081. data.y = e.clientY;
  80082. }
  80083. }
  80084. };
  80085. VirtualJoystick.prototype._onPointerUp = function (e) {
  80086. if (this._joystickPointerID == e.pointerId) {
  80087. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  80088. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  80089. this._joystickPointerID = -1;
  80090. this.pressed = false;
  80091. }
  80092. else {
  80093. var touch = this._touches.get(e.pointerId.toString());
  80094. if (touch) {
  80095. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  80096. }
  80097. }
  80098. this._deltaJoystickVector.x = 0;
  80099. this._deltaJoystickVector.y = 0;
  80100. this._touches.remove(e.pointerId.toString());
  80101. };
  80102. /**
  80103. * Change the color of the virtual joystick
  80104. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  80105. */
  80106. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  80107. this._joystickColor = newColor;
  80108. };
  80109. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  80110. this._action = action;
  80111. };
  80112. // Define which axis you'd like to control for left & right
  80113. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  80114. switch (axis) {
  80115. case JoystickAxis.X:
  80116. case JoystickAxis.Y:
  80117. case JoystickAxis.Z:
  80118. this._axisTargetedByLeftAndRight = axis;
  80119. break;
  80120. default:
  80121. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  80122. break;
  80123. }
  80124. };
  80125. // Define which axis you'd like to control for up & down
  80126. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  80127. switch (axis) {
  80128. case JoystickAxis.X:
  80129. case JoystickAxis.Y:
  80130. case JoystickAxis.Z:
  80131. this._axisTargetedByUpAndDown = axis;
  80132. break;
  80133. default:
  80134. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  80135. break;
  80136. }
  80137. };
  80138. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  80139. var _this = this;
  80140. if (this.pressed) {
  80141. this._touches.forEach(function (key, touch) {
  80142. if (touch.pointerId === _this._joystickPointerID) {
  80143. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  80144. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  80145. VirtualJoystick.vjCanvasContext.beginPath();
  80146. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  80147. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  80148. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  80149. VirtualJoystick.vjCanvasContext.stroke();
  80150. VirtualJoystick.vjCanvasContext.closePath();
  80151. VirtualJoystick.vjCanvasContext.beginPath();
  80152. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  80153. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  80154. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  80155. VirtualJoystick.vjCanvasContext.stroke();
  80156. VirtualJoystick.vjCanvasContext.closePath();
  80157. VirtualJoystick.vjCanvasContext.beginPath();
  80158. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  80159. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  80160. VirtualJoystick.vjCanvasContext.stroke();
  80161. VirtualJoystick.vjCanvasContext.closePath();
  80162. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  80163. }
  80164. else {
  80165. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  80166. VirtualJoystick.vjCanvasContext.beginPath();
  80167. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  80168. VirtualJoystick.vjCanvasContext.beginPath();
  80169. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  80170. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  80171. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  80172. VirtualJoystick.vjCanvasContext.stroke();
  80173. VirtualJoystick.vjCanvasContext.closePath();
  80174. touch.prevX = touch.x;
  80175. touch.prevY = touch.y;
  80176. }
  80177. ;
  80178. });
  80179. }
  80180. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  80181. };
  80182. VirtualJoystick.prototype.releaseCanvas = function () {
  80183. if (VirtualJoystick.vjCanvas) {
  80184. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  80185. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  80186. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  80187. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  80188. window.removeEventListener("resize", this._onResize);
  80189. document.body.removeChild(VirtualJoystick.vjCanvas);
  80190. VirtualJoystick.vjCanvas = null;
  80191. }
  80192. };
  80193. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  80194. VirtualJoystick._globalJoystickIndex = 0;
  80195. return VirtualJoystick;
  80196. }());
  80197. BABYLON.VirtualJoystick = VirtualJoystick;
  80198. })(BABYLON || (BABYLON = {}));
  80199. //# sourceMappingURL=babylon.virtualJoystick.js.map
  80200. var BABYLON;
  80201. (function (BABYLON) {
  80202. // We're mainly based on the logic defined into the FreeCamera code
  80203. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  80204. __extends(VirtualJoysticksCamera, _super);
  80205. function VirtualJoysticksCamera(name, position, scene) {
  80206. var _this = _super.call(this, name, position, scene) || this;
  80207. _this.inputs.addVirtualJoystick();
  80208. return _this;
  80209. }
  80210. VirtualJoysticksCamera.prototype.getClassName = function () {
  80211. return "VirtualJoysticksCamera";
  80212. };
  80213. return VirtualJoysticksCamera;
  80214. }(BABYLON.FreeCamera));
  80215. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  80216. })(BABYLON || (BABYLON = {}));
  80217. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  80218. var BABYLON;
  80219. (function (BABYLON) {
  80220. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  80221. function FreeCameraVirtualJoystickInput() {
  80222. }
  80223. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  80224. return this._leftjoystick;
  80225. };
  80226. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  80227. return this._rightjoystick;
  80228. };
  80229. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  80230. if (this._leftjoystick) {
  80231. var camera = this.camera;
  80232. var speed = camera._computeLocalCameraSpeed() * 50;
  80233. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  80234. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  80235. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  80236. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  80237. if (!this._leftjoystick.pressed) {
  80238. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  80239. }
  80240. if (!this._rightjoystick.pressed) {
  80241. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  80242. }
  80243. }
  80244. };
  80245. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  80246. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  80247. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  80248. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  80249. this._leftjoystick.setJoystickSensibility(0.15);
  80250. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  80251. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  80252. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  80253. this._rightjoystick.reverseUpDown = true;
  80254. this._rightjoystick.setJoystickSensibility(0.05);
  80255. this._rightjoystick.setJoystickColor("yellow");
  80256. };
  80257. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  80258. this._leftjoystick.releaseCanvas();
  80259. this._rightjoystick.releaseCanvas();
  80260. };
  80261. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  80262. return "FreeCameraVirtualJoystickInput";
  80263. };
  80264. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  80265. return "virtualJoystick";
  80266. };
  80267. return FreeCameraVirtualJoystickInput;
  80268. }());
  80269. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  80270. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  80271. })(BABYLON || (BABYLON = {}));
  80272. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  80273. var BABYLON;
  80274. (function (BABYLON) {
  80275. var SimplificationSettings = /** @class */ (function () {
  80276. function SimplificationSettings(quality, distance, optimizeMesh) {
  80277. this.quality = quality;
  80278. this.distance = distance;
  80279. this.optimizeMesh = optimizeMesh;
  80280. }
  80281. return SimplificationSettings;
  80282. }());
  80283. BABYLON.SimplificationSettings = SimplificationSettings;
  80284. var SimplificationQueue = /** @class */ (function () {
  80285. function SimplificationQueue() {
  80286. this.running = false;
  80287. this._simplificationArray = [];
  80288. }
  80289. SimplificationQueue.prototype.addTask = function (task) {
  80290. this._simplificationArray.push(task);
  80291. };
  80292. SimplificationQueue.prototype.executeNext = function () {
  80293. var task = this._simplificationArray.pop();
  80294. if (task) {
  80295. this.running = true;
  80296. this.runSimplification(task);
  80297. }
  80298. else {
  80299. this.running = false;
  80300. }
  80301. };
  80302. SimplificationQueue.prototype.runSimplification = function (task) {
  80303. var _this = this;
  80304. if (task.parallelProcessing) {
  80305. //parallel simplifier
  80306. task.settings.forEach(function (setting) {
  80307. var simplifier = _this.getSimplifier(task);
  80308. simplifier.simplify(setting, function (newMesh) {
  80309. task.mesh.addLODLevel(setting.distance, newMesh);
  80310. newMesh.isVisible = true;
  80311. //check if it is the last
  80312. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  80313. //all done, run the success callback.
  80314. task.successCallback();
  80315. }
  80316. _this.executeNext();
  80317. });
  80318. });
  80319. }
  80320. else {
  80321. //single simplifier.
  80322. var simplifier = this.getSimplifier(task);
  80323. var runDecimation = function (setting, callback) {
  80324. simplifier.simplify(setting, function (newMesh) {
  80325. task.mesh.addLODLevel(setting.distance, newMesh);
  80326. newMesh.isVisible = true;
  80327. //run the next quality level
  80328. callback();
  80329. });
  80330. };
  80331. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  80332. runDecimation(task.settings[loop.index], function () {
  80333. loop.executeNext();
  80334. });
  80335. }, function () {
  80336. //execution ended, run the success callback.
  80337. if (task.successCallback) {
  80338. task.successCallback();
  80339. }
  80340. _this.executeNext();
  80341. });
  80342. }
  80343. };
  80344. SimplificationQueue.prototype.getSimplifier = function (task) {
  80345. switch (task.simplificationType) {
  80346. case SimplificationType.QUADRATIC:
  80347. default:
  80348. return new QuadraticErrorSimplification(task.mesh);
  80349. }
  80350. };
  80351. return SimplificationQueue;
  80352. }());
  80353. BABYLON.SimplificationQueue = SimplificationQueue;
  80354. /**
  80355. * The implemented types of simplification.
  80356. * At the moment only Quadratic Error Decimation is implemented.
  80357. */
  80358. var SimplificationType;
  80359. (function (SimplificationType) {
  80360. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  80361. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  80362. var DecimationTriangle = /** @class */ (function () {
  80363. function DecimationTriangle(vertices) {
  80364. this.vertices = vertices;
  80365. this.error = new Array(4);
  80366. this.deleted = false;
  80367. this.isDirty = false;
  80368. this.deletePending = false;
  80369. this.borderFactor = 0;
  80370. }
  80371. return DecimationTriangle;
  80372. }());
  80373. BABYLON.DecimationTriangle = DecimationTriangle;
  80374. var DecimationVertex = /** @class */ (function () {
  80375. function DecimationVertex(position, id) {
  80376. this.position = position;
  80377. this.id = id;
  80378. this.isBorder = true;
  80379. this.q = new QuadraticMatrix();
  80380. this.triangleCount = 0;
  80381. this.triangleStart = 0;
  80382. this.originalOffsets = [];
  80383. }
  80384. DecimationVertex.prototype.updatePosition = function (newPosition) {
  80385. this.position.copyFrom(newPosition);
  80386. };
  80387. return DecimationVertex;
  80388. }());
  80389. BABYLON.DecimationVertex = DecimationVertex;
  80390. var QuadraticMatrix = /** @class */ (function () {
  80391. function QuadraticMatrix(data) {
  80392. this.data = new Array(10);
  80393. for (var i = 0; i < 10; ++i) {
  80394. if (data && data[i]) {
  80395. this.data[i] = data[i];
  80396. }
  80397. else {
  80398. this.data[i] = 0;
  80399. }
  80400. }
  80401. }
  80402. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  80403. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  80404. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  80405. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  80406. return det;
  80407. };
  80408. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  80409. for (var i = 0; i < 10; ++i) {
  80410. this.data[i] += matrix.data[i];
  80411. }
  80412. };
  80413. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  80414. for (var i = 0; i < 10; ++i) {
  80415. this.data[i] += data[i];
  80416. }
  80417. };
  80418. QuadraticMatrix.prototype.add = function (matrix) {
  80419. var m = new QuadraticMatrix();
  80420. for (var i = 0; i < 10; ++i) {
  80421. m.data[i] = this.data[i] + matrix.data[i];
  80422. }
  80423. return m;
  80424. };
  80425. QuadraticMatrix.FromData = function (a, b, c, d) {
  80426. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  80427. };
  80428. //returning an array to avoid garbage collection
  80429. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  80430. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  80431. };
  80432. return QuadraticMatrix;
  80433. }());
  80434. BABYLON.QuadraticMatrix = QuadraticMatrix;
  80435. var Reference = /** @class */ (function () {
  80436. function Reference(vertexId, triangleId) {
  80437. this.vertexId = vertexId;
  80438. this.triangleId = triangleId;
  80439. }
  80440. return Reference;
  80441. }());
  80442. BABYLON.Reference = Reference;
  80443. /**
  80444. * An implementation of the Quadratic Error simplification algorithm.
  80445. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  80446. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  80447. * @author RaananW
  80448. */
  80449. var QuadraticErrorSimplification = /** @class */ (function () {
  80450. function QuadraticErrorSimplification(_mesh) {
  80451. this._mesh = _mesh;
  80452. this.syncIterations = 5000;
  80453. this.aggressiveness = 7;
  80454. this.decimationIterations = 100;
  80455. this.boundingBoxEpsilon = BABYLON.Epsilon;
  80456. }
  80457. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  80458. var _this = this;
  80459. this.initDecimatedMesh();
  80460. //iterating through the submeshes array, one after the other.
  80461. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  80462. _this.initWithMesh(loop.index, function () {
  80463. _this.runDecimation(settings, loop.index, function () {
  80464. loop.executeNext();
  80465. });
  80466. }, settings.optimizeMesh);
  80467. }, function () {
  80468. setTimeout(function () {
  80469. successCallback(_this._reconstructedMesh);
  80470. }, 0);
  80471. });
  80472. };
  80473. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  80474. var _this = this;
  80475. var targetCount = ~~(this.triangles.length * settings.quality);
  80476. var deletedTriangles = 0;
  80477. var triangleCount = this.triangles.length;
  80478. var iterationFunction = function (iteration, callback) {
  80479. setTimeout(function () {
  80480. if (iteration % 5 === 0) {
  80481. _this.updateMesh(iteration === 0);
  80482. }
  80483. for (var i = 0; i < _this.triangles.length; ++i) {
  80484. _this.triangles[i].isDirty = false;
  80485. }
  80486. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  80487. var trianglesIterator = function (i) {
  80488. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  80489. var t = _this.triangles[tIdx];
  80490. if (!t)
  80491. return;
  80492. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  80493. return;
  80494. }
  80495. for (var j = 0; j < 3; ++j) {
  80496. if (t.error[j] < threshold) {
  80497. var deleted0 = [];
  80498. var deleted1 = [];
  80499. var v0 = t.vertices[j];
  80500. var v1 = t.vertices[(j + 1) % 3];
  80501. if (v0.isBorder || v1.isBorder)
  80502. continue;
  80503. var p = BABYLON.Vector3.Zero();
  80504. var n = BABYLON.Vector3.Zero();
  80505. var uv = BABYLON.Vector2.Zero();
  80506. var color = new BABYLON.Color4(0, 0, 0, 1);
  80507. _this.calculateError(v0, v1, p, n, uv, color);
  80508. var delTr = new Array();
  80509. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  80510. continue;
  80511. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  80512. continue;
  80513. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  80514. continue;
  80515. var uniqueArray = new Array();
  80516. delTr.forEach(function (deletedT) {
  80517. if (uniqueArray.indexOf(deletedT) === -1) {
  80518. deletedT.deletePending = true;
  80519. uniqueArray.push(deletedT);
  80520. }
  80521. });
  80522. if (uniqueArray.length % 2 !== 0) {
  80523. continue;
  80524. }
  80525. v0.q = v1.q.add(v0.q);
  80526. v0.updatePosition(p);
  80527. var tStart = _this.references.length;
  80528. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  80529. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  80530. var tCount = _this.references.length - tStart;
  80531. if (tCount <= v0.triangleCount) {
  80532. if (tCount) {
  80533. for (var c = 0; c < tCount; c++) {
  80534. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  80535. }
  80536. }
  80537. }
  80538. else {
  80539. v0.triangleStart = tStart;
  80540. }
  80541. v0.triangleCount = tCount;
  80542. break;
  80543. }
  80544. }
  80545. };
  80546. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  80547. }, 0);
  80548. };
  80549. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  80550. if (triangleCount - deletedTriangles <= targetCount)
  80551. loop.breakLoop();
  80552. else {
  80553. iterationFunction(loop.index, function () {
  80554. loop.executeNext();
  80555. });
  80556. }
  80557. }, function () {
  80558. setTimeout(function () {
  80559. //reconstruct this part of the mesh
  80560. _this.reconstructMesh(submeshIndex);
  80561. successCallback();
  80562. }, 0);
  80563. });
  80564. };
  80565. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  80566. var _this = this;
  80567. this.vertices = [];
  80568. this.triangles = [];
  80569. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  80570. var indices = this._mesh.getIndices();
  80571. var submesh = this._mesh.subMeshes[submeshIndex];
  80572. var findInVertices = function (positionToSearch) {
  80573. if (optimizeMesh) {
  80574. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  80575. if (_this.vertices[ii].position.equals(positionToSearch)) {
  80576. return _this.vertices[ii];
  80577. }
  80578. }
  80579. }
  80580. return null;
  80581. };
  80582. var vertexReferences = [];
  80583. var vertexInit = function (i) {
  80584. if (!positionData) {
  80585. return;
  80586. }
  80587. var offset = i + submesh.verticesStart;
  80588. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  80589. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  80590. vertex.originalOffsets.push(offset);
  80591. if (vertex.id === _this.vertices.length) {
  80592. _this.vertices.push(vertex);
  80593. }
  80594. vertexReferences.push(vertex.id);
  80595. };
  80596. //var totalVertices = mesh.getTotalVertices();
  80597. var totalVertices = submesh.verticesCount;
  80598. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  80599. var indicesInit = function (i) {
  80600. if (!indices) {
  80601. return;
  80602. }
  80603. var offset = (submesh.indexStart / 3) + i;
  80604. var pos = (offset * 3);
  80605. var i0 = indices[pos + 0];
  80606. var i1 = indices[pos + 1];
  80607. var i2 = indices[pos + 2];
  80608. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  80609. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  80610. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  80611. var triangle = new DecimationTriangle([v0, v1, v2]);
  80612. triangle.originalOffset = pos;
  80613. _this.triangles.push(triangle);
  80614. };
  80615. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  80616. _this.init(callback);
  80617. });
  80618. });
  80619. };
  80620. QuadraticErrorSimplification.prototype.init = function (callback) {
  80621. var _this = this;
  80622. var triangleInit1 = function (i) {
  80623. var t = _this.triangles[i];
  80624. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  80625. for (var j = 0; j < 3; j++) {
  80626. 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))));
  80627. }
  80628. };
  80629. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  80630. var triangleInit2 = function (i) {
  80631. var t = _this.triangles[i];
  80632. for (var j = 0; j < 3; ++j) {
  80633. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  80634. }
  80635. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  80636. };
  80637. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  80638. callback();
  80639. });
  80640. });
  80641. };
  80642. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  80643. var newTriangles = [];
  80644. var i;
  80645. for (i = 0; i < this.vertices.length; ++i) {
  80646. this.vertices[i].triangleCount = 0;
  80647. }
  80648. var t;
  80649. var j;
  80650. for (i = 0; i < this.triangles.length; ++i) {
  80651. if (!this.triangles[i].deleted) {
  80652. t = this.triangles[i];
  80653. for (j = 0; j < 3; ++j) {
  80654. t.vertices[j].triangleCount = 1;
  80655. }
  80656. newTriangles.push(t);
  80657. }
  80658. }
  80659. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  80660. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  80661. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  80662. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  80663. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  80664. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  80665. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  80666. var vertexCount = 0;
  80667. for (i = 0; i < this.vertices.length; ++i) {
  80668. var vertex = this.vertices[i];
  80669. vertex.id = vertexCount;
  80670. if (vertex.triangleCount) {
  80671. vertex.originalOffsets.forEach(function (originalOffset) {
  80672. if (!normalData) {
  80673. return;
  80674. }
  80675. newPositionData.push(vertex.position.x);
  80676. newPositionData.push(vertex.position.y);
  80677. newPositionData.push(vertex.position.z);
  80678. newNormalData.push(normalData[originalOffset * 3]);
  80679. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  80680. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  80681. if (uvs && uvs.length) {
  80682. newUVsData.push(uvs[(originalOffset * 2)]);
  80683. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  80684. }
  80685. else if (colorsData && colorsData.length) {
  80686. newColorsData.push(colorsData[(originalOffset * 4)]);
  80687. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  80688. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  80689. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  80690. }
  80691. ++vertexCount;
  80692. });
  80693. }
  80694. }
  80695. var startingIndex = this._reconstructedMesh.getTotalIndices();
  80696. var startingVertex = this._reconstructedMesh.getTotalVertices();
  80697. var submeshesArray = this._reconstructedMesh.subMeshes;
  80698. this._reconstructedMesh.subMeshes = [];
  80699. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  80700. var originalIndices = this._mesh.getIndices();
  80701. for (i = 0; i < newTriangles.length; ++i) {
  80702. t = newTriangles[i]; //now get the new referencing point for each vertex
  80703. [0, 1, 2].forEach(function (idx) {
  80704. var id = originalIndices[t.originalOffset + idx];
  80705. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  80706. if (offset < 0)
  80707. offset = 0;
  80708. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  80709. });
  80710. }
  80711. //overwriting the old vertex buffers and indices.
  80712. this._reconstructedMesh.setIndices(newIndicesArray);
  80713. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  80714. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  80715. if (newUVsData.length > 0)
  80716. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  80717. if (newColorsData.length > 0)
  80718. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  80719. //create submesh
  80720. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  80721. if (submeshIndex > 0) {
  80722. this._reconstructedMesh.subMeshes = [];
  80723. submeshesArray.forEach(function (submesh) {
  80724. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  80725. });
  80726. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  80727. }
  80728. };
  80729. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  80730. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  80731. this._reconstructedMesh.material = this._mesh.material;
  80732. this._reconstructedMesh.parent = this._mesh.parent;
  80733. this._reconstructedMesh.isVisible = false;
  80734. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  80735. };
  80736. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  80737. for (var i = 0; i < vertex1.triangleCount; ++i) {
  80738. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  80739. if (t.deleted)
  80740. continue;
  80741. var s = this.references[vertex1.triangleStart + i].vertexId;
  80742. var v1 = t.vertices[(s + 1) % 3];
  80743. var v2 = t.vertices[(s + 2) % 3];
  80744. if ((v1 === vertex2 || v2 === vertex2)) {
  80745. deletedArray[i] = true;
  80746. delTr.push(t);
  80747. continue;
  80748. }
  80749. var d1 = v1.position.subtract(point);
  80750. d1 = d1.normalize();
  80751. var d2 = v2.position.subtract(point);
  80752. d2 = d2.normalize();
  80753. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  80754. return true;
  80755. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  80756. deletedArray[i] = false;
  80757. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  80758. return true;
  80759. }
  80760. return false;
  80761. };
  80762. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  80763. var newDeleted = deletedTriangles;
  80764. for (var i = 0; i < vertex.triangleCount; ++i) {
  80765. var ref = this.references[vertex.triangleStart + i];
  80766. var t = this.triangles[ref.triangleId];
  80767. if (t.deleted)
  80768. continue;
  80769. if (deletedArray[i] && t.deletePending) {
  80770. t.deleted = true;
  80771. newDeleted++;
  80772. continue;
  80773. }
  80774. t.vertices[ref.vertexId] = origVertex;
  80775. t.isDirty = true;
  80776. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  80777. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  80778. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  80779. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  80780. this.references.push(ref);
  80781. }
  80782. return newDeleted;
  80783. };
  80784. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  80785. for (var i = 0; i < this.vertices.length; ++i) {
  80786. var vCount = [];
  80787. var vId = [];
  80788. var v = this.vertices[i];
  80789. var j;
  80790. for (j = 0; j < v.triangleCount; ++j) {
  80791. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  80792. for (var ii = 0; ii < 3; ii++) {
  80793. var ofs = 0;
  80794. var vv = triangle.vertices[ii];
  80795. while (ofs < vCount.length) {
  80796. if (vId[ofs] === vv.id)
  80797. break;
  80798. ++ofs;
  80799. }
  80800. if (ofs === vCount.length) {
  80801. vCount.push(1);
  80802. vId.push(vv.id);
  80803. }
  80804. else {
  80805. vCount[ofs]++;
  80806. }
  80807. }
  80808. }
  80809. for (j = 0; j < vCount.length; ++j) {
  80810. if (vCount[j] === 1) {
  80811. this.vertices[vId[j]].isBorder = true;
  80812. }
  80813. else {
  80814. this.vertices[vId[j]].isBorder = false;
  80815. }
  80816. }
  80817. }
  80818. };
  80819. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  80820. if (identifyBorders === void 0) { identifyBorders = false; }
  80821. var i;
  80822. if (!identifyBorders) {
  80823. var newTrianglesVector = [];
  80824. for (i = 0; i < this.triangles.length; ++i) {
  80825. if (!this.triangles[i].deleted) {
  80826. newTrianglesVector.push(this.triangles[i]);
  80827. }
  80828. }
  80829. this.triangles = newTrianglesVector;
  80830. }
  80831. for (i = 0; i < this.vertices.length; ++i) {
  80832. this.vertices[i].triangleCount = 0;
  80833. this.vertices[i].triangleStart = 0;
  80834. }
  80835. var t;
  80836. var j;
  80837. var v;
  80838. for (i = 0; i < this.triangles.length; ++i) {
  80839. t = this.triangles[i];
  80840. for (j = 0; j < 3; ++j) {
  80841. v = t.vertices[j];
  80842. v.triangleCount++;
  80843. }
  80844. }
  80845. var tStart = 0;
  80846. for (i = 0; i < this.vertices.length; ++i) {
  80847. this.vertices[i].triangleStart = tStart;
  80848. tStart += this.vertices[i].triangleCount;
  80849. this.vertices[i].triangleCount = 0;
  80850. }
  80851. var newReferences = new Array(this.triangles.length * 3);
  80852. for (i = 0; i < this.triangles.length; ++i) {
  80853. t = this.triangles[i];
  80854. for (j = 0; j < 3; ++j) {
  80855. v = t.vertices[j];
  80856. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  80857. v.triangleCount++;
  80858. }
  80859. }
  80860. this.references = newReferences;
  80861. if (identifyBorders) {
  80862. this.identifyBorder();
  80863. }
  80864. };
  80865. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  80866. var x = point.x;
  80867. var y = point.y;
  80868. var z = point.z;
  80869. 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
  80870. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  80871. };
  80872. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  80873. var q = vertex1.q.add(vertex2.q);
  80874. var border = vertex1.isBorder && vertex2.isBorder;
  80875. var error = 0;
  80876. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  80877. if (qDet !== 0 && !border) {
  80878. if (!pointResult) {
  80879. pointResult = BABYLON.Vector3.Zero();
  80880. }
  80881. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  80882. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  80883. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  80884. error = this.vertexError(q, pointResult);
  80885. }
  80886. else {
  80887. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  80888. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  80889. var error1 = this.vertexError(q, vertex1.position);
  80890. var error2 = this.vertexError(q, vertex2.position);
  80891. var error3 = this.vertexError(q, p3);
  80892. error = Math.min(error1, error2, error3);
  80893. if (error === error1) {
  80894. if (pointResult) {
  80895. pointResult.copyFrom(vertex1.position);
  80896. }
  80897. }
  80898. else if (error === error2) {
  80899. if (pointResult) {
  80900. pointResult.copyFrom(vertex2.position);
  80901. }
  80902. }
  80903. else {
  80904. if (pointResult) {
  80905. pointResult.copyFrom(p3);
  80906. }
  80907. }
  80908. }
  80909. return error;
  80910. };
  80911. return QuadraticErrorSimplification;
  80912. }());
  80913. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  80914. })(BABYLON || (BABYLON = {}));
  80915. //# sourceMappingURL=babylon.meshSimplification.js.map
  80916. var BABYLON;
  80917. (function (BABYLON) {
  80918. var MeshLODLevel = /** @class */ (function () {
  80919. function MeshLODLevel(distance, mesh) {
  80920. this.distance = distance;
  80921. this.mesh = mesh;
  80922. }
  80923. return MeshLODLevel;
  80924. }());
  80925. BABYLON.MeshLODLevel = MeshLODLevel;
  80926. })(BABYLON || (BABYLON = {}));
  80927. //# sourceMappingURL=babylon.meshLODLevel.js.map
  80928. var BABYLON;
  80929. (function (BABYLON) {
  80930. /**
  80931. * Defines the root class used to create scene optimization to use with SceneOptimizer
  80932. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  80933. */
  80934. var SceneOptimization = /** @class */ (function () {
  80935. /**
  80936. * Creates the SceneOptimization object
  80937. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  80938. * @param desc defines the description associated with the optimization
  80939. */
  80940. function SceneOptimization(
  80941. /**
  80942. * Defines the priority of this optimization (0 by default which means first in the list)
  80943. */
  80944. priority) {
  80945. if (priority === void 0) { priority = 0; }
  80946. this.priority = priority;
  80947. }
  80948. /**
  80949. * Gets a string describing the action executed by the current optimization
  80950. * @returns description string
  80951. */
  80952. SceneOptimization.prototype.getDescription = function () {
  80953. return "";
  80954. };
  80955. /**
  80956. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  80957. * @param scene defines the current scene where to apply this optimization
  80958. * @param optimizer defines the current optimizer
  80959. * @returns true if everything that can be done was applied
  80960. */
  80961. SceneOptimization.prototype.apply = function (scene, optimizer) {
  80962. return true;
  80963. };
  80964. ;
  80965. return SceneOptimization;
  80966. }());
  80967. BABYLON.SceneOptimization = SceneOptimization;
  80968. /**
  80969. * Defines an optimization used to reduce the size of render target textures
  80970. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  80971. */
  80972. var TextureOptimization = /** @class */ (function (_super) {
  80973. __extends(TextureOptimization, _super);
  80974. /**
  80975. * Creates the TextureOptimization object
  80976. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  80977. * @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
  80978. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  80979. */
  80980. function TextureOptimization(
  80981. /**
  80982. * Defines the priority of this optimization (0 by default which means first in the list)
  80983. */
  80984. priority,
  80985. /**
  80986. * 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
  80987. */
  80988. maximumSize,
  80989. /**
  80990. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  80991. */
  80992. step) {
  80993. if (priority === void 0) { priority = 0; }
  80994. if (maximumSize === void 0) { maximumSize = 1024; }
  80995. if (step === void 0) { step = 0.5; }
  80996. var _this = _super.call(this, priority) || this;
  80997. _this.priority = priority;
  80998. _this.maximumSize = maximumSize;
  80999. _this.step = step;
  81000. return _this;
  81001. }
  81002. /**
  81003. * Gets a string describing the action executed by the current optimization
  81004. * @returns description string
  81005. */
  81006. TextureOptimization.prototype.getDescription = function () {
  81007. return "Reducing render target texture size to " + this.maximumSize;
  81008. };
  81009. /**
  81010. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  81011. * @param scene defines the current scene where to apply this optimization
  81012. * @param optimizer defines the current optimizer
  81013. * @returns true if everything that can be done was applied
  81014. */
  81015. TextureOptimization.prototype.apply = function (scene, optimizer) {
  81016. var allDone = true;
  81017. for (var index = 0; index < scene.textures.length; index++) {
  81018. var texture = scene.textures[index];
  81019. if (!texture.canRescale || texture.getContext) {
  81020. continue;
  81021. }
  81022. var currentSize = texture.getSize();
  81023. var maxDimension = Math.max(currentSize.width, currentSize.height);
  81024. if (maxDimension > this.maximumSize) {
  81025. texture.scale(this.step);
  81026. allDone = false;
  81027. }
  81028. }
  81029. return allDone;
  81030. };
  81031. return TextureOptimization;
  81032. }(SceneOptimization));
  81033. BABYLON.TextureOptimization = TextureOptimization;
  81034. /**
  81035. * Defines an optimization used to increase or decrease the rendering resolution
  81036. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  81037. */
  81038. var HardwareScalingOptimization = /** @class */ (function (_super) {
  81039. __extends(HardwareScalingOptimization, _super);
  81040. /**
  81041. * Creates the HardwareScalingOptimization object
  81042. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  81043. * @param maximumScale defines the maximum scale to use (2 by default)
  81044. * @param step defines the step to use between two passes (0.5 by default)
  81045. */
  81046. function HardwareScalingOptimization(
  81047. /**
  81048. * Defines the priority of this optimization (0 by default which means first in the list)
  81049. */
  81050. priority,
  81051. /**
  81052. * Defines the maximum scale to use (2 by default)
  81053. */
  81054. maximumScale,
  81055. /**
  81056. * Defines the step to use between two passes (0.5 by default)
  81057. */
  81058. step) {
  81059. if (priority === void 0) { priority = 0; }
  81060. if (maximumScale === void 0) { maximumScale = 2; }
  81061. if (step === void 0) { step = 0.25; }
  81062. var _this = _super.call(this, priority) || this;
  81063. _this.priority = priority;
  81064. _this.maximumScale = maximumScale;
  81065. _this.step = step;
  81066. _this._currentScale = -1;
  81067. _this._directionOffset = 1;
  81068. return _this;
  81069. }
  81070. /**
  81071. * Gets a string describing the action executed by the current optimization
  81072. * @return description string
  81073. */
  81074. HardwareScalingOptimization.prototype.getDescription = function () {
  81075. return "Setting hardware scaling level to " + this._currentScale;
  81076. };
  81077. /**
  81078. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  81079. * @param scene defines the current scene where to apply this optimization
  81080. * @param optimizer defines the current optimizer
  81081. * @returns true if everything that can be done was applied
  81082. */
  81083. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  81084. if (this._currentScale === -1) {
  81085. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  81086. if (this._currentScale > this.maximumScale) {
  81087. this._directionOffset = -1;
  81088. }
  81089. }
  81090. this._currentScale += this._directionOffset * this.step;
  81091. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  81092. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  81093. };
  81094. ;
  81095. return HardwareScalingOptimization;
  81096. }(SceneOptimization));
  81097. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  81098. /**
  81099. * Defines an optimization used to remove shadows
  81100. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  81101. */
  81102. var ShadowsOptimization = /** @class */ (function (_super) {
  81103. __extends(ShadowsOptimization, _super);
  81104. function ShadowsOptimization() {
  81105. return _super !== null && _super.apply(this, arguments) || this;
  81106. }
  81107. /**
  81108. * Gets a string describing the action executed by the current optimization
  81109. * @return description string
  81110. */
  81111. ShadowsOptimization.prototype.getDescription = function () {
  81112. return "Turning shadows on/off";
  81113. };
  81114. /**
  81115. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  81116. * @param scene defines the current scene where to apply this optimization
  81117. * @param optimizer defines the current optimizer
  81118. * @returns true if everything that can be done was applied
  81119. */
  81120. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  81121. scene.shadowsEnabled = optimizer.isInImprovementMode;
  81122. return true;
  81123. };
  81124. ;
  81125. return ShadowsOptimization;
  81126. }(SceneOptimization));
  81127. BABYLON.ShadowsOptimization = ShadowsOptimization;
  81128. /**
  81129. * Defines an optimization used to turn post-processes off
  81130. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  81131. */
  81132. var PostProcessesOptimization = /** @class */ (function (_super) {
  81133. __extends(PostProcessesOptimization, _super);
  81134. function PostProcessesOptimization() {
  81135. return _super !== null && _super.apply(this, arguments) || this;
  81136. }
  81137. /**
  81138. * Gets a string describing the action executed by the current optimization
  81139. * @return description string
  81140. */
  81141. PostProcessesOptimization.prototype.getDescription = function () {
  81142. return "Turning post-processes on/off";
  81143. };
  81144. /**
  81145. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  81146. * @param scene defines the current scene where to apply this optimization
  81147. * @param optimizer defines the current optimizer
  81148. * @returns true if everything that can be done was applied
  81149. */
  81150. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  81151. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  81152. return true;
  81153. };
  81154. ;
  81155. return PostProcessesOptimization;
  81156. }(SceneOptimization));
  81157. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  81158. /**
  81159. * Defines an optimization used to turn lens flares off
  81160. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  81161. */
  81162. var LensFlaresOptimization = /** @class */ (function (_super) {
  81163. __extends(LensFlaresOptimization, _super);
  81164. function LensFlaresOptimization() {
  81165. return _super !== null && _super.apply(this, arguments) || this;
  81166. }
  81167. /**
  81168. * Gets a string describing the action executed by the current optimization
  81169. * @return description string
  81170. */
  81171. LensFlaresOptimization.prototype.getDescription = function () {
  81172. return "Turning lens flares on/off";
  81173. };
  81174. /**
  81175. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  81176. * @param scene defines the current scene where to apply this optimization
  81177. * @param optimizer defines the current optimizer
  81178. * @returns true if everything that can be done was applied
  81179. */
  81180. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  81181. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  81182. return true;
  81183. };
  81184. ;
  81185. return LensFlaresOptimization;
  81186. }(SceneOptimization));
  81187. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  81188. /**
  81189. * Defines an optimization based on user defined callback.
  81190. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  81191. */
  81192. var CustomOptimization = /** @class */ (function (_super) {
  81193. __extends(CustomOptimization, _super);
  81194. function CustomOptimization() {
  81195. return _super !== null && _super.apply(this, arguments) || this;
  81196. }
  81197. /**
  81198. * Gets a string describing the action executed by the current optimization
  81199. * @returns description string
  81200. */
  81201. CustomOptimization.prototype.getDescription = function () {
  81202. if (this.onGetDescription) {
  81203. return this.onGetDescription();
  81204. }
  81205. return "Running user defined callback";
  81206. };
  81207. /**
  81208. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  81209. * @param scene defines the current scene where to apply this optimization
  81210. * @param optimizer defines the current optimizer
  81211. * @returns true if everything that can be done was applied
  81212. */
  81213. CustomOptimization.prototype.apply = function (scene, optimizer) {
  81214. if (this.onApply) {
  81215. return this.onApply(scene, optimizer);
  81216. }
  81217. return true;
  81218. };
  81219. ;
  81220. return CustomOptimization;
  81221. }(SceneOptimization));
  81222. BABYLON.CustomOptimization = CustomOptimization;
  81223. /**
  81224. * Defines an optimization used to turn particles off
  81225. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  81226. */
  81227. var ParticlesOptimization = /** @class */ (function (_super) {
  81228. __extends(ParticlesOptimization, _super);
  81229. function ParticlesOptimization() {
  81230. return _super !== null && _super.apply(this, arguments) || this;
  81231. }
  81232. /**
  81233. * Gets a string describing the action executed by the current optimization
  81234. * @return description string
  81235. */
  81236. ParticlesOptimization.prototype.getDescription = function () {
  81237. return "Turning particles on/off";
  81238. };
  81239. /**
  81240. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  81241. * @param scene defines the current scene where to apply this optimization
  81242. * @param optimizer defines the current optimizer
  81243. * @returns true if everything that can be done was applied
  81244. */
  81245. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  81246. scene.particlesEnabled = optimizer.isInImprovementMode;
  81247. return true;
  81248. };
  81249. ;
  81250. return ParticlesOptimization;
  81251. }(SceneOptimization));
  81252. BABYLON.ParticlesOptimization = ParticlesOptimization;
  81253. /**
  81254. * Defines an optimization used to turn render targets off
  81255. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  81256. */
  81257. var RenderTargetsOptimization = /** @class */ (function (_super) {
  81258. __extends(RenderTargetsOptimization, _super);
  81259. function RenderTargetsOptimization() {
  81260. return _super !== null && _super.apply(this, arguments) || this;
  81261. }
  81262. /**
  81263. * Gets a string describing the action executed by the current optimization
  81264. * @return description string
  81265. */
  81266. RenderTargetsOptimization.prototype.getDescription = function () {
  81267. return "Turning render targets off";
  81268. };
  81269. /**
  81270. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  81271. * @param scene defines the current scene where to apply this optimization
  81272. * @param optimizer defines the current optimizer
  81273. * @returns true if everything that can be done was applied
  81274. */
  81275. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  81276. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  81277. return true;
  81278. };
  81279. ;
  81280. return RenderTargetsOptimization;
  81281. }(SceneOptimization));
  81282. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  81283. /**
  81284. * Defines an optimization used to merge meshes with compatible materials
  81285. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  81286. */
  81287. var MergeMeshesOptimization = /** @class */ (function (_super) {
  81288. __extends(MergeMeshesOptimization, _super);
  81289. function MergeMeshesOptimization() {
  81290. var _this = _super !== null && _super.apply(this, arguments) || this;
  81291. _this._canBeMerged = function (abstractMesh) {
  81292. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  81293. return false;
  81294. }
  81295. var mesh = abstractMesh;
  81296. if (!mesh.isVisible || !mesh.isEnabled()) {
  81297. return false;
  81298. }
  81299. if (mesh.instances.length > 0) {
  81300. return false;
  81301. }
  81302. if (mesh.skeleton || mesh.hasLODLevels) {
  81303. return false;
  81304. }
  81305. if (mesh.parent) {
  81306. return false;
  81307. }
  81308. return true;
  81309. };
  81310. return _this;
  81311. }
  81312. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  81313. /**
  81314. * Gets or sets a boolean which defines if optimization octree has to be updated
  81315. */
  81316. get: function () {
  81317. return MergeMeshesOptimization._UpdateSelectionTree;
  81318. },
  81319. /**
  81320. * Gets or sets a boolean which defines if optimization octree has to be updated
  81321. */
  81322. set: function (value) {
  81323. MergeMeshesOptimization._UpdateSelectionTree = value;
  81324. },
  81325. enumerable: true,
  81326. configurable: true
  81327. });
  81328. /**
  81329. * Gets a string describing the action executed by the current optimization
  81330. * @return description string
  81331. */
  81332. MergeMeshesOptimization.prototype.getDescription = function () {
  81333. return "Merging similar meshes together";
  81334. };
  81335. /**
  81336. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  81337. * @param scene defines the current scene where to apply this optimization
  81338. * @param optimizer defines the current optimizer
  81339. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  81340. * @returns true if everything that can be done was applied
  81341. */
  81342. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  81343. var globalPool = scene.meshes.slice(0);
  81344. var globalLength = globalPool.length;
  81345. for (var index = 0; index < globalLength; index++) {
  81346. var currentPool = new Array();
  81347. var current = globalPool[index];
  81348. // Checks
  81349. if (!this._canBeMerged(current)) {
  81350. continue;
  81351. }
  81352. currentPool.push(current);
  81353. // Find compatible meshes
  81354. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  81355. var otherMesh = globalPool[subIndex];
  81356. if (!this._canBeMerged(otherMesh)) {
  81357. continue;
  81358. }
  81359. if (otherMesh.material !== current.material) {
  81360. continue;
  81361. }
  81362. if (otherMesh.checkCollisions !== current.checkCollisions) {
  81363. continue;
  81364. }
  81365. currentPool.push(otherMesh);
  81366. globalLength--;
  81367. globalPool.splice(subIndex, 1);
  81368. subIndex--;
  81369. }
  81370. if (currentPool.length < 2) {
  81371. continue;
  81372. }
  81373. // Merge meshes
  81374. BABYLON.Mesh.MergeMeshes(currentPool);
  81375. }
  81376. if (updateSelectionTree != undefined) {
  81377. if (updateSelectionTree) {
  81378. scene.createOrUpdateSelectionOctree();
  81379. }
  81380. }
  81381. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  81382. scene.createOrUpdateSelectionOctree();
  81383. }
  81384. return true;
  81385. };
  81386. ;
  81387. MergeMeshesOptimization._UpdateSelectionTree = false;
  81388. return MergeMeshesOptimization;
  81389. }(SceneOptimization));
  81390. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  81391. /**
  81392. * Defines a list of options used by SceneOptimizer
  81393. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  81394. */
  81395. var SceneOptimizerOptions = /** @class */ (function () {
  81396. /**
  81397. * Creates a new list of options used by SceneOptimizer
  81398. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  81399. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  81400. */
  81401. function SceneOptimizerOptions(
  81402. /**
  81403. * Defines the target frame rate to reach (60 by default)
  81404. */
  81405. targetFrameRate,
  81406. /**
  81407. * Defines the interval between two checkes (2000ms by default)
  81408. */
  81409. trackerDuration) {
  81410. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  81411. if (trackerDuration === void 0) { trackerDuration = 2000; }
  81412. this.targetFrameRate = targetFrameRate;
  81413. this.trackerDuration = trackerDuration;
  81414. /**
  81415. * Gets the list of optimizations to apply
  81416. */
  81417. this.optimizations = new Array();
  81418. }
  81419. /**
  81420. * Add a new optimization
  81421. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  81422. * @returns the current SceneOptimizerOptions
  81423. */
  81424. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  81425. this.optimizations.push(optimization);
  81426. return this;
  81427. };
  81428. /**
  81429. * Add a new custom optimization
  81430. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  81431. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  81432. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  81433. * @returns the current SceneOptimizerOptions
  81434. */
  81435. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  81436. if (priority === void 0) { priority = 0; }
  81437. var optimization = new CustomOptimization(priority);
  81438. optimization.onApply = onApply;
  81439. optimization.onGetDescription = onGetDescription;
  81440. this.optimizations.push(optimization);
  81441. return this;
  81442. };
  81443. /**
  81444. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  81445. * @param targetFrameRate defines the target frame rate (60 by default)
  81446. * @returns a SceneOptimizerOptions object
  81447. */
  81448. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  81449. var result = new SceneOptimizerOptions(targetFrameRate);
  81450. var priority = 0;
  81451. result.addOptimization(new MergeMeshesOptimization(priority));
  81452. result.addOptimization(new ShadowsOptimization(priority));
  81453. result.addOptimization(new LensFlaresOptimization(priority));
  81454. // Next priority
  81455. priority++;
  81456. result.addOptimization(new PostProcessesOptimization(priority));
  81457. result.addOptimization(new ParticlesOptimization(priority));
  81458. // Next priority
  81459. priority++;
  81460. result.addOptimization(new TextureOptimization(priority, 1024));
  81461. return result;
  81462. };
  81463. /**
  81464. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  81465. * @param targetFrameRate defines the target frame rate (60 by default)
  81466. * @returns a SceneOptimizerOptions object
  81467. */
  81468. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  81469. var result = new SceneOptimizerOptions(targetFrameRate);
  81470. var priority = 0;
  81471. result.addOptimization(new MergeMeshesOptimization(priority));
  81472. result.addOptimization(new ShadowsOptimization(priority));
  81473. result.addOptimization(new LensFlaresOptimization(priority));
  81474. // Next priority
  81475. priority++;
  81476. result.addOptimization(new PostProcessesOptimization(priority));
  81477. result.addOptimization(new ParticlesOptimization(priority));
  81478. // Next priority
  81479. priority++;
  81480. result.addOptimization(new TextureOptimization(priority, 512));
  81481. // Next priority
  81482. priority++;
  81483. result.addOptimization(new RenderTargetsOptimization(priority));
  81484. // Next priority
  81485. priority++;
  81486. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  81487. return result;
  81488. };
  81489. /**
  81490. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  81491. * @param targetFrameRate defines the target frame rate (60 by default)
  81492. * @returns a SceneOptimizerOptions object
  81493. */
  81494. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  81495. var result = new SceneOptimizerOptions(targetFrameRate);
  81496. var priority = 0;
  81497. result.addOptimization(new MergeMeshesOptimization(priority));
  81498. result.addOptimization(new ShadowsOptimization(priority));
  81499. result.addOptimization(new LensFlaresOptimization(priority));
  81500. // Next priority
  81501. priority++;
  81502. result.addOptimization(new PostProcessesOptimization(priority));
  81503. result.addOptimization(new ParticlesOptimization(priority));
  81504. // Next priority
  81505. priority++;
  81506. result.addOptimization(new TextureOptimization(priority, 256));
  81507. // Next priority
  81508. priority++;
  81509. result.addOptimization(new RenderTargetsOptimization(priority));
  81510. // Next priority
  81511. priority++;
  81512. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  81513. return result;
  81514. };
  81515. return SceneOptimizerOptions;
  81516. }());
  81517. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  81518. /**
  81519. * Class used to run optimizations in order to reach a target frame rate
  81520. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  81521. */
  81522. var SceneOptimizer = /** @class */ (function () {
  81523. /**
  81524. * Creates a new SceneOptimizer
  81525. * @param scene defines the scene to work on
  81526. * @param options defines the options to use with the SceneOptimizer
  81527. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  81528. * @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)
  81529. */
  81530. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  81531. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  81532. if (improvementMode === void 0) { improvementMode = false; }
  81533. var _this = this;
  81534. this._isRunning = false;
  81535. this._currentPriorityLevel = 0;
  81536. this._targetFrameRate = 60;
  81537. this._trackerDuration = 2000;
  81538. this._currentFrameRate = 0;
  81539. this._improvementMode = false;
  81540. /**
  81541. * Defines an observable called when the optimizer reaches the target frame rate
  81542. */
  81543. this.onSuccessObservable = new BABYLON.Observable();
  81544. /**
  81545. * Defines an observable called when the optimizer enables an optimization
  81546. */
  81547. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  81548. /**
  81549. * Defines an observable called when the optimizer is not able to reach the target frame rate
  81550. */
  81551. this.onFailureObservable = new BABYLON.Observable();
  81552. if (!options) {
  81553. this._options = new SceneOptimizerOptions();
  81554. }
  81555. else {
  81556. this._options = options;
  81557. }
  81558. if (this._options.targetFrameRate) {
  81559. this._targetFrameRate = this._options.targetFrameRate;
  81560. }
  81561. if (this._options.trackerDuration) {
  81562. this._trackerDuration = this._options.trackerDuration;
  81563. }
  81564. if (autoGeneratePriorities) {
  81565. var priority = 0;
  81566. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  81567. var optim = _a[_i];
  81568. optim.priority = priority++;
  81569. }
  81570. }
  81571. this._improvementMode = improvementMode;
  81572. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  81573. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  81574. _this._sceneDisposeObserver = null;
  81575. _this.dispose();
  81576. });
  81577. }
  81578. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  81579. /**
  81580. * Gets a boolean indicating if the optimizer is in improvement mode
  81581. */
  81582. get: function () {
  81583. return this._improvementMode;
  81584. },
  81585. enumerable: true,
  81586. configurable: true
  81587. });
  81588. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  81589. /**
  81590. * Gets the current priority level (0 at start)
  81591. */
  81592. get: function () {
  81593. return this._currentPriorityLevel;
  81594. },
  81595. enumerable: true,
  81596. configurable: true
  81597. });
  81598. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  81599. /**
  81600. * Gets the current frame rate checked by the SceneOptimizer
  81601. */
  81602. get: function () {
  81603. return this._currentFrameRate;
  81604. },
  81605. enumerable: true,
  81606. configurable: true
  81607. });
  81608. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  81609. /**
  81610. * Gets or sets the current target frame rate (60 by default)
  81611. */
  81612. get: function () {
  81613. return this._targetFrameRate;
  81614. },
  81615. /**
  81616. * Gets or sets the current target frame rate (60 by default)
  81617. */
  81618. set: function (value) {
  81619. this._targetFrameRate = value;
  81620. },
  81621. enumerable: true,
  81622. configurable: true
  81623. });
  81624. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  81625. /**
  81626. * Gets or sets the current interval between two checks (every 2000ms by default)
  81627. */
  81628. get: function () {
  81629. return this._trackerDuration;
  81630. },
  81631. /**
  81632. * Gets or sets the current interval between two checks (every 2000ms by default)
  81633. */
  81634. set: function (value) {
  81635. this._trackerDuration = value;
  81636. },
  81637. enumerable: true,
  81638. configurable: true
  81639. });
  81640. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  81641. /**
  81642. * Gets the list of active optimizations
  81643. */
  81644. get: function () {
  81645. return this._options.optimizations;
  81646. },
  81647. enumerable: true,
  81648. configurable: true
  81649. });
  81650. /**
  81651. * Stops the current optimizer
  81652. */
  81653. SceneOptimizer.prototype.stop = function () {
  81654. this._isRunning = false;
  81655. };
  81656. /**
  81657. * Reset the optimizer to initial step (current priority level = 0)
  81658. */
  81659. SceneOptimizer.prototype.reset = function () {
  81660. this._currentPriorityLevel = 0;
  81661. };
  81662. /**
  81663. * Start the optimizer. By default it will try to reach a specific framerate
  81664. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  81665. */
  81666. SceneOptimizer.prototype.start = function () {
  81667. var _this = this;
  81668. if (this._isRunning) {
  81669. return;
  81670. }
  81671. this._isRunning = true;
  81672. // Let's wait for the scene to be ready before running our check
  81673. this._scene.executeWhenReady(function () {
  81674. setTimeout(function () {
  81675. _this._checkCurrentState();
  81676. }, _this._trackerDuration);
  81677. });
  81678. };
  81679. SceneOptimizer.prototype._checkCurrentState = function () {
  81680. var _this = this;
  81681. if (!this._isRunning) {
  81682. return;
  81683. }
  81684. var scene = this._scene;
  81685. var options = this._options;
  81686. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  81687. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  81688. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  81689. this._isRunning = false;
  81690. this.onSuccessObservable.notifyObservers(this);
  81691. return;
  81692. }
  81693. // Apply current level of optimizations
  81694. var allDone = true;
  81695. var noOptimizationApplied = true;
  81696. for (var index = 0; index < options.optimizations.length; index++) {
  81697. var optimization = options.optimizations[index];
  81698. if (optimization.priority === this._currentPriorityLevel) {
  81699. noOptimizationApplied = false;
  81700. allDone = allDone && optimization.apply(scene, this);
  81701. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  81702. }
  81703. }
  81704. // If no optimization was applied, this is a failure :(
  81705. if (noOptimizationApplied) {
  81706. this._isRunning = false;
  81707. this.onFailureObservable.notifyObservers(this);
  81708. return;
  81709. }
  81710. // If all optimizations were done, move to next level
  81711. if (allDone) {
  81712. this._currentPriorityLevel++;
  81713. }
  81714. // Let's the system running for a specific amount of time before checking FPS
  81715. scene.executeWhenReady(function () {
  81716. setTimeout(function () {
  81717. _this._checkCurrentState();
  81718. }, _this._trackerDuration);
  81719. });
  81720. };
  81721. /**
  81722. * Release all resources
  81723. */
  81724. SceneOptimizer.prototype.dispose = function () {
  81725. this.stop();
  81726. this.onSuccessObservable.clear();
  81727. this.onFailureObservable.clear();
  81728. this.onNewOptimizationAppliedObservable.clear();
  81729. if (this._sceneDisposeObserver) {
  81730. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  81731. }
  81732. };
  81733. /**
  81734. * Helper function to create a SceneOptimizer with one single line of code
  81735. * @param scene defines the scene to work on
  81736. * @param options defines the options to use with the SceneOptimizer
  81737. * @param onSuccess defines a callback to call on success
  81738. * @param onFailure defines a callback to call on failure
  81739. * @returns the new SceneOptimizer object
  81740. */
  81741. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  81742. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  81743. if (onSuccess) {
  81744. optimizer.onSuccessObservable.add(function () {
  81745. onSuccess();
  81746. });
  81747. }
  81748. if (onFailure) {
  81749. optimizer.onFailureObservable.add(function () {
  81750. onFailure();
  81751. });
  81752. }
  81753. optimizer.start();
  81754. return optimizer;
  81755. };
  81756. return SceneOptimizer;
  81757. }());
  81758. BABYLON.SceneOptimizer = SceneOptimizer;
  81759. })(BABYLON || (BABYLON = {}));
  81760. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  81761. var BABYLON;
  81762. (function (BABYLON) {
  81763. var OutlineRenderer = /** @class */ (function () {
  81764. function OutlineRenderer(scene) {
  81765. this.zOffset = 1;
  81766. this._scene = scene;
  81767. }
  81768. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  81769. var _this = this;
  81770. if (useOverlay === void 0) { useOverlay = false; }
  81771. var scene = this._scene;
  81772. var engine = this._scene.getEngine();
  81773. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  81774. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  81775. return;
  81776. }
  81777. var mesh = subMesh.getRenderingMesh();
  81778. var material = subMesh.getMaterial();
  81779. if (!material || !scene.activeCamera) {
  81780. return;
  81781. }
  81782. engine.enableEffect(this._effect);
  81783. // Logarithmic depth
  81784. if (material.useLogarithmicDepth) {
  81785. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  81786. }
  81787. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  81788. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  81789. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  81790. // Bones
  81791. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  81792. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  81793. }
  81794. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  81795. // Alpha test
  81796. if (material && material.needAlphaTesting()) {
  81797. var alphaTexture = material.getAlphaTestTexture();
  81798. if (alphaTexture) {
  81799. this._effect.setTexture("diffuseSampler", alphaTexture);
  81800. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  81801. }
  81802. }
  81803. engine.setZOffset(-this.zOffset);
  81804. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  81805. engine.setZOffset(0);
  81806. };
  81807. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  81808. var defines = [];
  81809. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  81810. var mesh = subMesh.getMesh();
  81811. var material = subMesh.getMaterial();
  81812. if (material) {
  81813. // Alpha test
  81814. if (material.needAlphaTesting()) {
  81815. defines.push("#define ALPHATEST");
  81816. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  81817. attribs.push(BABYLON.VertexBuffer.UVKind);
  81818. defines.push("#define UV1");
  81819. }
  81820. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  81821. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  81822. defines.push("#define UV2");
  81823. }
  81824. }
  81825. //Logarithmic depth
  81826. if (material.useLogarithmicDepth) {
  81827. defines.push("#define LOGARITHMICDEPTH");
  81828. }
  81829. }
  81830. // Bones
  81831. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  81832. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  81833. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  81834. if (mesh.numBoneInfluencers > 4) {
  81835. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  81836. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  81837. }
  81838. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  81839. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  81840. }
  81841. else {
  81842. defines.push("#define NUM_BONE_INFLUENCERS 0");
  81843. }
  81844. // Instances
  81845. if (useInstances) {
  81846. defines.push("#define INSTANCES");
  81847. attribs.push("world0");
  81848. attribs.push("world1");
  81849. attribs.push("world2");
  81850. attribs.push("world3");
  81851. }
  81852. // Get correct effect
  81853. var join = defines.join("\n");
  81854. if (this._cachedDefines !== join) {
  81855. this._cachedDefines = join;
  81856. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  81857. }
  81858. return this._effect.isReady();
  81859. };
  81860. return OutlineRenderer;
  81861. }());
  81862. BABYLON.OutlineRenderer = OutlineRenderer;
  81863. })(BABYLON || (BABYLON = {}));
  81864. //# sourceMappingURL=babylon.outlineRenderer.js.map
  81865. var BABYLON;
  81866. (function (BABYLON) {
  81867. var FaceAdjacencies = /** @class */ (function () {
  81868. function FaceAdjacencies() {
  81869. this.edges = new Array();
  81870. this.edgesConnectedCount = 0;
  81871. }
  81872. return FaceAdjacencies;
  81873. }());
  81874. var EdgesRenderer = /** @class */ (function () {
  81875. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  81876. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  81877. if (epsilon === void 0) { epsilon = 0.95; }
  81878. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  81879. this.edgesWidthScalerForOrthographic = 1000.0;
  81880. this.edgesWidthScalerForPerspective = 50.0;
  81881. this._linesPositions = new Array();
  81882. this._linesNormals = new Array();
  81883. this._linesIndices = new Array();
  81884. this._buffers = {};
  81885. this._checkVerticesInsteadOfIndices = false;
  81886. this._source = source;
  81887. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  81888. this._epsilon = epsilon;
  81889. this._prepareRessources();
  81890. this._generateEdgesLines();
  81891. }
  81892. EdgesRenderer.prototype._prepareRessources = function () {
  81893. if (this._lineShader) {
  81894. return;
  81895. }
  81896. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  81897. attributes: ["position", "normal"],
  81898. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  81899. });
  81900. this._lineShader.disableDepthWrite = true;
  81901. this._lineShader.backFaceCulling = false;
  81902. };
  81903. EdgesRenderer.prototype._rebuild = function () {
  81904. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  81905. if (buffer) {
  81906. buffer._rebuild();
  81907. }
  81908. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  81909. if (buffer) {
  81910. buffer._rebuild();
  81911. }
  81912. var scene = this._source.getScene();
  81913. var engine = scene.getEngine();
  81914. this._ib = engine.createIndexBuffer(this._linesIndices);
  81915. };
  81916. EdgesRenderer.prototype.dispose = function () {
  81917. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  81918. if (buffer) {
  81919. buffer.dispose();
  81920. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  81921. }
  81922. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  81923. if (buffer) {
  81924. buffer.dispose();
  81925. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  81926. }
  81927. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  81928. this._lineShader.dispose();
  81929. };
  81930. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  81931. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  81932. return 0;
  81933. }
  81934. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  81935. return 1;
  81936. }
  81937. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  81938. return 2;
  81939. }
  81940. return -1;
  81941. };
  81942. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  81943. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  81944. return 0;
  81945. }
  81946. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  81947. return 1;
  81948. }
  81949. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  81950. return 2;
  81951. }
  81952. return -1;
  81953. };
  81954. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  81955. var needToCreateLine;
  81956. if (edge === undefined) {
  81957. needToCreateLine = true;
  81958. }
  81959. else {
  81960. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  81961. needToCreateLine = dotProduct < this._epsilon;
  81962. }
  81963. if (needToCreateLine) {
  81964. var offset = this._linesPositions.length / 3;
  81965. var normal = p0.subtract(p1);
  81966. normal.normalize();
  81967. // Positions
  81968. this._linesPositions.push(p0.x);
  81969. this._linesPositions.push(p0.y);
  81970. this._linesPositions.push(p0.z);
  81971. this._linesPositions.push(p0.x);
  81972. this._linesPositions.push(p0.y);
  81973. this._linesPositions.push(p0.z);
  81974. this._linesPositions.push(p1.x);
  81975. this._linesPositions.push(p1.y);
  81976. this._linesPositions.push(p1.z);
  81977. this._linesPositions.push(p1.x);
  81978. this._linesPositions.push(p1.y);
  81979. this._linesPositions.push(p1.z);
  81980. // Normals
  81981. this._linesNormals.push(p1.x);
  81982. this._linesNormals.push(p1.y);
  81983. this._linesNormals.push(p1.z);
  81984. this._linesNormals.push(-1);
  81985. this._linesNormals.push(p1.x);
  81986. this._linesNormals.push(p1.y);
  81987. this._linesNormals.push(p1.z);
  81988. this._linesNormals.push(1);
  81989. this._linesNormals.push(p0.x);
  81990. this._linesNormals.push(p0.y);
  81991. this._linesNormals.push(p0.z);
  81992. this._linesNormals.push(-1);
  81993. this._linesNormals.push(p0.x);
  81994. this._linesNormals.push(p0.y);
  81995. this._linesNormals.push(p0.z);
  81996. this._linesNormals.push(1);
  81997. // Indices
  81998. this._linesIndices.push(offset);
  81999. this._linesIndices.push(offset + 1);
  82000. this._linesIndices.push(offset + 2);
  82001. this._linesIndices.push(offset);
  82002. this._linesIndices.push(offset + 2);
  82003. this._linesIndices.push(offset + 3);
  82004. }
  82005. };
  82006. EdgesRenderer.prototype._generateEdgesLines = function () {
  82007. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  82008. var indices = this._source.getIndices();
  82009. if (!indices || !positions) {
  82010. return;
  82011. }
  82012. // First let's find adjacencies
  82013. var adjacencies = new Array();
  82014. var faceNormals = new Array();
  82015. var index;
  82016. var faceAdjacencies;
  82017. // Prepare faces
  82018. for (index = 0; index < indices.length; index += 3) {
  82019. faceAdjacencies = new FaceAdjacencies();
  82020. var p0Index = indices[index];
  82021. var p1Index = indices[index + 1];
  82022. var p2Index = indices[index + 2];
  82023. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  82024. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  82025. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  82026. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  82027. faceNormal.normalize();
  82028. faceNormals.push(faceNormal);
  82029. adjacencies.push(faceAdjacencies);
  82030. }
  82031. // Scan
  82032. for (index = 0; index < adjacencies.length; index++) {
  82033. faceAdjacencies = adjacencies[index];
  82034. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  82035. var otherFaceAdjacencies = adjacencies[otherIndex];
  82036. if (faceAdjacencies.edgesConnectedCount === 3) {
  82037. break;
  82038. }
  82039. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  82040. continue;
  82041. }
  82042. var otherP0 = indices[otherIndex * 3];
  82043. var otherP1 = indices[otherIndex * 3 + 1];
  82044. var otherP2 = indices[otherIndex * 3 + 2];
  82045. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  82046. var otherEdgeIndex = 0;
  82047. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  82048. continue;
  82049. }
  82050. switch (edgeIndex) {
  82051. case 0:
  82052. if (this._checkVerticesInsteadOfIndices) {
  82053. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  82054. }
  82055. else {
  82056. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  82057. }
  82058. break;
  82059. case 1:
  82060. if (this._checkVerticesInsteadOfIndices) {
  82061. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  82062. }
  82063. else {
  82064. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  82065. }
  82066. break;
  82067. case 2:
  82068. if (this._checkVerticesInsteadOfIndices) {
  82069. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  82070. }
  82071. else {
  82072. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  82073. }
  82074. break;
  82075. }
  82076. if (otherEdgeIndex === -1) {
  82077. continue;
  82078. }
  82079. faceAdjacencies.edges[edgeIndex] = otherIndex;
  82080. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  82081. faceAdjacencies.edgesConnectedCount++;
  82082. otherFaceAdjacencies.edgesConnectedCount++;
  82083. if (faceAdjacencies.edgesConnectedCount === 3) {
  82084. break;
  82085. }
  82086. }
  82087. }
  82088. }
  82089. // Create lines
  82090. for (index = 0; index < adjacencies.length; index++) {
  82091. // 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
  82092. var current = adjacencies[index];
  82093. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  82094. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  82095. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  82096. }
  82097. // Merge into a single mesh
  82098. var engine = this._source.getScene().getEngine();
  82099. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  82100. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  82101. this._ib = engine.createIndexBuffer(this._linesIndices);
  82102. this._indicesCount = this._linesIndices.length;
  82103. };
  82104. EdgesRenderer.prototype.render = function () {
  82105. var scene = this._source.getScene();
  82106. if (!this._lineShader.isReady() || !scene.activeCamera) {
  82107. return;
  82108. }
  82109. var engine = scene.getEngine();
  82110. this._lineShader._preBind();
  82111. // VBOs
  82112. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  82113. scene.resetCachedMaterial();
  82114. this._lineShader.setColor4("color", this._source.edgesColor);
  82115. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  82116. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  82117. }
  82118. else {
  82119. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  82120. }
  82121. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  82122. this._lineShader.bind(this._source.getWorldMatrix());
  82123. // Draw order
  82124. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  82125. this._lineShader.unbind();
  82126. engine.setDepthWrite(true);
  82127. };
  82128. return EdgesRenderer;
  82129. }());
  82130. BABYLON.EdgesRenderer = EdgesRenderer;
  82131. })(BABYLON || (BABYLON = {}));
  82132. //# sourceMappingURL=babylon.edgesRenderer.js.map
  82133. var __assign = (this && this.__assign) || Object.assign || function(t) {
  82134. for (var s, i = 1, n = arguments.length; i < n; i++) {
  82135. s = arguments[i];
  82136. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  82137. t[p] = s[p];
  82138. }
  82139. return t;
  82140. };
  82141. var BABYLON;
  82142. (function (BABYLON) {
  82143. /**
  82144. * The effect layer Helps adding post process effect blended with the main pass.
  82145. *
  82146. * This can be for instance use to generate glow or higlight effects on the scene.
  82147. *
  82148. * The effect layer class can not be used directly and is intented to inherited from to be
  82149. * customized per effects.
  82150. */
  82151. var EffectLayer = /** @class */ (function () {
  82152. /**
  82153. * Instantiates a new effect Layer and references it in the scene.
  82154. * @param name The name of the layer
  82155. * @param scene The scene to use the layer in
  82156. */
  82157. function EffectLayer(
  82158. /** The Friendly of the effect in the scene */
  82159. name, scene) {
  82160. this.name = name;
  82161. this._vertexBuffers = {};
  82162. this._maxSize = 0;
  82163. this._mainTextureDesiredSize = { width: 0, height: 0 };
  82164. this._shouldRender = true;
  82165. this._postProcesses = [];
  82166. this._textures = [];
  82167. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  82168. /**
  82169. * The clear color of the texture used to generate the glow map.
  82170. */
  82171. this.neutralColor = new BABYLON.Color4();
  82172. /**
  82173. * Specifies wether the highlight layer is enabled or not.
  82174. */
  82175. this.isEnabled = true;
  82176. /**
  82177. * An event triggered when the effect layer has been disposed.
  82178. */
  82179. this.onDisposeObservable = new BABYLON.Observable();
  82180. /**
  82181. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  82182. */
  82183. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  82184. /**
  82185. * An event triggered when the generated texture is being merged in the scene.
  82186. */
  82187. this.onBeforeComposeObservable = new BABYLON.Observable();
  82188. /**
  82189. * An event triggered when the generated texture has been merged in the scene.
  82190. */
  82191. this.onAfterComposeObservable = new BABYLON.Observable();
  82192. /**
  82193. * An event triggered when the efffect layer changes its size.
  82194. */
  82195. this.onSizeChangedObservable = new BABYLON.Observable();
  82196. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  82197. this._engine = scene.getEngine();
  82198. this._maxSize = this._engine.getCaps().maxTextureSize;
  82199. this._scene.effectLayers.push(this);
  82200. // Generate Buffers
  82201. this._generateIndexBuffer();
  82202. this._genrateVertexBuffer();
  82203. }
  82204. Object.defineProperty(EffectLayer.prototype, "camera", {
  82205. /**
  82206. * Gets the camera attached to the layer.
  82207. */
  82208. get: function () {
  82209. return this._effectLayerOptions.camera;
  82210. },
  82211. enumerable: true,
  82212. configurable: true
  82213. });
  82214. /**
  82215. * Initializes the effect layer with the required options.
  82216. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  82217. */
  82218. EffectLayer.prototype._init = function (options) {
  82219. // Adapt options
  82220. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  82221. this._setMainTextureSize();
  82222. this._createMainTexture();
  82223. this._createTextureAndPostProcesses();
  82224. this._mergeEffect = this._createMergeEffect();
  82225. };
  82226. /**
  82227. * Generates the index buffer of the full screen quad blending to the main canvas.
  82228. */
  82229. EffectLayer.prototype._generateIndexBuffer = function () {
  82230. // Indices
  82231. var indices = [];
  82232. indices.push(0);
  82233. indices.push(1);
  82234. indices.push(2);
  82235. indices.push(0);
  82236. indices.push(2);
  82237. indices.push(3);
  82238. this._indexBuffer = this._engine.createIndexBuffer(indices);
  82239. };
  82240. /**
  82241. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  82242. */
  82243. EffectLayer.prototype._genrateVertexBuffer = function () {
  82244. // VBO
  82245. var vertices = [];
  82246. vertices.push(1, 1);
  82247. vertices.push(-1, 1);
  82248. vertices.push(-1, -1);
  82249. vertices.push(1, -1);
  82250. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  82251. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  82252. };
  82253. /**
  82254. * Sets the main texture desired size which is the closest power of two
  82255. * of the engine canvas size.
  82256. */
  82257. EffectLayer.prototype._setMainTextureSize = function () {
  82258. if (this._effectLayerOptions.mainTextureFixedSize) {
  82259. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  82260. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  82261. }
  82262. else {
  82263. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  82264. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  82265. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  82266. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  82267. }
  82268. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  82269. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  82270. };
  82271. /**
  82272. * Creates the main texture for the effect layer.
  82273. */
  82274. EffectLayer.prototype._createMainTexture = function () {
  82275. var _this = this;
  82276. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  82277. width: this._mainTextureDesiredSize.width,
  82278. height: this._mainTextureDesiredSize.height
  82279. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  82280. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  82281. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  82282. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  82283. this._mainTexture.anisotropicFilteringLevel = 1;
  82284. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  82285. this._mainTexture.renderParticles = false;
  82286. this._mainTexture.renderList = null;
  82287. this._mainTexture.ignoreCameraViewport = true;
  82288. // Custom render function
  82289. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  82290. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  82291. var index;
  82292. var engine = _this._scene.getEngine();
  82293. if (depthOnlySubMeshes.length) {
  82294. engine.setColorWrite(false);
  82295. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  82296. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  82297. }
  82298. engine.setColorWrite(true);
  82299. }
  82300. for (index = 0; index < opaqueSubMeshes.length; index++) {
  82301. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  82302. }
  82303. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  82304. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  82305. }
  82306. for (index = 0; index < transparentSubMeshes.length; index++) {
  82307. _this._renderSubMesh(transparentSubMeshes.data[index]);
  82308. }
  82309. };
  82310. this._mainTexture.onClearObservable.add(function (engine) {
  82311. engine.clear(_this.neutralColor, true, true, true);
  82312. });
  82313. };
  82314. /**
  82315. * Checks for the readiness of the element composing the layer.
  82316. * @param subMesh the mesh to check for
  82317. * @param useInstances specify wether or not to use instances to render the mesh
  82318. * @param emissiveTexture the associated emissive texture used to generate the glow
  82319. * @return true if ready otherwise, false
  82320. */
  82321. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  82322. var material = subMesh.getMaterial();
  82323. if (!material) {
  82324. return false;
  82325. }
  82326. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  82327. return false;
  82328. }
  82329. var defines = [];
  82330. var attribs = [BABYLON.VertexBuffer.PositionKind];
  82331. var mesh = subMesh.getMesh();
  82332. var uv1 = false;
  82333. var uv2 = false;
  82334. // Alpha test
  82335. if (material && material.needAlphaTesting()) {
  82336. var alphaTexture = material.getAlphaTestTexture();
  82337. if (alphaTexture) {
  82338. defines.push("#define ALPHATEST");
  82339. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  82340. alphaTexture.coordinatesIndex === 1) {
  82341. defines.push("#define DIFFUSEUV2");
  82342. uv2 = true;
  82343. }
  82344. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  82345. defines.push("#define DIFFUSEUV1");
  82346. uv1 = true;
  82347. }
  82348. }
  82349. }
  82350. // Emissive
  82351. if (emissiveTexture) {
  82352. defines.push("#define EMISSIVE");
  82353. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  82354. emissiveTexture.coordinatesIndex === 1) {
  82355. defines.push("#define EMISSIVEUV2");
  82356. uv2 = true;
  82357. }
  82358. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  82359. defines.push("#define EMISSIVEUV1");
  82360. uv1 = true;
  82361. }
  82362. }
  82363. if (uv1) {
  82364. attribs.push(BABYLON.VertexBuffer.UVKind);
  82365. defines.push("#define UV1");
  82366. }
  82367. if (uv2) {
  82368. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  82369. defines.push("#define UV2");
  82370. }
  82371. // Bones
  82372. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  82373. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  82374. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  82375. if (mesh.numBoneInfluencers > 4) {
  82376. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  82377. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  82378. }
  82379. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  82380. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  82381. }
  82382. else {
  82383. defines.push("#define NUM_BONE_INFLUENCERS 0");
  82384. }
  82385. // Instances
  82386. if (useInstances) {
  82387. defines.push("#define INSTANCES");
  82388. attribs.push("world0");
  82389. attribs.push("world1");
  82390. attribs.push("world2");
  82391. attribs.push("world3");
  82392. }
  82393. // Get correct effect
  82394. var join = defines.join("\n");
  82395. if (this._cachedDefines !== join) {
  82396. this._cachedDefines = join;
  82397. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix"], ["diffuseSampler", "emissiveSampler"], join);
  82398. }
  82399. return this._effectLayerMapGenerationEffect.isReady();
  82400. };
  82401. /**
  82402. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  82403. */
  82404. EffectLayer.prototype.render = function () {
  82405. var currentEffect = this._mergeEffect;
  82406. // Check
  82407. if (!currentEffect.isReady())
  82408. return;
  82409. for (var i = 0; i < this._postProcesses.length; i++) {
  82410. if (!this._postProcesses[i].isReady()) {
  82411. return;
  82412. }
  82413. }
  82414. var engine = this._scene.getEngine();
  82415. this.onBeforeComposeObservable.notifyObservers(this);
  82416. // Render
  82417. engine.enableEffect(currentEffect);
  82418. engine.setState(false);
  82419. // VBOs
  82420. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  82421. // Cache
  82422. var previousAlphaMode = engine.getAlphaMode();
  82423. // Go Blend.
  82424. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  82425. // Blends the map on the main canvas.
  82426. this._internalRender(currentEffect);
  82427. // Restore Alpha
  82428. engine.setAlphaMode(previousAlphaMode);
  82429. this.onAfterComposeObservable.notifyObservers(this);
  82430. // Handle size changes.
  82431. var size = this._mainTexture.getSize();
  82432. this._setMainTextureSize();
  82433. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  82434. // Recreate RTT and post processes on size change.
  82435. this.onSizeChangedObservable.notifyObservers(this);
  82436. this._disposeTextureAndPostProcesses();
  82437. this._createMainTexture();
  82438. this._createTextureAndPostProcesses();
  82439. }
  82440. };
  82441. /**
  82442. * Determine if a given mesh will be used in the current effect.
  82443. * @param mesh mesh to test
  82444. * @returns true if the mesh will be used
  82445. */
  82446. EffectLayer.prototype.hasMesh = function (mesh) {
  82447. return true;
  82448. };
  82449. /**
  82450. * Returns true if the layer contains information to display, otherwise false.
  82451. * @returns true if the glow layer should be rendered
  82452. */
  82453. EffectLayer.prototype.shouldRender = function () {
  82454. return this.isEnabled && this._shouldRender;
  82455. };
  82456. /**
  82457. * Returns true if the mesh should render, otherwise false.
  82458. * @param mesh The mesh to render
  82459. * @returns true if it should render otherwise false
  82460. */
  82461. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  82462. return true;
  82463. };
  82464. /**
  82465. * Returns true if the mesh should render, otherwise false.
  82466. * @param mesh The mesh to render
  82467. * @returns true if it should render otherwise false
  82468. */
  82469. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  82470. return true;
  82471. };
  82472. /**
  82473. * Renders the submesh passed in parameter to the generation map.
  82474. */
  82475. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  82476. var _this = this;
  82477. if (!this.shouldRender()) {
  82478. return;
  82479. }
  82480. var material = subMesh.getMaterial();
  82481. var mesh = subMesh.getRenderingMesh();
  82482. var scene = this._scene;
  82483. var engine = scene.getEngine();
  82484. if (!material) {
  82485. return;
  82486. }
  82487. // Do not block in blend mode.
  82488. if (material.needAlphaBlendingForMesh(mesh)) {
  82489. return;
  82490. }
  82491. // Culling
  82492. engine.setState(material.backFaceCulling);
  82493. // Managing instances
  82494. var batch = mesh._getInstancesRenderList(subMesh._id);
  82495. if (batch.mustReturn) {
  82496. return;
  82497. }
  82498. // Early Exit per mesh
  82499. if (!this._shouldRenderMesh(mesh)) {
  82500. return;
  82501. }
  82502. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  82503. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  82504. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  82505. engine.enableEffect(this._effectLayerMapGenerationEffect);
  82506. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  82507. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  82508. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  82509. // Alpha test
  82510. if (material && material.needAlphaTesting()) {
  82511. var alphaTexture = material.getAlphaTestTexture();
  82512. if (alphaTexture) {
  82513. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  82514. var textureMatrix = alphaTexture.getTextureMatrix();
  82515. if (textureMatrix) {
  82516. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  82517. }
  82518. }
  82519. }
  82520. // Glow emissive only
  82521. if (this._emissiveTextureAndColor.texture) {
  82522. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  82523. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  82524. }
  82525. // Bones
  82526. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  82527. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  82528. }
  82529. // Draw
  82530. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  82531. }
  82532. else {
  82533. // Need to reset refresh rate of the shadowMap
  82534. this._mainTexture.resetRefreshCounter();
  82535. }
  82536. };
  82537. /**
  82538. * Rebuild the required buffers.
  82539. * @ignore Internal use only.
  82540. */
  82541. EffectLayer.prototype._rebuild = function () {
  82542. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  82543. if (vb) {
  82544. vb._rebuild();
  82545. }
  82546. this._generateIndexBuffer();
  82547. };
  82548. /**
  82549. * Dispose only the render target textures and post process.
  82550. */
  82551. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  82552. this._mainTexture.dispose();
  82553. for (var i = 0; i < this._postProcesses.length; i++) {
  82554. if (this._postProcesses[i]) {
  82555. this._postProcesses[i].dispose();
  82556. }
  82557. }
  82558. this._postProcesses = [];
  82559. for (var i = 0; i < this._textures.length; i++) {
  82560. if (this._textures[i]) {
  82561. this._textures[i].dispose();
  82562. }
  82563. }
  82564. this._textures = [];
  82565. };
  82566. /**
  82567. * Dispose the highlight layer and free resources.
  82568. */
  82569. EffectLayer.prototype.dispose = function () {
  82570. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  82571. if (vertexBuffer) {
  82572. vertexBuffer.dispose();
  82573. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  82574. }
  82575. if (this._indexBuffer) {
  82576. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  82577. this._indexBuffer = null;
  82578. }
  82579. // Clean textures and post processes
  82580. this._disposeTextureAndPostProcesses();
  82581. // Remove from scene
  82582. var index = this._scene.effectLayers.indexOf(this, 0);
  82583. if (index > -1) {
  82584. this._scene.effectLayers.splice(index, 1);
  82585. }
  82586. // Callback
  82587. this.onDisposeObservable.notifyObservers(this);
  82588. this.onDisposeObservable.clear();
  82589. this.onBeforeRenderMainTextureObservable.clear();
  82590. this.onBeforeComposeObservable.clear();
  82591. this.onAfterComposeObservable.clear();
  82592. this.onSizeChangedObservable.clear();
  82593. };
  82594. return EffectLayer;
  82595. }());
  82596. BABYLON.EffectLayer = EffectLayer;
  82597. })(BABYLON || (BABYLON = {}));
  82598. //# sourceMappingURL=babylon.effectLayer.js.map
  82599. var BABYLON;
  82600. (function (BABYLON) {
  82601. /**
  82602. * Special Glow Blur post process only blurring the alpha channel
  82603. * It enforces keeping the most luminous color in the color channel.
  82604. */
  82605. var GlowBlurPostProcess = /** @class */ (function (_super) {
  82606. __extends(GlowBlurPostProcess, _super);
  82607. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  82608. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  82609. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  82610. _this.direction = direction;
  82611. _this.kernel = kernel;
  82612. _this.onApplyObservable.add(function (effect) {
  82613. effect.setFloat2("screenSize", _this.width, _this.height);
  82614. effect.setVector2("direction", _this.direction);
  82615. effect.setFloat("blurWidth", _this.kernel);
  82616. });
  82617. return _this;
  82618. }
  82619. return GlowBlurPostProcess;
  82620. }(BABYLON.PostProcess));
  82621. /**
  82622. * The highlight layer Helps adding a glow effect around a mesh.
  82623. *
  82624. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  82625. * glowy meshes to your scene.
  82626. *
  82627. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  82628. */
  82629. var HighlightLayer = /** @class */ (function (_super) {
  82630. __extends(HighlightLayer, _super);
  82631. /**
  82632. * Instantiates a new highlight Layer and references it to the scene..
  82633. * @param name The name of the layer
  82634. * @param scene The scene to use the layer in
  82635. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  82636. */
  82637. function HighlightLayer(name, scene, options) {
  82638. var _this = _super.call(this, name, scene) || this;
  82639. _this.name = name;
  82640. /**
  82641. * Specifies whether or not the inner glow is ACTIVE in the layer.
  82642. */
  82643. _this.innerGlow = true;
  82644. /**
  82645. * Specifies whether or not the outer glow is ACTIVE in the layer.
  82646. */
  82647. _this.outerGlow = true;
  82648. /**
  82649. * An event triggered when the highlight layer is being blurred.
  82650. */
  82651. _this.onBeforeBlurObservable = new BABYLON.Observable();
  82652. /**
  82653. * An event triggered when the highlight layer has been blurred.
  82654. */
  82655. _this.onAfterBlurObservable = new BABYLON.Observable();
  82656. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  82657. _this._meshes = {};
  82658. _this._excludedMeshes = {};
  82659. _this.neutralColor = HighlightLayer.NeutralColor;
  82660. // Warn on stencil
  82661. if (!_this._engine.isStencilEnable) {
  82662. 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 }");
  82663. }
  82664. // Adapt options
  82665. _this._options = __assign({ mainTextureRatio: 0.5, blurTextureSizeRatio: 0.5, blurHorizontalSize: 1.0, blurVerticalSize: 1.0, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  82666. // Initialize the layer
  82667. _this._init({
  82668. alphaBlendingMode: _this._options.alphaBlendingMode,
  82669. camera: _this._options.camera,
  82670. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  82671. mainTextureRatio: _this._options.mainTextureRatio
  82672. });
  82673. return _this;
  82674. }
  82675. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  82676. /**
  82677. * Gets the horizontal size of the blur.
  82678. */
  82679. get: function () {
  82680. return this._horizontalBlurPostprocess.kernel;
  82681. },
  82682. /**
  82683. * Specifies the horizontal size of the blur.
  82684. */
  82685. set: function (value) {
  82686. this._horizontalBlurPostprocess.kernel = value;
  82687. },
  82688. enumerable: true,
  82689. configurable: true
  82690. });
  82691. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  82692. /**
  82693. * Gets the vertical size of the blur.
  82694. */
  82695. get: function () {
  82696. return this._verticalBlurPostprocess.kernel;
  82697. },
  82698. /**
  82699. * Specifies the vertical size of the blur.
  82700. */
  82701. set: function (value) {
  82702. this._verticalBlurPostprocess.kernel = value;
  82703. },
  82704. enumerable: true,
  82705. configurable: true
  82706. });
  82707. /**
  82708. * Get the effect name of the layer.
  82709. * @return The effect name
  82710. */
  82711. HighlightLayer.prototype.getEffectName = function () {
  82712. return HighlightLayer.EffectName;
  82713. };
  82714. /**
  82715. * Create the merge effect. This is the shader use to blit the information back
  82716. * to the main canvas at the end of the scene rendering.
  82717. */
  82718. HighlightLayer.prototype._createMergeEffect = function () {
  82719. // Effect
  82720. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  82721. };
  82722. /**
  82723. * Creates the render target textures and post processes used in the highlight layer.
  82724. */
  82725. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  82726. var _this = this;
  82727. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  82728. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  82729. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  82730. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  82731. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  82732. width: blurTextureWidth,
  82733. height: blurTextureHeight
  82734. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  82735. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  82736. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  82737. this._blurTexture.anisotropicFilteringLevel = 16;
  82738. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  82739. this._blurTexture.renderParticles = false;
  82740. this._blurTexture.ignoreCameraViewport = true;
  82741. this._textures = [this._blurTexture];
  82742. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  82743. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  82744. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  82745. effect.setTexture("textureSampler", _this._mainTexture);
  82746. });
  82747. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  82748. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  82749. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  82750. });
  82751. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  82752. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  82753. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  82754. });
  82755. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  82756. }
  82757. else {
  82758. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  82759. width: blurTextureWidth,
  82760. height: blurTextureHeight
  82761. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  82762. this._horizontalBlurPostprocess.width = blurTextureWidth;
  82763. this._horizontalBlurPostprocess.height = blurTextureHeight;
  82764. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  82765. effect.setTexture("textureSampler", _this._mainTexture);
  82766. });
  82767. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  82768. width: blurTextureWidth,
  82769. height: blurTextureHeight
  82770. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  82771. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  82772. }
  82773. this._mainTexture.onAfterUnbindObservable.add(function () {
  82774. _this.onBeforeBlurObservable.notifyObservers(_this);
  82775. var internalTexture = _this._blurTexture.getInternalTexture();
  82776. if (internalTexture) {
  82777. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  82778. }
  82779. _this.onAfterBlurObservable.notifyObservers(_this);
  82780. });
  82781. // Prevent autoClear.
  82782. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  82783. };
  82784. /**
  82785. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  82786. */
  82787. HighlightLayer.prototype.needStencil = function () {
  82788. return true;
  82789. };
  82790. /**
  82791. * Checks for the readiness of the element composing the layer.
  82792. * @param subMesh the mesh to check for
  82793. * @param useInstances specify wether or not to use instances to render the mesh
  82794. * @param emissiveTexture the associated emissive texture used to generate the glow
  82795. * @return true if ready otherwise, false
  82796. */
  82797. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  82798. var material = subMesh.getMaterial();
  82799. var mesh = subMesh.getRenderingMesh();
  82800. if (!material || !mesh || !this._meshes) {
  82801. return false;
  82802. }
  82803. var emissiveTexture = null;
  82804. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  82805. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  82806. emissiveTexture = material.emissiveTexture;
  82807. }
  82808. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  82809. };
  82810. /**
  82811. * Implementation specific of rendering the generating effect on the main canvas.
  82812. * @param effect The effect used to render through
  82813. */
  82814. HighlightLayer.prototype._internalRender = function (effect) {
  82815. // Texture
  82816. effect.setTexture("textureSampler", this._blurTexture);
  82817. // Cache
  82818. var engine = this._engine;
  82819. var previousStencilBuffer = engine.getStencilBuffer();
  82820. var previousStencilFunction = engine.getStencilFunction();
  82821. var previousStencilMask = engine.getStencilMask();
  82822. var previousStencilOperationPass = engine.getStencilOperationPass();
  82823. var previousStencilOperationFail = engine.getStencilOperationFail();
  82824. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  82825. // Stencil operations
  82826. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  82827. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  82828. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  82829. // Draw order
  82830. engine.setStencilMask(0x00);
  82831. engine.setStencilBuffer(true);
  82832. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  82833. // 2 passes inner outer
  82834. if (this.outerGlow) {
  82835. effect.setFloat("offset", 0);
  82836. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  82837. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  82838. }
  82839. if (this.innerGlow) {
  82840. effect.setFloat("offset", 1);
  82841. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  82842. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  82843. }
  82844. // Restore Cache
  82845. engine.setStencilFunction(previousStencilFunction);
  82846. engine.setStencilMask(previousStencilMask);
  82847. engine.setStencilBuffer(previousStencilBuffer);
  82848. engine.setStencilOperationPass(previousStencilOperationPass);
  82849. engine.setStencilOperationFail(previousStencilOperationFail);
  82850. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  82851. };
  82852. /**
  82853. * Returns true if the layer contains information to display, otherwise false.
  82854. */
  82855. HighlightLayer.prototype.shouldRender = function () {
  82856. if (_super.prototype.shouldRender.call(this)) {
  82857. return this._meshes ? true : false;
  82858. }
  82859. return false;
  82860. };
  82861. /**
  82862. * Returns true if the mesh should render, otherwise false.
  82863. * @param mesh The mesh to render
  82864. * @returns true if it should render otherwise false
  82865. */
  82866. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  82867. // Excluded Mesh
  82868. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  82869. return false;
  82870. }
  82871. ;
  82872. return true;
  82873. };
  82874. /**
  82875. * Sets the required values for both the emissive texture and and the main color.
  82876. */
  82877. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  82878. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  82879. if (highlightLayerMesh) {
  82880. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  82881. }
  82882. else {
  82883. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  82884. }
  82885. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  82886. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  82887. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  82888. }
  82889. else {
  82890. this._emissiveTextureAndColor.texture = null;
  82891. }
  82892. };
  82893. /**
  82894. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  82895. * @param mesh The mesh to exclude from the highlight layer
  82896. */
  82897. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  82898. if (!this._excludedMeshes) {
  82899. return;
  82900. }
  82901. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  82902. if (!meshExcluded) {
  82903. this._excludedMeshes[mesh.uniqueId] = {
  82904. mesh: mesh,
  82905. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  82906. mesh.getEngine().setStencilBuffer(false);
  82907. }),
  82908. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  82909. mesh.getEngine().setStencilBuffer(true);
  82910. }),
  82911. };
  82912. }
  82913. };
  82914. /**
  82915. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  82916. * @param mesh The mesh to highlight
  82917. */
  82918. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  82919. if (!this._excludedMeshes) {
  82920. return;
  82921. }
  82922. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  82923. if (meshExcluded) {
  82924. if (meshExcluded.beforeRender) {
  82925. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  82926. }
  82927. if (meshExcluded.afterRender) {
  82928. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  82929. }
  82930. }
  82931. this._excludedMeshes[mesh.uniqueId] = null;
  82932. };
  82933. /**
  82934. * Determine if a given mesh will be highlighted by the current HighlightLayer
  82935. * @param mesh mesh to test
  82936. * @returns true if the mesh will be highlighted by the current HighlightLayer
  82937. */
  82938. HighlightLayer.prototype.hasMesh = function (mesh) {
  82939. if (!this._meshes) {
  82940. return false;
  82941. }
  82942. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  82943. };
  82944. /**
  82945. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  82946. * @param mesh The mesh to highlight
  82947. * @param color The color of the highlight
  82948. * @param glowEmissiveOnly Extract the glow from the emissive texture
  82949. */
  82950. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  82951. var _this = this;
  82952. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  82953. if (!this._meshes) {
  82954. return;
  82955. }
  82956. var meshHighlight = this._meshes[mesh.uniqueId];
  82957. if (meshHighlight) {
  82958. meshHighlight.color = color;
  82959. }
  82960. else {
  82961. this._meshes[mesh.uniqueId] = {
  82962. mesh: mesh,
  82963. color: color,
  82964. // Lambda required for capture due to Observable this context
  82965. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  82966. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  82967. _this._defaultStencilReference(mesh);
  82968. }
  82969. else {
  82970. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  82971. }
  82972. }),
  82973. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  82974. glowEmissiveOnly: glowEmissiveOnly
  82975. };
  82976. }
  82977. this._shouldRender = true;
  82978. };
  82979. /**
  82980. * Remove a mesh from the highlight layer in order to make it stop glowing.
  82981. * @param mesh The mesh to highlight
  82982. */
  82983. HighlightLayer.prototype.removeMesh = function (mesh) {
  82984. if (!this._meshes) {
  82985. return;
  82986. }
  82987. var meshHighlight = this._meshes[mesh.uniqueId];
  82988. if (meshHighlight) {
  82989. if (meshHighlight.observerHighlight) {
  82990. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  82991. }
  82992. if (meshHighlight.observerDefault) {
  82993. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  82994. }
  82995. delete this._meshes[mesh.uniqueId];
  82996. }
  82997. this._shouldRender = false;
  82998. for (var meshHighlightToCheck in this._meshes) {
  82999. if (this._meshes[meshHighlightToCheck]) {
  83000. this._shouldRender = true;
  83001. break;
  83002. }
  83003. }
  83004. };
  83005. /**
  83006. * Force the stencil to the normal expected value for none glowing parts
  83007. */
  83008. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  83009. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  83010. };
  83011. /**
  83012. * Free any resources and references associated to a mesh.
  83013. * Internal use
  83014. * @param mesh The mesh to free.
  83015. */
  83016. HighlightLayer.prototype._disposeMesh = function (mesh) {
  83017. this.removeMesh(mesh);
  83018. this.removeExcludedMesh(mesh);
  83019. };
  83020. /**
  83021. * Dispose the highlight layer and free resources.
  83022. */
  83023. HighlightLayer.prototype.dispose = function () {
  83024. if (this._meshes) {
  83025. // Clean mesh references
  83026. for (var id in this._meshes) {
  83027. var meshHighlight = this._meshes[id];
  83028. if (meshHighlight && meshHighlight.mesh) {
  83029. if (meshHighlight.observerHighlight) {
  83030. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  83031. }
  83032. if (meshHighlight.observerDefault) {
  83033. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  83034. }
  83035. }
  83036. }
  83037. this._meshes = null;
  83038. }
  83039. if (this._excludedMeshes) {
  83040. for (var id in this._excludedMeshes) {
  83041. var meshHighlight = this._excludedMeshes[id];
  83042. if (meshHighlight) {
  83043. if (meshHighlight.beforeRender) {
  83044. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  83045. }
  83046. if (meshHighlight.afterRender) {
  83047. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  83048. }
  83049. }
  83050. }
  83051. this._excludedMeshes = null;
  83052. }
  83053. _super.prototype.dispose.call(this);
  83054. };
  83055. /**
  83056. * Effect Name of the highlight layer.
  83057. */
  83058. HighlightLayer.EffectName = "HighlightLayer";
  83059. /**
  83060. * The neutral color used during the preparation of the glow effect.
  83061. * This is black by default as the blend operation is a blend operation.
  83062. */
  83063. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  83064. /**
  83065. * Stencil value used for glowing meshes.
  83066. */
  83067. HighlightLayer.GlowingMeshStencilReference = 0x02;
  83068. /**
  83069. * Stencil value used for the other meshes in the scene.
  83070. */
  83071. HighlightLayer.NormalMeshStencilReference = 0x01;
  83072. return HighlightLayer;
  83073. }(BABYLON.EffectLayer));
  83074. BABYLON.HighlightLayer = HighlightLayer;
  83075. })(BABYLON || (BABYLON = {}));
  83076. //# sourceMappingURL=babylon.highlightLayer.js.map
  83077. var BABYLON;
  83078. (function (BABYLON) {
  83079. /**
  83080. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  83081. *
  83082. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  83083. * glowy meshes to your scene.
  83084. *
  83085. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  83086. */
  83087. var GlowLayer = /** @class */ (function (_super) {
  83088. __extends(GlowLayer, _super);
  83089. /**
  83090. * Instantiates a new glow Layer and references it to the scene.
  83091. * @param name The name of the layer
  83092. * @param scene The scene to use the layer in
  83093. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  83094. */
  83095. function GlowLayer(name, scene, options) {
  83096. var _this = _super.call(this, name, scene) || this;
  83097. _this.name = name;
  83098. _this._intensity = 1.0;
  83099. _this._includedOnlyMeshes = [];
  83100. _this._excludedMeshes = [];
  83101. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  83102. // Adapt options
  83103. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1 }, options);
  83104. // Initialize the layer
  83105. _this._init({
  83106. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  83107. camera: _this._options.camera,
  83108. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  83109. mainTextureRatio: _this._options.mainTextureRatio
  83110. });
  83111. return _this;
  83112. }
  83113. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  83114. /**
  83115. * Gets the kernel size of the blur.
  83116. */
  83117. get: function () {
  83118. return this._horizontalBlurPostprocess1.kernel;
  83119. },
  83120. /**
  83121. * Sets the kernel size of the blur.
  83122. */
  83123. set: function (value) {
  83124. this._horizontalBlurPostprocess1.kernel = value;
  83125. this._verticalBlurPostprocess1.kernel = value;
  83126. this._horizontalBlurPostprocess2.kernel = value;
  83127. this._verticalBlurPostprocess2.kernel = value;
  83128. },
  83129. enumerable: true,
  83130. configurable: true
  83131. });
  83132. Object.defineProperty(GlowLayer.prototype, "intensity", {
  83133. /**
  83134. * Gets the glow intensity.
  83135. */
  83136. get: function () {
  83137. return this._intensity;
  83138. },
  83139. /**
  83140. * Sets the glow intensity.
  83141. */
  83142. set: function (value) {
  83143. this._intensity = value;
  83144. },
  83145. enumerable: true,
  83146. configurable: true
  83147. });
  83148. /**
  83149. * Get the effect name of the layer.
  83150. * @return The effect name
  83151. */
  83152. GlowLayer.prototype.getEffectName = function () {
  83153. return GlowLayer.EffectName;
  83154. };
  83155. /**
  83156. * Create the merge effect. This is the shader use to blit the information back
  83157. * to the main canvas at the end of the scene rendering.
  83158. */
  83159. GlowLayer.prototype._createMergeEffect = function () {
  83160. // Effect
  83161. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  83162. };
  83163. /**
  83164. * Creates the render target textures and post processes used in the glow layer.
  83165. */
  83166. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  83167. var _this = this;
  83168. var blurTextureWidth = this._mainTextureDesiredSize.width;
  83169. var blurTextureHeight = this._mainTextureDesiredSize.height;
  83170. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  83171. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  83172. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  83173. width: blurTextureWidth,
  83174. height: blurTextureHeight
  83175. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  83176. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  83177. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  83178. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  83179. this._blurTexture1.renderParticles = false;
  83180. this._blurTexture1.ignoreCameraViewport = true;
  83181. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  83182. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  83183. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  83184. width: blurTextureWidth2,
  83185. height: blurTextureHeight2
  83186. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  83187. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  83188. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  83189. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  83190. this._blurTexture2.renderParticles = false;
  83191. this._blurTexture2.ignoreCameraViewport = true;
  83192. this._textures = [this._blurTexture1, this._blurTexture2];
  83193. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  83194. width: blurTextureWidth,
  83195. height: blurTextureHeight
  83196. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  83197. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  83198. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  83199. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  83200. effect.setTexture("textureSampler", _this._mainTexture);
  83201. });
  83202. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  83203. width: blurTextureWidth,
  83204. height: blurTextureHeight
  83205. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  83206. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  83207. width: blurTextureWidth2,
  83208. height: blurTextureHeight2
  83209. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  83210. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  83211. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  83212. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  83213. effect.setTexture("textureSampler", _this._blurTexture1);
  83214. });
  83215. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  83216. width: blurTextureWidth2,
  83217. height: blurTextureHeight2
  83218. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  83219. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  83220. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  83221. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  83222. this._mainTexture.samples = this._options.mainTextureSamples;
  83223. this._mainTexture.onAfterUnbindObservable.add(function () {
  83224. var internalTexture = _this._blurTexture1.getInternalTexture();
  83225. if (internalTexture) {
  83226. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  83227. internalTexture = _this._blurTexture2.getInternalTexture();
  83228. if (internalTexture) {
  83229. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  83230. }
  83231. }
  83232. });
  83233. // Prevent autoClear.
  83234. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  83235. };
  83236. /**
  83237. * Checks for the readiness of the element composing the layer.
  83238. * @param subMesh the mesh to check for
  83239. * @param useInstances specify wether or not to use instances to render the mesh
  83240. * @param emissiveTexture the associated emissive texture used to generate the glow
  83241. * @return true if ready otherwise, false
  83242. */
  83243. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  83244. var material = subMesh.getMaterial();
  83245. var mesh = subMesh.getRenderingMesh();
  83246. if (!material || !mesh) {
  83247. return false;
  83248. }
  83249. var emissiveTexture = material.emissiveTexture;
  83250. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  83251. };
  83252. /**
  83253. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  83254. */
  83255. GlowLayer.prototype.needStencil = function () {
  83256. return false;
  83257. };
  83258. /**
  83259. * Implementation specific of rendering the generating effect on the main canvas.
  83260. * @param effect The effect used to render through
  83261. */
  83262. GlowLayer.prototype._internalRender = function (effect) {
  83263. // Texture
  83264. effect.setTexture("textureSampler", this._blurTexture1);
  83265. effect.setTexture("textureSampler2", this._blurTexture2);
  83266. effect.setFloat("offset", this._intensity);
  83267. // Cache
  83268. var engine = this._engine;
  83269. var previousStencilBuffer = engine.getStencilBuffer();
  83270. // Draw order
  83271. engine.setStencilBuffer(false);
  83272. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  83273. // Draw order
  83274. engine.setStencilBuffer(previousStencilBuffer);
  83275. };
  83276. /**
  83277. * Sets the required values for both the emissive texture and and the main color.
  83278. */
  83279. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  83280. var textureLevel = 1.0;
  83281. if (this.customEmissiveTextureSelector) {
  83282. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  83283. }
  83284. else {
  83285. if (material) {
  83286. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  83287. if (this._emissiveTextureAndColor.texture) {
  83288. textureLevel = this._emissiveTextureAndColor.texture.level;
  83289. }
  83290. }
  83291. else {
  83292. this._emissiveTextureAndColor.texture = null;
  83293. }
  83294. }
  83295. if (this.customEmissiveColorSelector) {
  83296. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  83297. }
  83298. else {
  83299. if (material.emissiveColor) {
  83300. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  83301. }
  83302. else {
  83303. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  83304. }
  83305. }
  83306. };
  83307. /**
  83308. * Returns true if the mesh should render, otherwise false.
  83309. * @param mesh The mesh to render
  83310. * @returns true if it should render otherwise false
  83311. */
  83312. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  83313. return this.hasMesh(mesh);
  83314. };
  83315. /**
  83316. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  83317. * @param mesh The mesh to exclude from the glow layer
  83318. */
  83319. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  83320. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  83321. this._excludedMeshes.push(mesh.uniqueId);
  83322. }
  83323. };
  83324. /**
  83325. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  83326. * @param mesh The mesh to remove
  83327. */
  83328. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  83329. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  83330. if (index !== -1) {
  83331. this._excludedMeshes.splice(index, 1);
  83332. }
  83333. };
  83334. /**
  83335. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  83336. * @param mesh The mesh to include in the glow layer
  83337. */
  83338. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  83339. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  83340. this._includedOnlyMeshes.push(mesh.uniqueId);
  83341. }
  83342. };
  83343. /**
  83344. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  83345. * @param mesh The mesh to remove
  83346. */
  83347. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  83348. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  83349. if (index !== -1) {
  83350. this._includedOnlyMeshes.splice(index, 1);
  83351. }
  83352. };
  83353. /**
  83354. * Determine if a given mesh will be used in the glow layer
  83355. * @param mesh The mesh to test
  83356. * @returns true if the mesh will be highlighted by the current glow layer
  83357. */
  83358. GlowLayer.prototype.hasMesh = function (mesh) {
  83359. // Included Mesh
  83360. if (this._includedOnlyMeshes.length) {
  83361. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  83362. }
  83363. ;
  83364. // Excluded Mesh
  83365. if (this._excludedMeshes.length) {
  83366. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  83367. }
  83368. ;
  83369. return true;
  83370. };
  83371. /**
  83372. * Free any resources and references associated to a mesh.
  83373. * Internal use
  83374. * @param mesh The mesh to free.
  83375. */
  83376. GlowLayer.prototype._disposeMesh = function (mesh) {
  83377. this.removeIncludedOnlyMesh(mesh);
  83378. this.removeExcludedMesh(mesh);
  83379. };
  83380. /**
  83381. * Effect Name of the layer.
  83382. */
  83383. GlowLayer.EffectName = "GlowLayer";
  83384. /**
  83385. * The default blur kernel size used for the glow.
  83386. */
  83387. GlowLayer.DefaultBlurKernelSize = 32;
  83388. /**
  83389. * The default texture size ratio used for the glow.
  83390. */
  83391. GlowLayer.DefaultTextureRatio = 0.5;
  83392. return GlowLayer;
  83393. }(BABYLON.EffectLayer));
  83394. BABYLON.GlowLayer = GlowLayer;
  83395. })(BABYLON || (BABYLON = {}));
  83396. //# sourceMappingURL=babylon.glowLayer.js.map
  83397. var BABYLON;
  83398. (function (BABYLON) {
  83399. /**
  83400. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  83401. */
  83402. var AssetTaskState;
  83403. (function (AssetTaskState) {
  83404. /**
  83405. * Initialization
  83406. */
  83407. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  83408. /**
  83409. * Running
  83410. */
  83411. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  83412. /**
  83413. * Done
  83414. */
  83415. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  83416. /**
  83417. * Error
  83418. */
  83419. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  83420. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  83421. /**
  83422. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  83423. */
  83424. var AbstractAssetTask = /** @class */ (function () {
  83425. /**
  83426. * Creates a new {BABYLON.AssetsManager}
  83427. * @param name defines the name of the task
  83428. */
  83429. function AbstractAssetTask(
  83430. /**
  83431. * Task name
  83432. */ name) {
  83433. this.name = name;
  83434. this._isCompleted = false;
  83435. this._taskState = AssetTaskState.INIT;
  83436. }
  83437. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  83438. /**
  83439. * Get if the task is completed
  83440. */
  83441. get: function () {
  83442. return this._isCompleted;
  83443. },
  83444. enumerable: true,
  83445. configurable: true
  83446. });
  83447. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  83448. /**
  83449. * Gets the current state of the task
  83450. */
  83451. get: function () {
  83452. return this._taskState;
  83453. },
  83454. enumerable: true,
  83455. configurable: true
  83456. });
  83457. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  83458. /**
  83459. * Gets the current error object (if task is in error)
  83460. */
  83461. get: function () {
  83462. return this._errorObject;
  83463. },
  83464. enumerable: true,
  83465. configurable: true
  83466. });
  83467. /**
  83468. * Internal only
  83469. * @ignore
  83470. */
  83471. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  83472. if (this._errorObject) {
  83473. return;
  83474. }
  83475. this._errorObject = {
  83476. message: message,
  83477. exception: exception
  83478. };
  83479. };
  83480. /**
  83481. * Execute the current task
  83482. * @param scene defines the scene where you want your assets to be loaded
  83483. * @param onSuccess is a callback called when the task is successfully executed
  83484. * @param onError is a callback called if an error occurs
  83485. */
  83486. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  83487. var _this = this;
  83488. this._taskState = AssetTaskState.RUNNING;
  83489. this.runTask(scene, function () {
  83490. _this.onDoneCallback(onSuccess, onError);
  83491. }, function (msg, exception) {
  83492. _this.onErrorCallback(onError, msg, exception);
  83493. });
  83494. };
  83495. /**
  83496. * Execute the current task
  83497. * @param scene defines the scene where you want your assets to be loaded
  83498. * @param onSuccess is a callback called when the task is successfully executed
  83499. * @param onError is a callback called if an error occurs
  83500. */
  83501. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  83502. throw new Error("runTask is not implemented");
  83503. };
  83504. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  83505. this._taskState = AssetTaskState.ERROR;
  83506. this._errorObject = {
  83507. message: message,
  83508. exception: exception
  83509. };
  83510. if (this.onError) {
  83511. this.onError(this, message, exception);
  83512. }
  83513. onError();
  83514. };
  83515. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  83516. try {
  83517. this._taskState = AssetTaskState.DONE;
  83518. this._isCompleted = true;
  83519. if (this.onSuccess) {
  83520. this.onSuccess(this);
  83521. }
  83522. onSuccess();
  83523. }
  83524. catch (e) {
  83525. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  83526. }
  83527. };
  83528. return AbstractAssetTask;
  83529. }());
  83530. BABYLON.AbstractAssetTask = AbstractAssetTask;
  83531. /**
  83532. * Class used to share progress information about assets loading
  83533. */
  83534. var AssetsProgressEvent = /** @class */ (function () {
  83535. /**
  83536. * Creates a {BABYLON.AssetsProgressEvent}
  83537. * @param remainingCount defines the number of remaining tasks to process
  83538. * @param totalCount defines the total number of tasks
  83539. * @param task defines the task that was just processed
  83540. */
  83541. function AssetsProgressEvent(remainingCount, totalCount, task) {
  83542. this.remainingCount = remainingCount;
  83543. this.totalCount = totalCount;
  83544. this.task = task;
  83545. }
  83546. return AssetsProgressEvent;
  83547. }());
  83548. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  83549. /**
  83550. * Define a task used by {BABYLON.AssetsManager} to load meshes
  83551. */
  83552. var MeshAssetTask = /** @class */ (function (_super) {
  83553. __extends(MeshAssetTask, _super);
  83554. /**
  83555. * Creates a new {BABYLON.MeshAssetTask}
  83556. * @param name defines the name of the task
  83557. * @param meshesNames defines the list of mesh's names you want to load
  83558. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  83559. * @param sceneFilename defines the filename of the scene to load from
  83560. */
  83561. function MeshAssetTask(
  83562. /**
  83563. * Defines the name of the task
  83564. */
  83565. name,
  83566. /**
  83567. * Defines the list of mesh's names you want to load
  83568. */
  83569. meshesNames,
  83570. /**
  83571. * Defines the root url to use as a base to load your meshes and associated resources
  83572. */
  83573. rootUrl,
  83574. /**
  83575. * Defines the filename of the scene to load from
  83576. */
  83577. sceneFilename) {
  83578. var _this = _super.call(this, name) || this;
  83579. _this.name = name;
  83580. _this.meshesNames = meshesNames;
  83581. _this.rootUrl = rootUrl;
  83582. _this.sceneFilename = sceneFilename;
  83583. return _this;
  83584. }
  83585. /**
  83586. * Execute the current task
  83587. * @param scene defines the scene where you want your assets to be loaded
  83588. * @param onSuccess is a callback called when the task is successfully executed
  83589. * @param onError is a callback called if an error occurs
  83590. */
  83591. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  83592. var _this = this;
  83593. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  83594. _this.loadedMeshes = meshes;
  83595. _this.loadedParticleSystems = particleSystems;
  83596. _this.loadedSkeletons = skeletons;
  83597. onSuccess();
  83598. }, null, function (scene, message, exception) {
  83599. onError(message, exception);
  83600. });
  83601. };
  83602. return MeshAssetTask;
  83603. }(AbstractAssetTask));
  83604. BABYLON.MeshAssetTask = MeshAssetTask;
  83605. /**
  83606. * Define a task used by {BABYLON.AssetsManager} to load text content
  83607. */
  83608. var TextFileAssetTask = /** @class */ (function (_super) {
  83609. __extends(TextFileAssetTask, _super);
  83610. /**
  83611. * Creates a new TextFileAssetTask object
  83612. * @param name defines the name of the task
  83613. * @param url defines the location of the file to load
  83614. */
  83615. function TextFileAssetTask(
  83616. /**
  83617. * Defines the name of the task
  83618. */
  83619. name,
  83620. /**
  83621. * Defines the location of the file to load
  83622. */
  83623. url) {
  83624. var _this = _super.call(this, name) || this;
  83625. _this.name = name;
  83626. _this.url = url;
  83627. return _this;
  83628. }
  83629. /**
  83630. * Execute the current task
  83631. * @param scene defines the scene where you want your assets to be loaded
  83632. * @param onSuccess is a callback called when the task is successfully executed
  83633. * @param onError is a callback called if an error occurs
  83634. */
  83635. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  83636. var _this = this;
  83637. scene._loadFile(this.url, function (data) {
  83638. _this.text = data;
  83639. onSuccess();
  83640. }, undefined, false, false, function (request, exception) {
  83641. if (request) {
  83642. onError(request.status + " " + request.statusText, exception);
  83643. }
  83644. });
  83645. };
  83646. return TextFileAssetTask;
  83647. }(AbstractAssetTask));
  83648. BABYLON.TextFileAssetTask = TextFileAssetTask;
  83649. /**
  83650. * Define a task used by {BABYLON.AssetsManager} to load binary data
  83651. */
  83652. var BinaryFileAssetTask = /** @class */ (function (_super) {
  83653. __extends(BinaryFileAssetTask, _super);
  83654. /**
  83655. * Creates a new BinaryFileAssetTask object
  83656. * @param name defines the name of the new task
  83657. * @param url defines the location of the file to load
  83658. */
  83659. function BinaryFileAssetTask(
  83660. /**
  83661. * Defines the name of the task
  83662. */
  83663. name,
  83664. /**
  83665. * Defines the location of the file to load
  83666. */
  83667. url) {
  83668. var _this = _super.call(this, name) || this;
  83669. _this.name = name;
  83670. _this.url = url;
  83671. return _this;
  83672. }
  83673. /**
  83674. * Execute the current task
  83675. * @param scene defines the scene where you want your assets to be loaded
  83676. * @param onSuccess is a callback called when the task is successfully executed
  83677. * @param onError is a callback called if an error occurs
  83678. */
  83679. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  83680. var _this = this;
  83681. scene._loadFile(this.url, function (data) {
  83682. _this.data = data;
  83683. onSuccess();
  83684. }, undefined, true, true, function (request, exception) {
  83685. if (request) {
  83686. onError(request.status + " " + request.statusText, exception);
  83687. }
  83688. });
  83689. };
  83690. return BinaryFileAssetTask;
  83691. }(AbstractAssetTask));
  83692. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  83693. /**
  83694. * Define a task used by {BABYLON.AssetsManager} to load images
  83695. */
  83696. var ImageAssetTask = /** @class */ (function (_super) {
  83697. __extends(ImageAssetTask, _super);
  83698. /**
  83699. * Creates a new ImageAssetTask
  83700. * @param name defines the name of the task
  83701. * @param url defines the location of the image to load
  83702. */
  83703. function ImageAssetTask(
  83704. /**
  83705. * Defines the name of the task
  83706. */
  83707. name,
  83708. /**
  83709. * Defines the location of the image to load
  83710. */
  83711. url) {
  83712. var _this = _super.call(this, name) || this;
  83713. _this.name = name;
  83714. _this.url = url;
  83715. return _this;
  83716. }
  83717. /**
  83718. * Execute the current task
  83719. * @param scene defines the scene where you want your assets to be loaded
  83720. * @param onSuccess is a callback called when the task is successfully executed
  83721. * @param onError is a callback called if an error occurs
  83722. */
  83723. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  83724. var _this = this;
  83725. var img = new Image();
  83726. BABYLON.Tools.SetCorsBehavior(this.url, img);
  83727. img.onload = function () {
  83728. _this.image = img;
  83729. onSuccess();
  83730. };
  83731. img.onerror = function (err) {
  83732. onError("Error loading image", err);
  83733. };
  83734. img.src = this.url;
  83735. };
  83736. return ImageAssetTask;
  83737. }(AbstractAssetTask));
  83738. BABYLON.ImageAssetTask = ImageAssetTask;
  83739. /**
  83740. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  83741. */
  83742. var TextureAssetTask = /** @class */ (function (_super) {
  83743. __extends(TextureAssetTask, _super);
  83744. /**
  83745. * Creates a new TextureAssetTask object
  83746. * @param name defines the name of the task
  83747. * @param url defines the location of the file to load
  83748. * @param noMipmap defines if mipmap should not be generated (default is false)
  83749. * @param invertY defines if texture must be inverted on Y axis (default is false)
  83750. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  83751. */
  83752. function TextureAssetTask(
  83753. /**
  83754. * Defines the name of the task
  83755. */
  83756. name,
  83757. /**
  83758. * Defines the location of the file to load
  83759. */
  83760. url,
  83761. /**
  83762. * Defines if mipmap should not be generated (default is false)
  83763. */
  83764. noMipmap,
  83765. /**
  83766. * Defines if texture must be inverted on Y axis (default is false)
  83767. */
  83768. invertY,
  83769. /**
  83770. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  83771. */
  83772. samplingMode) {
  83773. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  83774. var _this = _super.call(this, name) || this;
  83775. _this.name = name;
  83776. _this.url = url;
  83777. _this.noMipmap = noMipmap;
  83778. _this.invertY = invertY;
  83779. _this.samplingMode = samplingMode;
  83780. return _this;
  83781. }
  83782. /**
  83783. * Execute the current task
  83784. * @param scene defines the scene where you want your assets to be loaded
  83785. * @param onSuccess is a callback called when the task is successfully executed
  83786. * @param onError is a callback called if an error occurs
  83787. */
  83788. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  83789. var onload = function () {
  83790. onSuccess();
  83791. };
  83792. var onerror = function (message, exception) {
  83793. onError(message, exception);
  83794. };
  83795. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  83796. };
  83797. return TextureAssetTask;
  83798. }(AbstractAssetTask));
  83799. BABYLON.TextureAssetTask = TextureAssetTask;
  83800. /**
  83801. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  83802. */
  83803. var CubeTextureAssetTask = /** @class */ (function (_super) {
  83804. __extends(CubeTextureAssetTask, _super);
  83805. /**
  83806. * Creates a new CubeTextureAssetTask
  83807. * @param name defines the name of the task
  83808. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  83809. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  83810. * @param noMipmap defines if mipmaps should not be generated (default is false)
  83811. * @param files defines the explicit list of files (undefined by default)
  83812. */
  83813. function CubeTextureAssetTask(
  83814. /**
  83815. * Defines the name of the task
  83816. */
  83817. name,
  83818. /**
  83819. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  83820. */
  83821. url,
  83822. /**
  83823. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  83824. */
  83825. extensions,
  83826. /**
  83827. * Defines if mipmaps should not be generated (default is false)
  83828. */
  83829. noMipmap,
  83830. /**
  83831. * Defines the explicit list of files (undefined by default)
  83832. */
  83833. files) {
  83834. var _this = _super.call(this, name) || this;
  83835. _this.name = name;
  83836. _this.url = url;
  83837. _this.extensions = extensions;
  83838. _this.noMipmap = noMipmap;
  83839. _this.files = files;
  83840. return _this;
  83841. }
  83842. /**
  83843. * Execute the current task
  83844. * @param scene defines the scene where you want your assets to be loaded
  83845. * @param onSuccess is a callback called when the task is successfully executed
  83846. * @param onError is a callback called if an error occurs
  83847. */
  83848. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  83849. var onload = function () {
  83850. onSuccess();
  83851. };
  83852. var onerror = function (message, exception) {
  83853. onError(message, exception);
  83854. };
  83855. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  83856. };
  83857. return CubeTextureAssetTask;
  83858. }(AbstractAssetTask));
  83859. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  83860. /**
  83861. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  83862. */
  83863. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  83864. __extends(HDRCubeTextureAssetTask, _super);
  83865. /**
  83866. * Creates a new HDRCubeTextureAssetTask object
  83867. * @param name defines the name of the task
  83868. * @param url defines the location of the file to load
  83869. * @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.
  83870. * @param noMipmap defines if mipmaps should not be generated (default is false)
  83871. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  83872. * @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)
  83873. * @param usePMREMGenerator specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  83874. */
  83875. function HDRCubeTextureAssetTask(
  83876. /**
  83877. * Defines the name of the task
  83878. */
  83879. name,
  83880. /**
  83881. * Defines the location of the file to load
  83882. */
  83883. url,
  83884. /**
  83885. * 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.
  83886. */
  83887. size,
  83888. /**
  83889. * Defines if mipmaps should not be generated (default is false)
  83890. */
  83891. noMipmap,
  83892. /**
  83893. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  83894. */
  83895. generateHarmonics,
  83896. /**
  83897. * 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)
  83898. */
  83899. useInGammaSpace,
  83900. /**
  83901. * Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  83902. */
  83903. usePMREMGenerator) {
  83904. if (noMipmap === void 0) { noMipmap = false; }
  83905. if (generateHarmonics === void 0) { generateHarmonics = true; }
  83906. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  83907. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  83908. var _this = _super.call(this, name) || this;
  83909. _this.name = name;
  83910. _this.url = url;
  83911. _this.size = size;
  83912. _this.noMipmap = noMipmap;
  83913. _this.generateHarmonics = generateHarmonics;
  83914. _this.useInGammaSpace = useInGammaSpace;
  83915. _this.usePMREMGenerator = usePMREMGenerator;
  83916. return _this;
  83917. }
  83918. /**
  83919. * Execute the current task
  83920. * @param scene defines the scene where you want your assets to be loaded
  83921. * @param onSuccess is a callback called when the task is successfully executed
  83922. * @param onError is a callback called if an error occurs
  83923. */
  83924. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  83925. var onload = function () {
  83926. onSuccess();
  83927. };
  83928. var onerror = function (message, exception) {
  83929. onError(message, exception);
  83930. };
  83931. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.useInGammaSpace, this.usePMREMGenerator, onload, onerror);
  83932. };
  83933. return HDRCubeTextureAssetTask;
  83934. }(AbstractAssetTask));
  83935. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  83936. /**
  83937. * This class can be used to easily import assets into a scene
  83938. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  83939. */
  83940. var AssetsManager = /** @class */ (function () {
  83941. /**
  83942. * Creates a new AssetsManager
  83943. * @param scene defines the scene to work on
  83944. */
  83945. function AssetsManager(scene) {
  83946. this._isLoading = false;
  83947. this._tasks = new Array();
  83948. this._waitingTasksCount = 0;
  83949. this._totalTasksCount = 0;
  83950. /**
  83951. * Observable called when all tasks are processed
  83952. */
  83953. this.onTaskSuccessObservable = new BABYLON.Observable();
  83954. /**
  83955. * Observable called when a task had an error
  83956. */
  83957. this.onTaskErrorObservable = new BABYLON.Observable();
  83958. /**
  83959. * Observable called when a task is successful
  83960. */
  83961. this.onTasksDoneObservable = new BABYLON.Observable();
  83962. /**
  83963. * Observable called when a task is done (whatever the result is)
  83964. */
  83965. this.onProgressObservable = new BABYLON.Observable();
  83966. /**
  83967. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  83968. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  83969. */
  83970. this.useDefaultLoadingScreen = true;
  83971. this._scene = scene;
  83972. }
  83973. /**
  83974. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  83975. * @param taskName defines the name of the new task
  83976. * @param meshesNames defines the name of meshes to load
  83977. * @param rootUrl defines the root url to use to locate files
  83978. * @param sceneFilename defines the filename of the scene file
  83979. * @returns a new {BABYLON.MeshAssetTask} object
  83980. */
  83981. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  83982. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  83983. this._tasks.push(task);
  83984. return task;
  83985. };
  83986. /**
  83987. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  83988. * @param taskName defines the name of the new task
  83989. * @param url defines the url of the file to load
  83990. * @returns a new {BABYLON.TextFileAssetTask} object
  83991. */
  83992. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  83993. var task = new TextFileAssetTask(taskName, url);
  83994. this._tasks.push(task);
  83995. return task;
  83996. };
  83997. /**
  83998. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  83999. * @param taskName defines the name of the new task
  84000. * @param url defines the url of the file to load
  84001. * @returns a new {BABYLON.BinaryFileAssetTask} object
  84002. */
  84003. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  84004. var task = new BinaryFileAssetTask(taskName, url);
  84005. this._tasks.push(task);
  84006. return task;
  84007. };
  84008. /**
  84009. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  84010. * @param taskName defines the name of the new task
  84011. * @param url defines the url of the file to load
  84012. * @returns a new {BABYLON.ImageAssetTask} object
  84013. */
  84014. AssetsManager.prototype.addImageTask = function (taskName, url) {
  84015. var task = new ImageAssetTask(taskName, url);
  84016. this._tasks.push(task);
  84017. return task;
  84018. };
  84019. /**
  84020. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  84021. * @param taskName defines the name of the new task
  84022. * @param url defines the url of the file to load
  84023. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  84024. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  84025. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  84026. * @returns a new {BABYLON.TextureAssetTask} object
  84027. */
  84028. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  84029. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  84030. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  84031. this._tasks.push(task);
  84032. return task;
  84033. };
  84034. /**
  84035. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  84036. * @param taskName defines the name of the new task
  84037. * @param url defines the url of the file to load
  84038. * @param extensions defines the extension to use to load the cube map (can be null)
  84039. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  84040. * @param files defines the list of files to load (can be null)
  84041. * @returns a new {BABYLON.CubeTextureAssetTask} object
  84042. */
  84043. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  84044. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  84045. this._tasks.push(task);
  84046. return task;
  84047. };
  84048. /**
  84049. *
  84050. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  84051. * @param taskName defines the name of the new task
  84052. * @param url defines the url of the file to load
  84053. * @param size defines the size you want for the cubemap (can be null)
  84054. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  84055. * @param generateHarmonics defines if you want to automatically generate (true by default)
  84056. * @param useInGammaSpace defines if the texture must be considered in gamma space (false by default)
  84057. * @param usePMREMGenerator is a reserved parameter and must be set to false or ignored
  84058. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  84059. */
  84060. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  84061. if (noMipmap === void 0) { noMipmap = false; }
  84062. if (generateHarmonics === void 0) { generateHarmonics = true; }
  84063. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  84064. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  84065. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator);
  84066. this._tasks.push(task);
  84067. return task;
  84068. };
  84069. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  84070. var _this = this;
  84071. this._waitingTasksCount--;
  84072. try {
  84073. if (task.taskState === AssetTaskState.DONE) {
  84074. // Let's remove successfull tasks
  84075. BABYLON.Tools.SetImmediate(function () {
  84076. var index = _this._tasks.indexOf(task);
  84077. if (index > -1) {
  84078. _this._tasks.splice(index, 1);
  84079. }
  84080. });
  84081. }
  84082. if (this.onProgress) {
  84083. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  84084. }
  84085. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  84086. }
  84087. catch (e) {
  84088. BABYLON.Tools.Error("Error running progress callbacks.");
  84089. console.log(e);
  84090. }
  84091. if (this._waitingTasksCount === 0) {
  84092. try {
  84093. if (this.onFinish) {
  84094. this.onFinish(this._tasks);
  84095. }
  84096. this.onTasksDoneObservable.notifyObservers(this._tasks);
  84097. }
  84098. catch (e) {
  84099. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  84100. console.log(e);
  84101. }
  84102. this._isLoading = false;
  84103. this._scene.getEngine().hideLoadingUI();
  84104. }
  84105. };
  84106. AssetsManager.prototype._runTask = function (task) {
  84107. var _this = this;
  84108. var done = function () {
  84109. try {
  84110. if (_this.onTaskSuccess) {
  84111. _this.onTaskSuccess(task);
  84112. }
  84113. _this.onTaskSuccessObservable.notifyObservers(task);
  84114. _this._decreaseWaitingTasksCount(task);
  84115. }
  84116. catch (e) {
  84117. error("Error executing task success callbacks", e);
  84118. }
  84119. };
  84120. var error = function (message, exception) {
  84121. task._setErrorObject(message, exception);
  84122. if (_this.onTaskError) {
  84123. _this.onTaskError(task);
  84124. }
  84125. _this.onTaskErrorObservable.notifyObservers(task);
  84126. _this._decreaseWaitingTasksCount(task);
  84127. };
  84128. task.run(this._scene, done, error);
  84129. };
  84130. /**
  84131. * Reset the {BABYLON.AssetsManager} and remove all tasks
  84132. * @return the current instance of the {BABYLON.AssetsManager}
  84133. */
  84134. AssetsManager.prototype.reset = function () {
  84135. this._isLoading = false;
  84136. this._tasks = new Array();
  84137. return this;
  84138. };
  84139. /**
  84140. * Start the loading process
  84141. * @return the current instance of the {BABYLON.AssetsManager}
  84142. */
  84143. AssetsManager.prototype.load = function () {
  84144. if (this._isLoading) {
  84145. return this;
  84146. }
  84147. this._isLoading = true;
  84148. this._waitingTasksCount = this._tasks.length;
  84149. this._totalTasksCount = this._tasks.length;
  84150. if (this._waitingTasksCount === 0) {
  84151. if (this.onFinish) {
  84152. this.onFinish(this._tasks);
  84153. }
  84154. this.onTasksDoneObservable.notifyObservers(this._tasks);
  84155. return this;
  84156. }
  84157. if (this.useDefaultLoadingScreen) {
  84158. this._scene.getEngine().displayLoadingUI();
  84159. }
  84160. for (var index = 0; index < this._tasks.length; index++) {
  84161. var task = this._tasks[index];
  84162. this._runTask(task);
  84163. }
  84164. return this;
  84165. };
  84166. return AssetsManager;
  84167. }());
  84168. BABYLON.AssetsManager = AssetsManager;
  84169. })(BABYLON || (BABYLON = {}));
  84170. //# sourceMappingURL=babylon.assetsManager.js.map
  84171. var BABYLON;
  84172. (function (BABYLON) {
  84173. var serializedGeometries = [];
  84174. var serializeGeometry = function (geometry, serializationGeometries) {
  84175. if (serializedGeometries[geometry.id]) {
  84176. return;
  84177. }
  84178. if (geometry.doNotSerialize) {
  84179. return;
  84180. }
  84181. if (geometry instanceof BABYLON.BoxGeometry) {
  84182. serializationGeometries.boxes.push(geometry.serialize());
  84183. }
  84184. else if (geometry instanceof BABYLON.SphereGeometry) {
  84185. serializationGeometries.spheres.push(geometry.serialize());
  84186. }
  84187. else if (geometry instanceof BABYLON.CylinderGeometry) {
  84188. serializationGeometries.cylinders.push(geometry.serialize());
  84189. }
  84190. else if (geometry instanceof BABYLON.TorusGeometry) {
  84191. serializationGeometries.toruses.push(geometry.serialize());
  84192. }
  84193. else if (geometry instanceof BABYLON.GroundGeometry) {
  84194. serializationGeometries.grounds.push(geometry.serialize());
  84195. }
  84196. else if (geometry instanceof BABYLON.Plane) {
  84197. serializationGeometries.planes.push(geometry.serialize());
  84198. }
  84199. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  84200. serializationGeometries.torusKnots.push(geometry.serialize());
  84201. }
  84202. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  84203. throw new Error("Unknown primitive type");
  84204. }
  84205. else {
  84206. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  84207. }
  84208. serializedGeometries[geometry.id] = true;
  84209. };
  84210. var serializeMesh = function (mesh, serializationScene) {
  84211. var serializationObject = {};
  84212. // Geometry
  84213. var geometry = mesh._geometry;
  84214. if (geometry) {
  84215. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  84216. // 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
  84217. serializeGeometry(geometry, serializationScene.geometries);
  84218. }
  84219. }
  84220. // Custom
  84221. if (mesh.serialize) {
  84222. mesh.serialize(serializationObject);
  84223. }
  84224. return serializationObject;
  84225. };
  84226. var finalizeSingleMesh = function (mesh, serializationObject) {
  84227. //only works if the mesh is already loaded
  84228. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  84229. //serialize material
  84230. if (mesh.material) {
  84231. if (mesh.material instanceof BABYLON.StandardMaterial) {
  84232. serializationObject.materials = serializationObject.materials || [];
  84233. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  84234. serializationObject.materials.push(mesh.material.serialize());
  84235. }
  84236. }
  84237. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  84238. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  84239. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  84240. serializationObject.multiMaterials.push(mesh.material.serialize());
  84241. }
  84242. }
  84243. }
  84244. //serialize geometry
  84245. var geometry = mesh._geometry;
  84246. if (geometry) {
  84247. if (!serializationObject.geometries) {
  84248. serializationObject.geometries = {};
  84249. serializationObject.geometries.boxes = [];
  84250. serializationObject.geometries.spheres = [];
  84251. serializationObject.geometries.cylinders = [];
  84252. serializationObject.geometries.toruses = [];
  84253. serializationObject.geometries.grounds = [];
  84254. serializationObject.geometries.planes = [];
  84255. serializationObject.geometries.torusKnots = [];
  84256. serializationObject.geometries.vertexData = [];
  84257. }
  84258. serializeGeometry(geometry, serializationObject.geometries);
  84259. }
  84260. // Skeletons
  84261. if (mesh.skeleton) {
  84262. serializationObject.skeletons = serializationObject.skeletons || [];
  84263. serializationObject.skeletons.push(mesh.skeleton.serialize());
  84264. }
  84265. //serialize the actual mesh
  84266. serializationObject.meshes = serializationObject.meshes || [];
  84267. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  84268. }
  84269. };
  84270. var SceneSerializer = /** @class */ (function () {
  84271. function SceneSerializer() {
  84272. }
  84273. SceneSerializer.ClearCache = function () {
  84274. serializedGeometries = [];
  84275. };
  84276. SceneSerializer.Serialize = function (scene) {
  84277. var serializationObject = {};
  84278. SceneSerializer.ClearCache();
  84279. // Scene
  84280. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  84281. serializationObject.autoClear = scene.autoClear;
  84282. serializationObject.clearColor = scene.clearColor.asArray();
  84283. serializationObject.ambientColor = scene.ambientColor.asArray();
  84284. serializationObject.gravity = scene.gravity.asArray();
  84285. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  84286. serializationObject.workerCollisions = scene.workerCollisions;
  84287. // Fog
  84288. if (scene.fogMode && scene.fogMode !== 0) {
  84289. serializationObject.fogMode = scene.fogMode;
  84290. serializationObject.fogColor = scene.fogColor.asArray();
  84291. serializationObject.fogStart = scene.fogStart;
  84292. serializationObject.fogEnd = scene.fogEnd;
  84293. serializationObject.fogDensity = scene.fogDensity;
  84294. }
  84295. //Physics
  84296. if (scene.isPhysicsEnabled()) {
  84297. var physicEngine = scene.getPhysicsEngine();
  84298. if (physicEngine) {
  84299. serializationObject.physicsEnabled = true;
  84300. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  84301. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  84302. }
  84303. }
  84304. // Metadata
  84305. if (scene.metadata) {
  84306. serializationObject.metadata = scene.metadata;
  84307. }
  84308. // Morph targets
  84309. serializationObject.morphTargetManagers = [];
  84310. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  84311. var abstractMesh = _a[_i];
  84312. var manager = abstractMesh.morphTargetManager;
  84313. if (manager) {
  84314. serializationObject.morphTargetManagers.push(manager.serialize());
  84315. }
  84316. }
  84317. // Lights
  84318. serializationObject.lights = [];
  84319. var index;
  84320. var light;
  84321. for (index = 0; index < scene.lights.length; index++) {
  84322. light = scene.lights[index];
  84323. if (!light.doNotSerialize) {
  84324. serializationObject.lights.push(light.serialize());
  84325. }
  84326. }
  84327. // Cameras
  84328. serializationObject.cameras = [];
  84329. for (index = 0; index < scene.cameras.length; index++) {
  84330. var camera = scene.cameras[index];
  84331. if (!camera.doNotSerialize) {
  84332. serializationObject.cameras.push(camera.serialize());
  84333. }
  84334. }
  84335. if (scene.activeCamera) {
  84336. serializationObject.activeCameraID = scene.activeCamera.id;
  84337. }
  84338. // Animations
  84339. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  84340. // Materials
  84341. serializationObject.materials = [];
  84342. serializationObject.multiMaterials = [];
  84343. var material;
  84344. for (index = 0; index < scene.materials.length; index++) {
  84345. material = scene.materials[index];
  84346. if (!material.doNotSerialize) {
  84347. serializationObject.materials.push(material.serialize());
  84348. }
  84349. }
  84350. // MultiMaterials
  84351. serializationObject.multiMaterials = [];
  84352. for (index = 0; index < scene.multiMaterials.length; index++) {
  84353. var multiMaterial = scene.multiMaterials[index];
  84354. serializationObject.multiMaterials.push(multiMaterial.serialize());
  84355. }
  84356. // Environment texture
  84357. if (scene.environmentTexture) {
  84358. serializationObject.environmentTexture = scene.environmentTexture.name;
  84359. }
  84360. // Skeletons
  84361. serializationObject.skeletons = [];
  84362. for (index = 0; index < scene.skeletons.length; index++) {
  84363. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  84364. }
  84365. // Transform nodes
  84366. serializationObject.transformNodes = [];
  84367. for (index = 0; index < scene.transformNodes.length; index++) {
  84368. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  84369. }
  84370. // Geometries
  84371. serializationObject.geometries = {};
  84372. serializationObject.geometries.boxes = [];
  84373. serializationObject.geometries.spheres = [];
  84374. serializationObject.geometries.cylinders = [];
  84375. serializationObject.geometries.toruses = [];
  84376. serializationObject.geometries.grounds = [];
  84377. serializationObject.geometries.planes = [];
  84378. serializationObject.geometries.torusKnots = [];
  84379. serializationObject.geometries.vertexData = [];
  84380. serializedGeometries = [];
  84381. var geometries = scene.getGeometries();
  84382. for (index = 0; index < geometries.length; index++) {
  84383. var geometry = geometries[index];
  84384. if (geometry.isReady()) {
  84385. serializeGeometry(geometry, serializationObject.geometries);
  84386. }
  84387. }
  84388. // Meshes
  84389. serializationObject.meshes = [];
  84390. for (index = 0; index < scene.meshes.length; index++) {
  84391. var abstractMesh = scene.meshes[index];
  84392. if (abstractMesh instanceof BABYLON.Mesh) {
  84393. var mesh = abstractMesh;
  84394. if (!mesh.doNotSerialize) {
  84395. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  84396. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  84397. }
  84398. }
  84399. }
  84400. }
  84401. // Particles Systems
  84402. serializationObject.particleSystems = [];
  84403. for (index = 0; index < scene.particleSystems.length; index++) {
  84404. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  84405. }
  84406. // Lens flares
  84407. serializationObject.lensFlareSystems = [];
  84408. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  84409. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  84410. }
  84411. // Shadows
  84412. serializationObject.shadowGenerators = [];
  84413. for (index = 0; index < scene.lights.length; index++) {
  84414. light = scene.lights[index];
  84415. var shadowGenerator = light.getShadowGenerator();
  84416. if (shadowGenerator) {
  84417. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  84418. }
  84419. }
  84420. // Action Manager
  84421. if (scene.actionManager) {
  84422. serializationObject.actions = scene.actionManager.serialize("scene");
  84423. }
  84424. // Audio
  84425. serializationObject.sounds = [];
  84426. for (index = 0; index < scene.soundTracks.length; index++) {
  84427. var soundtrack = scene.soundTracks[index];
  84428. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  84429. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  84430. }
  84431. }
  84432. return serializationObject;
  84433. };
  84434. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  84435. if (withParents === void 0) { withParents = false; }
  84436. if (withChildren === void 0) { withChildren = false; }
  84437. var serializationObject = {};
  84438. SceneSerializer.ClearCache();
  84439. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  84440. if (withParents || withChildren) {
  84441. //deliberate for loop! not for each, appended should be processed as well.
  84442. for (var i = 0; i < toSerialize.length; ++i) {
  84443. if (withChildren) {
  84444. toSerialize[i].getDescendants().forEach(function (node) {
  84445. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  84446. toSerialize.push(node);
  84447. }
  84448. });
  84449. }
  84450. //make sure the array doesn't contain the object already
  84451. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  84452. toSerialize.push(toSerialize[i].parent);
  84453. }
  84454. }
  84455. }
  84456. toSerialize.forEach(function (mesh) {
  84457. finalizeSingleMesh(mesh, serializationObject);
  84458. });
  84459. return serializationObject;
  84460. };
  84461. return SceneSerializer;
  84462. }());
  84463. BABYLON.SceneSerializer = SceneSerializer;
  84464. })(BABYLON || (BABYLON = {}));
  84465. //# sourceMappingURL=babylon.sceneSerializer.js.map
  84466. var BABYLON;
  84467. (function (BABYLON) {
  84468. var ReflectionProbe = /** @class */ (function () {
  84469. function ReflectionProbe(name, size, scene, generateMipMaps) {
  84470. if (generateMipMaps === void 0) { generateMipMaps = true; }
  84471. var _this = this;
  84472. this.name = name;
  84473. this._viewMatrix = BABYLON.Matrix.Identity();
  84474. this._target = BABYLON.Vector3.Zero();
  84475. this._add = BABYLON.Vector3.Zero();
  84476. this.invertYAxis = false;
  84477. this.position = BABYLON.Vector3.Zero();
  84478. this._scene = scene;
  84479. this._scene.reflectionProbes.push(this);
  84480. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  84481. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  84482. switch (faceIndex) {
  84483. case 0:
  84484. _this._add.copyFromFloats(1, 0, 0);
  84485. break;
  84486. case 1:
  84487. _this._add.copyFromFloats(-1, 0, 0);
  84488. break;
  84489. case 2:
  84490. _this._add.copyFromFloats(0, _this.invertYAxis ? 1 : -1, 0);
  84491. break;
  84492. case 3:
  84493. _this._add.copyFromFloats(0, _this.invertYAxis ? -1 : 1, 0);
  84494. break;
  84495. case 4:
  84496. _this._add.copyFromFloats(0, 0, 1);
  84497. break;
  84498. case 5:
  84499. _this._add.copyFromFloats(0, 0, -1);
  84500. break;
  84501. }
  84502. if (_this._attachedMesh) {
  84503. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  84504. }
  84505. _this.position.addToRef(_this._add, _this._target);
  84506. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  84507. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  84508. scene._forcedViewPosition = _this.position;
  84509. });
  84510. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  84511. scene._forcedViewPosition = null;
  84512. scene.updateTransformMatrix(true);
  84513. });
  84514. if (scene.activeCamera) {
  84515. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  84516. }
  84517. }
  84518. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  84519. get: function () {
  84520. return this._renderTargetTexture.samples;
  84521. },
  84522. set: function (value) {
  84523. this._renderTargetTexture.samples = value;
  84524. },
  84525. enumerable: true,
  84526. configurable: true
  84527. });
  84528. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  84529. get: function () {
  84530. return this._renderTargetTexture.refreshRate;
  84531. },
  84532. set: function (value) {
  84533. this._renderTargetTexture.refreshRate = value;
  84534. },
  84535. enumerable: true,
  84536. configurable: true
  84537. });
  84538. ReflectionProbe.prototype.getScene = function () {
  84539. return this._scene;
  84540. };
  84541. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  84542. get: function () {
  84543. return this._renderTargetTexture;
  84544. },
  84545. enumerable: true,
  84546. configurable: true
  84547. });
  84548. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  84549. get: function () {
  84550. return this._renderTargetTexture.renderList;
  84551. },
  84552. enumerable: true,
  84553. configurable: true
  84554. });
  84555. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  84556. this._attachedMesh = mesh;
  84557. };
  84558. /**
  84559. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  84560. *
  84561. * @param renderingGroupId The rendering group id corresponding to its index
  84562. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  84563. */
  84564. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  84565. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  84566. };
  84567. ReflectionProbe.prototype.dispose = function () {
  84568. var index = this._scene.reflectionProbes.indexOf(this);
  84569. if (index !== -1) {
  84570. // Remove from the scene if found
  84571. this._scene.reflectionProbes.splice(index, 1);
  84572. }
  84573. if (this._renderTargetTexture) {
  84574. this._renderTargetTexture.dispose();
  84575. this._renderTargetTexture = null;
  84576. }
  84577. };
  84578. return ReflectionProbe;
  84579. }());
  84580. BABYLON.ReflectionProbe = ReflectionProbe;
  84581. })(BABYLON || (BABYLON = {}));
  84582. //# sourceMappingURL=babylon.reflectionProbe.js.map
  84583. var BABYLON;
  84584. (function (BABYLON) {
  84585. var Layer = /** @class */ (function () {
  84586. function Layer(name, imgUrl, scene, isBackground, color) {
  84587. this.name = name;
  84588. this.scale = new BABYLON.Vector2(1, 1);
  84589. this.offset = new BABYLON.Vector2(0, 0);
  84590. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  84591. this.layerMask = 0x0FFFFFFF;
  84592. this._vertexBuffers = {};
  84593. // Events
  84594. /**
  84595. * An event triggered when the layer is disposed.
  84596. * @type {BABYLON.Observable}
  84597. */
  84598. this.onDisposeObservable = new BABYLON.Observable();
  84599. /**
  84600. * An event triggered before rendering the scene
  84601. * @type {BABYLON.Observable}
  84602. */
  84603. this.onBeforeRenderObservable = new BABYLON.Observable();
  84604. /**
  84605. * An event triggered after rendering the scene
  84606. * @type {BABYLON.Observable}
  84607. */
  84608. this.onAfterRenderObservable = new BABYLON.Observable();
  84609. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  84610. this.isBackground = isBackground === undefined ? true : isBackground;
  84611. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  84612. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  84613. this._scene.layers.push(this);
  84614. var engine = this._scene.getEngine();
  84615. // VBO
  84616. var vertices = [];
  84617. vertices.push(1, 1);
  84618. vertices.push(-1, 1);
  84619. vertices.push(-1, -1);
  84620. vertices.push(1, -1);
  84621. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  84622. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  84623. this._createIndexBuffer();
  84624. // Effects
  84625. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  84626. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  84627. }
  84628. Object.defineProperty(Layer.prototype, "onDispose", {
  84629. set: function (callback) {
  84630. if (this._onDisposeObserver) {
  84631. this.onDisposeObservable.remove(this._onDisposeObserver);
  84632. }
  84633. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  84634. },
  84635. enumerable: true,
  84636. configurable: true
  84637. });
  84638. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  84639. set: function (callback) {
  84640. if (this._onBeforeRenderObserver) {
  84641. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  84642. }
  84643. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  84644. },
  84645. enumerable: true,
  84646. configurable: true
  84647. });
  84648. Object.defineProperty(Layer.prototype, "onAfterRender", {
  84649. set: function (callback) {
  84650. if (this._onAfterRenderObserver) {
  84651. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  84652. }
  84653. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  84654. },
  84655. enumerable: true,
  84656. configurable: true
  84657. });
  84658. Layer.prototype._createIndexBuffer = function () {
  84659. var engine = this._scene.getEngine();
  84660. // Indices
  84661. var indices = [];
  84662. indices.push(0);
  84663. indices.push(1);
  84664. indices.push(2);
  84665. indices.push(0);
  84666. indices.push(2);
  84667. indices.push(3);
  84668. this._indexBuffer = engine.createIndexBuffer(indices);
  84669. };
  84670. Layer.prototype._rebuild = function () {
  84671. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  84672. if (vb) {
  84673. vb._rebuild();
  84674. }
  84675. this._createIndexBuffer();
  84676. };
  84677. Layer.prototype.render = function () {
  84678. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  84679. // Check
  84680. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  84681. return;
  84682. var engine = this._scene.getEngine();
  84683. this.onBeforeRenderObservable.notifyObservers(this);
  84684. // Render
  84685. engine.enableEffect(currentEffect);
  84686. engine.setState(false);
  84687. // Texture
  84688. currentEffect.setTexture("textureSampler", this.texture);
  84689. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  84690. // Color
  84691. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  84692. // Scale / offset
  84693. currentEffect.setVector2("offset", this.offset);
  84694. currentEffect.setVector2("scale", this.scale);
  84695. // VBOs
  84696. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  84697. // Draw order
  84698. if (!this.alphaTest) {
  84699. engine.setAlphaMode(this.alphaBlendingMode);
  84700. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  84701. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  84702. }
  84703. else {
  84704. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  84705. }
  84706. this.onAfterRenderObservable.notifyObservers(this);
  84707. };
  84708. Layer.prototype.dispose = function () {
  84709. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  84710. if (vertexBuffer) {
  84711. vertexBuffer.dispose();
  84712. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  84713. }
  84714. if (this._indexBuffer) {
  84715. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  84716. this._indexBuffer = null;
  84717. }
  84718. if (this.texture) {
  84719. this.texture.dispose();
  84720. this.texture = null;
  84721. }
  84722. // Remove from scene
  84723. var index = this._scene.layers.indexOf(this);
  84724. this._scene.layers.splice(index, 1);
  84725. // Callback
  84726. this.onDisposeObservable.notifyObservers(this);
  84727. this.onDisposeObservable.clear();
  84728. this.onAfterRenderObservable.clear();
  84729. this.onBeforeRenderObservable.clear();
  84730. };
  84731. return Layer;
  84732. }());
  84733. BABYLON.Layer = Layer;
  84734. })(BABYLON || (BABYLON = {}));
  84735. //# sourceMappingURL=babylon.layer.js.map
  84736. var BABYLON;
  84737. (function (BABYLON) {
  84738. var TextureTools = /** @class */ (function () {
  84739. function TextureTools() {
  84740. }
  84741. /**
  84742. * Uses the GPU to create a copy texture rescaled at a given size
  84743. * @param texture Texture to copy from
  84744. * @param width Desired width
  84745. * @param height Desired height
  84746. * @return Generated texture
  84747. */
  84748. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  84749. if (useBilinearMode === void 0) { useBilinearMode = true; }
  84750. var scene = texture.getScene();
  84751. var engine = scene.getEngine();
  84752. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  84753. rtt.wrapU = texture.wrapU;
  84754. rtt.wrapV = texture.wrapV;
  84755. rtt.uOffset = texture.uOffset;
  84756. rtt.vOffset = texture.vOffset;
  84757. rtt.uScale = texture.uScale;
  84758. rtt.vScale = texture.vScale;
  84759. rtt.uAng = texture.uAng;
  84760. rtt.vAng = texture.vAng;
  84761. rtt.wAng = texture.wAng;
  84762. rtt.coordinatesIndex = texture.coordinatesIndex;
  84763. rtt.level = texture.level;
  84764. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  84765. rtt._texture.isReady = false;
  84766. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  84767. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  84768. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  84769. passPostProcess.getEffect().executeWhenCompiled(function () {
  84770. passPostProcess.onApply = function (effect) {
  84771. effect.setTexture("textureSampler", texture);
  84772. };
  84773. var internalTexture = rtt.getInternalTexture();
  84774. if (internalTexture) {
  84775. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  84776. engine.unBindFramebuffer(internalTexture);
  84777. rtt.disposeFramebufferObjects();
  84778. passPostProcess.dispose();
  84779. internalTexture.isReady = true;
  84780. }
  84781. });
  84782. return rtt;
  84783. };
  84784. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  84785. if (!scene._environmentBRDFTexture) {
  84786. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  84787. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  84788. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  84789. scene._environmentBRDFTexture = texture;
  84790. }
  84791. return scene._environmentBRDFTexture;
  84792. };
  84793. 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=";
  84794. return TextureTools;
  84795. }());
  84796. BABYLON.TextureTools = TextureTools;
  84797. })(BABYLON || (BABYLON = {}));
  84798. //# sourceMappingURL=babylon.textureTools.js.map
  84799. var BABYLON;
  84800. (function (BABYLON) {
  84801. var FramingBehavior = /** @class */ (function () {
  84802. function FramingBehavior() {
  84803. this._mode = FramingBehavior.FitFrustumSidesMode;
  84804. this._radiusScale = 1.0;
  84805. this._positionScale = 0.5;
  84806. this._defaultElevation = 0.3;
  84807. this._elevationReturnTime = 1500;
  84808. this._elevationReturnWaitTime = 1000;
  84809. this._zoomStopsAnimation = false;
  84810. this._framingTime = 1500;
  84811. this._isPointerDown = false;
  84812. this._lastInteractionTime = -Infinity;
  84813. // Framing control
  84814. this._animatables = new Array();
  84815. this._betaIsAnimating = false;
  84816. }
  84817. Object.defineProperty(FramingBehavior.prototype, "name", {
  84818. get: function () {
  84819. return "Framing";
  84820. },
  84821. enumerable: true,
  84822. configurable: true
  84823. });
  84824. Object.defineProperty(FramingBehavior.prototype, "mode", {
  84825. /**
  84826. * Gets current mode used by the behavior.
  84827. */
  84828. get: function () {
  84829. return this._mode;
  84830. },
  84831. /**
  84832. * Sets the current mode used by the behavior
  84833. */
  84834. set: function (mode) {
  84835. this._mode = mode;
  84836. },
  84837. enumerable: true,
  84838. configurable: true
  84839. });
  84840. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  84841. /**
  84842. * Gets the scale applied to the radius
  84843. */
  84844. get: function () {
  84845. return this._radiusScale;
  84846. },
  84847. /**
  84848. * Sets the scale applied to the radius (1 by default)
  84849. */
  84850. set: function (radius) {
  84851. this._radiusScale = radius;
  84852. },
  84853. enumerable: true,
  84854. configurable: true
  84855. });
  84856. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  84857. /**
  84858. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  84859. */
  84860. get: function () {
  84861. return this._positionScale;
  84862. },
  84863. /**
  84864. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  84865. */
  84866. set: function (scale) {
  84867. this._positionScale = scale;
  84868. },
  84869. enumerable: true,
  84870. configurable: true
  84871. });
  84872. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  84873. /**
  84874. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  84875. * behaviour is triggered, in radians.
  84876. */
  84877. get: function () {
  84878. return this._defaultElevation;
  84879. },
  84880. /**
  84881. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  84882. * behaviour is triggered, in radians.
  84883. */
  84884. set: function (elevation) {
  84885. this._defaultElevation = elevation;
  84886. },
  84887. enumerable: true,
  84888. configurable: true
  84889. });
  84890. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  84891. /**
  84892. * Gets the time (in milliseconds) taken to return to the default beta position.
  84893. * Negative value indicates camera should not return to default.
  84894. */
  84895. get: function () {
  84896. return this._elevationReturnTime;
  84897. },
  84898. /**
  84899. * Sets the time (in milliseconds) taken to return to the default beta position.
  84900. * Negative value indicates camera should not return to default.
  84901. */
  84902. set: function (speed) {
  84903. this._elevationReturnTime = speed;
  84904. },
  84905. enumerable: true,
  84906. configurable: true
  84907. });
  84908. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  84909. /**
  84910. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  84911. */
  84912. get: function () {
  84913. return this._elevationReturnWaitTime;
  84914. },
  84915. /**
  84916. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  84917. */
  84918. set: function (time) {
  84919. this._elevationReturnWaitTime = time;
  84920. },
  84921. enumerable: true,
  84922. configurable: true
  84923. });
  84924. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  84925. /**
  84926. * Gets the flag that indicates if user zooming should stop animation.
  84927. */
  84928. get: function () {
  84929. return this._zoomStopsAnimation;
  84930. },
  84931. /**
  84932. * Sets the flag that indicates if user zooming should stop animation.
  84933. */
  84934. set: function (flag) {
  84935. this._zoomStopsAnimation = flag;
  84936. },
  84937. enumerable: true,
  84938. configurable: true
  84939. });
  84940. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  84941. /**
  84942. * Gets the transition time when framing the mesh, in milliseconds
  84943. */
  84944. get: function () {
  84945. return this._framingTime;
  84946. },
  84947. /**
  84948. * Sets the transition time when framing the mesh, in milliseconds
  84949. */
  84950. set: function (time) {
  84951. this._framingTime = time;
  84952. },
  84953. enumerable: true,
  84954. configurable: true
  84955. });
  84956. FramingBehavior.prototype.init = function () {
  84957. // Do notihng
  84958. };
  84959. FramingBehavior.prototype.attach = function (camera) {
  84960. var _this = this;
  84961. this._attachedCamera = camera;
  84962. var scene = this._attachedCamera.getScene();
  84963. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  84964. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  84965. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  84966. _this._isPointerDown = true;
  84967. return;
  84968. }
  84969. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  84970. _this._isPointerDown = false;
  84971. }
  84972. });
  84973. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  84974. if (mesh) {
  84975. _this.zoomOnMesh(mesh);
  84976. }
  84977. });
  84978. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  84979. // Stop the animation if there is user interaction and the animation should stop for this interaction
  84980. _this._applyUserInteraction();
  84981. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  84982. // back to the default position after a given timeout
  84983. _this._maintainCameraAboveGround();
  84984. });
  84985. };
  84986. FramingBehavior.prototype.detach = function () {
  84987. if (!this._attachedCamera) {
  84988. return;
  84989. }
  84990. var scene = this._attachedCamera.getScene();
  84991. if (this._onPrePointerObservableObserver) {
  84992. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  84993. }
  84994. if (this._onAfterCheckInputsObserver) {
  84995. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  84996. }
  84997. if (this._onMeshTargetChangedObserver) {
  84998. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  84999. }
  85000. this._attachedCamera = null;
  85001. };
  85002. /**
  85003. * Targets the given mesh and updates zoom level accordingly.
  85004. * @param mesh The mesh to target.
  85005. * @param radius Optional. If a cached radius position already exists, overrides default.
  85006. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  85007. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  85008. * @param onAnimationEnd Callback triggered at the end of the framing animation
  85009. */
  85010. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  85011. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  85012. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  85013. mesh.computeWorldMatrix(true);
  85014. var boundingBox = mesh.getBoundingInfo().boundingBox;
  85015. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  85016. };
  85017. /**
  85018. * Targets the given mesh with its children and updates zoom level accordingly.
  85019. * @param mesh The mesh to target.
  85020. * @param radius Optional. If a cached radius position already exists, overrides default.
  85021. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  85022. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  85023. * @param onAnimationEnd Callback triggered at the end of the framing animation
  85024. */
  85025. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  85026. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  85027. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  85028. mesh.computeWorldMatrix(true);
  85029. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  85030. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  85031. };
  85032. /**
  85033. * Targets the given meshes with their children and updates zoom level accordingly.
  85034. * @param meshes The mesh to target.
  85035. * @param radius Optional. If a cached radius position already exists, overrides default.
  85036. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  85037. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  85038. * @param onAnimationEnd Callback triggered at the end of the framing animation
  85039. */
  85040. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  85041. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  85042. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  85043. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  85044. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  85045. for (var i = 0; i < meshes.length; i++) {
  85046. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  85047. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  85048. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  85049. }
  85050. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  85051. };
  85052. /**
  85053. * Targets the given mesh and updates zoom level accordingly.
  85054. * @param mesh The mesh to target.
  85055. * @param radius Optional. If a cached radius position already exists, overrides default.
  85056. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  85057. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  85058. * @param onAnimationEnd Callback triggered at the end of the framing animation
  85059. */
  85060. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  85061. var _this = this;
  85062. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  85063. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  85064. var zoomTarget;
  85065. if (!this._attachedCamera) {
  85066. return;
  85067. }
  85068. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  85069. var bottom = minimumWorld.y;
  85070. var top = maximumWorld.y;
  85071. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  85072. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  85073. if (focusOnOriginXZ) {
  85074. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  85075. }
  85076. else {
  85077. var centerWorld = minimumWorld.add(radiusWorld);
  85078. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  85079. }
  85080. if (!this._vectorTransition) {
  85081. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  85082. }
  85083. this._betaIsAnimating = true;
  85084. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  85085. if (animatable) {
  85086. this._animatables.push(animatable);
  85087. }
  85088. // sets the radius and lower radius bounds
  85089. // Small delta ensures camera is not always at lower zoom limit.
  85090. var radius = 0;
  85091. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  85092. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  85093. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  85094. radius = position;
  85095. }
  85096. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  85097. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  85098. if (this._attachedCamera.lowerRadiusLimit === null) {
  85099. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  85100. }
  85101. }
  85102. // Set sensibilities
  85103. var extend = maximumWorld.subtract(minimumWorld).length();
  85104. this._attachedCamera.panningSensibility = 5000 / extend;
  85105. this._attachedCamera.wheelPrecision = 100 / radius;
  85106. // transition to new radius
  85107. if (!this._radiusTransition) {
  85108. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  85109. }
  85110. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  85111. if (onAnimationEnd) {
  85112. onAnimationEnd();
  85113. }
  85114. if (_this._attachedCamera) {
  85115. _this._attachedCamera.storeState();
  85116. }
  85117. });
  85118. if (animatable) {
  85119. this._animatables.push(animatable);
  85120. }
  85121. };
  85122. /**
  85123. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  85124. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  85125. * frustum width.
  85126. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  85127. * to fully enclose the mesh in the viewing frustum.
  85128. */
  85129. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  85130. var size = maximumWorld.subtract(minimumWorld);
  85131. var boxVectorGlobalDiagonal = size.length();
  85132. var frustumSlope = this._getFrustumSlope();
  85133. // Formula for setting distance
  85134. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  85135. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  85136. // Horizon distance
  85137. var radius = radiusWithoutFraming * this._radiusScale;
  85138. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  85139. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  85140. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  85141. var camera = this._attachedCamera;
  85142. if (!camera) {
  85143. return 0;
  85144. }
  85145. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  85146. // Don't exceed the requested limit
  85147. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  85148. }
  85149. // Don't exceed the upper radius limit
  85150. if (camera.upperRadiusLimit) {
  85151. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  85152. }
  85153. return distance;
  85154. };
  85155. /**
  85156. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  85157. * is automatically returned to its default position (expected to be above ground plane).
  85158. */
  85159. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  85160. var _this = this;
  85161. if (this._elevationReturnTime < 0) {
  85162. return;
  85163. }
  85164. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  85165. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  85166. var limitBeta = Math.PI * 0.5;
  85167. // Bring the camera back up if below the ground plane
  85168. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  85169. this._betaIsAnimating = true;
  85170. //Transition to new position
  85171. this.stopAllAnimations();
  85172. if (!this._betaTransition) {
  85173. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  85174. }
  85175. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  85176. _this._clearAnimationLocks();
  85177. _this.stopAllAnimations();
  85178. });
  85179. if (animatabe) {
  85180. this._animatables.push(animatabe);
  85181. }
  85182. }
  85183. };
  85184. /**
  85185. * Returns the frustum slope based on the canvas ratio and camera FOV
  85186. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  85187. */
  85188. FramingBehavior.prototype._getFrustumSlope = function () {
  85189. // Calculate the viewport ratio
  85190. // Aspect Ratio is Height/Width.
  85191. var camera = this._attachedCamera;
  85192. if (!camera) {
  85193. return BABYLON.Vector2.Zero();
  85194. }
  85195. var engine = camera.getScene().getEngine();
  85196. var aspectRatio = engine.getAspectRatio(camera);
  85197. // Camera FOV is the vertical field of view (top-bottom) in radians.
  85198. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  85199. var frustumSlopeY = Math.tan(camera.fov / 2);
  85200. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  85201. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  85202. // along the forward vector.
  85203. var frustumSlopeX = frustumSlopeY * aspectRatio;
  85204. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  85205. };
  85206. /**
  85207. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  85208. */
  85209. FramingBehavior.prototype._clearAnimationLocks = function () {
  85210. this._betaIsAnimating = false;
  85211. };
  85212. /**
  85213. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  85214. */
  85215. FramingBehavior.prototype._applyUserInteraction = function () {
  85216. if (this.isUserIsMoving) {
  85217. this._lastInteractionTime = BABYLON.Tools.Now;
  85218. this.stopAllAnimations();
  85219. this._clearAnimationLocks();
  85220. }
  85221. };
  85222. /**
  85223. * Stops and removes all animations that have been applied to the camera
  85224. */
  85225. FramingBehavior.prototype.stopAllAnimations = function () {
  85226. if (this._attachedCamera) {
  85227. this._attachedCamera.animations = [];
  85228. }
  85229. while (this._animatables.length) {
  85230. if (this._animatables[0]) {
  85231. this._animatables[0].onAnimationEnd = null;
  85232. this._animatables[0].stop();
  85233. }
  85234. this._animatables.shift();
  85235. }
  85236. };
  85237. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  85238. /**
  85239. * Gets a value indicating if the user is moving the camera
  85240. */
  85241. get: function () {
  85242. if (!this._attachedCamera) {
  85243. return false;
  85244. }
  85245. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  85246. this._attachedCamera.inertialBetaOffset !== 0 ||
  85247. this._attachedCamera.inertialRadiusOffset !== 0 ||
  85248. this._attachedCamera.inertialPanningX !== 0 ||
  85249. this._attachedCamera.inertialPanningY !== 0 ||
  85250. this._isPointerDown;
  85251. },
  85252. enumerable: true,
  85253. configurable: true
  85254. });
  85255. /**
  85256. * The easing function used by animations
  85257. */
  85258. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  85259. /**
  85260. * The easing mode used by animations
  85261. */
  85262. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  85263. // Statics
  85264. /**
  85265. * The camera can move all the way towards the mesh.
  85266. */
  85267. FramingBehavior.IgnoreBoundsSizeMode = 0;
  85268. /**
  85269. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  85270. */
  85271. FramingBehavior.FitFrustumSidesMode = 1;
  85272. return FramingBehavior;
  85273. }());
  85274. BABYLON.FramingBehavior = FramingBehavior;
  85275. })(BABYLON || (BABYLON = {}));
  85276. //# sourceMappingURL=babylon.framingBehavior.js.map
  85277. var BABYLON;
  85278. (function (BABYLON) {
  85279. /**
  85280. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  85281. */
  85282. var BouncingBehavior = /** @class */ (function () {
  85283. function BouncingBehavior() {
  85284. /**
  85285. * The duration of the animation, in milliseconds
  85286. */
  85287. this.transitionDuration = 450;
  85288. /**
  85289. * Length of the distance animated by the transition when lower radius is reached
  85290. */
  85291. this.lowerRadiusTransitionRange = 2;
  85292. /**
  85293. * Length of the distance animated by the transition when upper radius is reached
  85294. */
  85295. this.upperRadiusTransitionRange = -2;
  85296. this._autoTransitionRange = false;
  85297. // Animations
  85298. this._radiusIsAnimating = false;
  85299. this._radiusBounceTransition = null;
  85300. this._animatables = new Array();
  85301. }
  85302. Object.defineProperty(BouncingBehavior.prototype, "name", {
  85303. get: function () {
  85304. return "Bouncing";
  85305. },
  85306. enumerable: true,
  85307. configurable: true
  85308. });
  85309. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  85310. /**
  85311. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  85312. */
  85313. get: function () {
  85314. return this._autoTransitionRange;
  85315. },
  85316. /**
  85317. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  85318. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  85319. */
  85320. set: function (value) {
  85321. var _this = this;
  85322. if (this._autoTransitionRange === value) {
  85323. return;
  85324. }
  85325. this._autoTransitionRange = value;
  85326. var camera = this._attachedCamera;
  85327. if (!camera) {
  85328. return;
  85329. }
  85330. if (value) {
  85331. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  85332. if (!mesh) {
  85333. return;
  85334. }
  85335. mesh.computeWorldMatrix(true);
  85336. var diagonal = mesh.getBoundingInfo().diagonalLength;
  85337. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  85338. _this.upperRadiusTransitionRange = diagonal * 0.05;
  85339. });
  85340. }
  85341. else if (this._onMeshTargetChangedObserver) {
  85342. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  85343. }
  85344. },
  85345. enumerable: true,
  85346. configurable: true
  85347. });
  85348. BouncingBehavior.prototype.init = function () {
  85349. // Do notihng
  85350. };
  85351. BouncingBehavior.prototype.attach = function (camera) {
  85352. var _this = this;
  85353. this._attachedCamera = camera;
  85354. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  85355. if (!_this._attachedCamera) {
  85356. return;
  85357. }
  85358. // Add the bounce animation to the lower radius limit
  85359. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  85360. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  85361. }
  85362. // Add the bounce animation to the upper radius limit
  85363. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  85364. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  85365. }
  85366. });
  85367. };
  85368. BouncingBehavior.prototype.detach = function () {
  85369. if (!this._attachedCamera) {
  85370. return;
  85371. }
  85372. if (this._onAfterCheckInputsObserver) {
  85373. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  85374. }
  85375. if (this._onMeshTargetChangedObserver) {
  85376. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  85377. }
  85378. this._attachedCamera = null;
  85379. };
  85380. /**
  85381. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  85382. * @param radiusLimit The limit to check against.
  85383. * @return Bool to indicate if at limit.
  85384. */
  85385. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  85386. if (!this._attachedCamera) {
  85387. return false;
  85388. }
  85389. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  85390. return true;
  85391. }
  85392. return false;
  85393. };
  85394. /**
  85395. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  85396. * @param radiusDelta The delta by which to animate to. Can be negative.
  85397. */
  85398. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  85399. var _this = this;
  85400. if (!this._attachedCamera) {
  85401. return;
  85402. }
  85403. if (!this._radiusBounceTransition) {
  85404. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  85405. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  85406. }
  85407. // Prevent zoom until bounce has completed
  85408. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  85409. this._attachedCamera.wheelPrecision = Infinity;
  85410. this._attachedCamera.inertialRadiusOffset = 0;
  85411. // Animate to the radius limit
  85412. this.stopAllAnimations();
  85413. this._radiusIsAnimating = true;
  85414. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  85415. if (animatable) {
  85416. this._animatables.push(animatable);
  85417. }
  85418. };
  85419. /**
  85420. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  85421. */
  85422. BouncingBehavior.prototype._clearAnimationLocks = function () {
  85423. this._radiusIsAnimating = false;
  85424. if (this._attachedCamera) {
  85425. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  85426. }
  85427. };
  85428. /**
  85429. * Stops and removes all animations that have been applied to the camera
  85430. */
  85431. BouncingBehavior.prototype.stopAllAnimations = function () {
  85432. if (this._attachedCamera) {
  85433. this._attachedCamera.animations = [];
  85434. }
  85435. while (this._animatables.length) {
  85436. this._animatables[0].onAnimationEnd = null;
  85437. this._animatables[0].stop();
  85438. this._animatables.shift();
  85439. }
  85440. };
  85441. /**
  85442. * The easing function used by animations
  85443. */
  85444. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  85445. /**
  85446. * The easing mode used by animations
  85447. */
  85448. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  85449. return BouncingBehavior;
  85450. }());
  85451. BABYLON.BouncingBehavior = BouncingBehavior;
  85452. })(BABYLON || (BABYLON = {}));
  85453. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  85454. var BABYLON;
  85455. (function (BABYLON) {
  85456. var AutoRotationBehavior = /** @class */ (function () {
  85457. function AutoRotationBehavior() {
  85458. this._zoomStopsAnimation = false;
  85459. this._idleRotationSpeed = 0.05;
  85460. this._idleRotationWaitTime = 2000;
  85461. this._idleRotationSpinupTime = 2000;
  85462. this._isPointerDown = false;
  85463. this._lastFrameTime = null;
  85464. this._lastInteractionTime = -Infinity;
  85465. this._cameraRotationSpeed = 0;
  85466. this._lastFrameRadius = 0;
  85467. }
  85468. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  85469. get: function () {
  85470. return "AutoRotation";
  85471. },
  85472. enumerable: true,
  85473. configurable: true
  85474. });
  85475. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  85476. /**
  85477. * Gets the flag that indicates if user zooming should stop animation.
  85478. */
  85479. get: function () {
  85480. return this._zoomStopsAnimation;
  85481. },
  85482. /**
  85483. * Sets the flag that indicates if user zooming should stop animation.
  85484. */
  85485. set: function (flag) {
  85486. this._zoomStopsAnimation = flag;
  85487. },
  85488. enumerable: true,
  85489. configurable: true
  85490. });
  85491. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  85492. /**
  85493. * Gets the default speed at which the camera rotates around the model.
  85494. */
  85495. get: function () {
  85496. return this._idleRotationSpeed;
  85497. },
  85498. /**
  85499. * Sets the default speed at which the camera rotates around the model.
  85500. */
  85501. set: function (speed) {
  85502. this._idleRotationSpeed = speed;
  85503. },
  85504. enumerable: true,
  85505. configurable: true
  85506. });
  85507. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  85508. /**
  85509. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  85510. */
  85511. get: function () {
  85512. return this._idleRotationWaitTime;
  85513. },
  85514. /**
  85515. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  85516. */
  85517. set: function (time) {
  85518. this._idleRotationWaitTime = time;
  85519. },
  85520. enumerable: true,
  85521. configurable: true
  85522. });
  85523. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  85524. /**
  85525. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  85526. */
  85527. get: function () {
  85528. return this._idleRotationSpinupTime;
  85529. },
  85530. /**
  85531. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  85532. */
  85533. set: function (time) {
  85534. this._idleRotationSpinupTime = time;
  85535. },
  85536. enumerable: true,
  85537. configurable: true
  85538. });
  85539. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  85540. /**
  85541. * Gets a value indicating if the camera is currently rotating because of this behavior
  85542. */
  85543. get: function () {
  85544. return Math.abs(this._cameraRotationSpeed) > 0;
  85545. },
  85546. enumerable: true,
  85547. configurable: true
  85548. });
  85549. AutoRotationBehavior.prototype.init = function () {
  85550. // Do notihng
  85551. };
  85552. AutoRotationBehavior.prototype.attach = function (camera) {
  85553. var _this = this;
  85554. this._attachedCamera = camera;
  85555. var scene = this._attachedCamera.getScene();
  85556. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  85557. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  85558. _this._isPointerDown = true;
  85559. return;
  85560. }
  85561. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  85562. _this._isPointerDown = false;
  85563. }
  85564. });
  85565. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  85566. var now = BABYLON.Tools.Now;
  85567. var dt = 0;
  85568. if (_this._lastFrameTime != null) {
  85569. dt = now - _this._lastFrameTime;
  85570. }
  85571. _this._lastFrameTime = now;
  85572. // Stop the animation if there is user interaction and the animation should stop for this interaction
  85573. _this._applyUserInteraction();
  85574. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  85575. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  85576. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  85577. // Step camera rotation by rotation speed
  85578. if (_this._attachedCamera) {
  85579. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  85580. }
  85581. });
  85582. };
  85583. AutoRotationBehavior.prototype.detach = function () {
  85584. if (!this._attachedCamera) {
  85585. return;
  85586. }
  85587. var scene = this._attachedCamera.getScene();
  85588. if (this._onPrePointerObservableObserver) {
  85589. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  85590. }
  85591. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  85592. this._attachedCamera = null;
  85593. };
  85594. /**
  85595. * Returns true if user is scrolling.
  85596. * @return true if user is scrolling.
  85597. */
  85598. AutoRotationBehavior.prototype._userIsZooming = function () {
  85599. if (!this._attachedCamera) {
  85600. return false;
  85601. }
  85602. return this._attachedCamera.inertialRadiusOffset !== 0;
  85603. };
  85604. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  85605. if (!this._attachedCamera) {
  85606. return false;
  85607. }
  85608. var zoomHasHitLimit = false;
  85609. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  85610. zoomHasHitLimit = true;
  85611. }
  85612. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  85613. this._lastFrameRadius = this._attachedCamera.radius;
  85614. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  85615. };
  85616. /**
  85617. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  85618. */
  85619. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  85620. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  85621. this._lastInteractionTime = BABYLON.Tools.Now;
  85622. }
  85623. };
  85624. // Tools
  85625. AutoRotationBehavior.prototype._userIsMoving = function () {
  85626. if (!this._attachedCamera) {
  85627. return false;
  85628. }
  85629. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  85630. this._attachedCamera.inertialBetaOffset !== 0 ||
  85631. this._attachedCamera.inertialRadiusOffset !== 0 ||
  85632. this._attachedCamera.inertialPanningX !== 0 ||
  85633. this._attachedCamera.inertialPanningY !== 0 ||
  85634. this._isPointerDown;
  85635. };
  85636. return AutoRotationBehavior;
  85637. }());
  85638. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  85639. })(BABYLON || (BABYLON = {}));
  85640. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  85641. var BABYLON;
  85642. (function (BABYLON) {
  85643. /**
  85644. * This class can be used to get instrumentation data from a Babylon engine
  85645. */
  85646. var EngineInstrumentation = /** @class */ (function () {
  85647. function EngineInstrumentation(engine) {
  85648. this.engine = engine;
  85649. this._captureGPUFrameTime = false;
  85650. this._gpuFrameTime = new BABYLON.PerfCounter();
  85651. this._captureShaderCompilationTime = false;
  85652. this._shaderCompilationTime = new BABYLON.PerfCounter();
  85653. // Observers
  85654. this._onBeginFrameObserver = null;
  85655. this._onEndFrameObserver = null;
  85656. this._onBeforeShaderCompilationObserver = null;
  85657. this._onAfterShaderCompilationObserver = null;
  85658. }
  85659. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  85660. // Properties
  85661. /**
  85662. * Gets the perf counter used for GPU frame time
  85663. */
  85664. get: function () {
  85665. return this._gpuFrameTime;
  85666. },
  85667. enumerable: true,
  85668. configurable: true
  85669. });
  85670. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  85671. /**
  85672. * Gets the GPU frame time capture status
  85673. */
  85674. get: function () {
  85675. return this._captureGPUFrameTime;
  85676. },
  85677. /**
  85678. * Enable or disable the GPU frame time capture
  85679. */
  85680. set: function (value) {
  85681. var _this = this;
  85682. if (value === this._captureGPUFrameTime) {
  85683. return;
  85684. }
  85685. this._captureGPUFrameTime = value;
  85686. if (value) {
  85687. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  85688. if (!_this._gpuFrameTimeToken) {
  85689. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  85690. }
  85691. });
  85692. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  85693. if (!_this._gpuFrameTimeToken) {
  85694. return;
  85695. }
  85696. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  85697. if (time > -1) {
  85698. _this._gpuFrameTimeToken = null;
  85699. _this._gpuFrameTime.fetchNewFrame();
  85700. _this._gpuFrameTime.addCount(time, true);
  85701. }
  85702. });
  85703. }
  85704. else {
  85705. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  85706. this._onBeginFrameObserver = null;
  85707. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  85708. this._onEndFrameObserver = null;
  85709. }
  85710. },
  85711. enumerable: true,
  85712. configurable: true
  85713. });
  85714. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  85715. /**
  85716. * Gets the perf counter used for shader compilation time
  85717. */
  85718. get: function () {
  85719. return this._shaderCompilationTime;
  85720. },
  85721. enumerable: true,
  85722. configurable: true
  85723. });
  85724. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  85725. /**
  85726. * Gets the shader compilation time capture status
  85727. */
  85728. get: function () {
  85729. return this._captureShaderCompilationTime;
  85730. },
  85731. /**
  85732. * Enable or disable the shader compilation time capture
  85733. */
  85734. set: function (value) {
  85735. var _this = this;
  85736. if (value === this._captureShaderCompilationTime) {
  85737. return;
  85738. }
  85739. this._captureShaderCompilationTime = value;
  85740. if (value) {
  85741. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  85742. _this._shaderCompilationTime.fetchNewFrame();
  85743. _this._shaderCompilationTime.beginMonitoring();
  85744. });
  85745. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  85746. _this._shaderCompilationTime.endMonitoring();
  85747. });
  85748. }
  85749. else {
  85750. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  85751. this._onBeforeShaderCompilationObserver = null;
  85752. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  85753. this._onAfterShaderCompilationObserver = null;
  85754. }
  85755. },
  85756. enumerable: true,
  85757. configurable: true
  85758. });
  85759. EngineInstrumentation.prototype.dispose = function () {
  85760. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  85761. this._onBeginFrameObserver = null;
  85762. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  85763. this._onEndFrameObserver = null;
  85764. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  85765. this._onBeforeShaderCompilationObserver = null;
  85766. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  85767. this._onAfterShaderCompilationObserver = null;
  85768. this.engine = null;
  85769. };
  85770. return EngineInstrumentation;
  85771. }());
  85772. BABYLON.EngineInstrumentation = EngineInstrumentation;
  85773. })(BABYLON || (BABYLON = {}));
  85774. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  85775. var BABYLON;
  85776. (function (BABYLON) {
  85777. /**
  85778. * This class can be used to get instrumentation data from a Babylon engine
  85779. */
  85780. var SceneInstrumentation = /** @class */ (function () {
  85781. function SceneInstrumentation(scene) {
  85782. var _this = this;
  85783. this.scene = scene;
  85784. this._captureActiveMeshesEvaluationTime = false;
  85785. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  85786. this._captureRenderTargetsRenderTime = false;
  85787. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  85788. this._captureFrameTime = false;
  85789. this._frameTime = new BABYLON.PerfCounter();
  85790. this._captureRenderTime = false;
  85791. this._renderTime = new BABYLON.PerfCounter();
  85792. this._captureInterFrameTime = false;
  85793. this._interFrameTime = new BABYLON.PerfCounter();
  85794. this._captureParticlesRenderTime = false;
  85795. this._particlesRenderTime = new BABYLON.PerfCounter();
  85796. this._captureSpritesRenderTime = false;
  85797. this._spritesRenderTime = new BABYLON.PerfCounter();
  85798. this._capturePhysicsTime = false;
  85799. this._physicsTime = new BABYLON.PerfCounter();
  85800. this._captureAnimationsTime = false;
  85801. this._animationsTime = new BABYLON.PerfCounter();
  85802. // Observers
  85803. this._onBeforeActiveMeshesEvaluationObserver = null;
  85804. this._onAfterActiveMeshesEvaluationObserver = null;
  85805. this._onBeforeRenderTargetsRenderObserver = null;
  85806. this._onAfterRenderTargetsRenderObserver = null;
  85807. this._onAfterRenderObserver = null;
  85808. this._onBeforeDrawPhaseObserver = null;
  85809. this._onAfterDrawPhaseObserver = null;
  85810. this._onBeforeAnimationsObserver = null;
  85811. this._onBeforeParticlesRenderingObserver = null;
  85812. this._onAfterParticlesRenderingObserver = null;
  85813. this._onBeforeSpritesRenderingObserver = null;
  85814. this._onAfterSpritesRenderingObserver = null;
  85815. this._onBeforePhysicsObserver = null;
  85816. this._onAfterPhysicsObserver = null;
  85817. this._onAfterAnimationsObserver = null;
  85818. // Before render
  85819. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  85820. if (_this._captureActiveMeshesEvaluationTime) {
  85821. _this._activeMeshesEvaluationTime.fetchNewFrame();
  85822. }
  85823. if (_this._captureRenderTargetsRenderTime) {
  85824. _this._renderTargetsRenderTime.fetchNewFrame();
  85825. }
  85826. if (_this._captureFrameTime) {
  85827. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  85828. _this._frameTime.beginMonitoring();
  85829. }
  85830. if (_this._captureInterFrameTime) {
  85831. _this._interFrameTime.endMonitoring();
  85832. }
  85833. if (_this._captureParticlesRenderTime) {
  85834. _this._particlesRenderTime.fetchNewFrame();
  85835. }
  85836. if (_this._captureSpritesRenderTime) {
  85837. _this._spritesRenderTime.fetchNewFrame();
  85838. }
  85839. if (_this._captureAnimationsTime) {
  85840. _this._animationsTime.beginMonitoring();
  85841. }
  85842. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  85843. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  85844. });
  85845. // After render
  85846. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  85847. if (_this._captureFrameTime) {
  85848. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  85849. _this._frameTime.endMonitoring();
  85850. }
  85851. if (_this._captureRenderTime) {
  85852. _this._renderTime.endMonitoring(false);
  85853. }
  85854. if (_this._captureInterFrameTime) {
  85855. _this._interFrameTime.beginMonitoring();
  85856. }
  85857. });
  85858. }
  85859. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  85860. // Properties
  85861. /**
  85862. * Gets the perf counter used for active meshes evaluation time
  85863. */
  85864. get: function () {
  85865. return this._activeMeshesEvaluationTime;
  85866. },
  85867. enumerable: true,
  85868. configurable: true
  85869. });
  85870. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  85871. /**
  85872. * Gets the active meshes evaluation time capture status
  85873. */
  85874. get: function () {
  85875. return this._captureActiveMeshesEvaluationTime;
  85876. },
  85877. /**
  85878. * Enable or disable the active meshes evaluation time capture
  85879. */
  85880. set: function (value) {
  85881. var _this = this;
  85882. if (value === this._captureActiveMeshesEvaluationTime) {
  85883. return;
  85884. }
  85885. this._captureActiveMeshesEvaluationTime = value;
  85886. if (value) {
  85887. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  85888. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  85889. _this._activeMeshesEvaluationTime.beginMonitoring();
  85890. });
  85891. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  85892. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  85893. _this._activeMeshesEvaluationTime.endMonitoring();
  85894. });
  85895. }
  85896. else {
  85897. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  85898. this._onBeforeActiveMeshesEvaluationObserver = null;
  85899. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  85900. this._onAfterActiveMeshesEvaluationObserver = null;
  85901. }
  85902. },
  85903. enumerable: true,
  85904. configurable: true
  85905. });
  85906. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  85907. /**
  85908. * Gets the perf counter used for render targets render time
  85909. */
  85910. get: function () {
  85911. return this._renderTargetsRenderTime;
  85912. },
  85913. enumerable: true,
  85914. configurable: true
  85915. });
  85916. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  85917. /**
  85918. * Gets the render targets render time capture status
  85919. */
  85920. get: function () {
  85921. return this._captureRenderTargetsRenderTime;
  85922. },
  85923. /**
  85924. * Enable or disable the render targets render time capture
  85925. */
  85926. set: function (value) {
  85927. var _this = this;
  85928. if (value === this._captureRenderTargetsRenderTime) {
  85929. return;
  85930. }
  85931. this._captureRenderTargetsRenderTime = value;
  85932. if (value) {
  85933. this._onBeforeRenderTargetsRenderObserver = this.scene.OnBeforeRenderTargetsRenderObservable.add(function () {
  85934. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  85935. _this._renderTargetsRenderTime.beginMonitoring();
  85936. });
  85937. this._onAfterRenderTargetsRenderObserver = this.scene.OnAfterRenderTargetsRenderObservable.add(function () {
  85938. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  85939. _this._renderTargetsRenderTime.endMonitoring(false);
  85940. });
  85941. }
  85942. else {
  85943. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  85944. this._onBeforeRenderTargetsRenderObserver = null;
  85945. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  85946. this._onAfterRenderTargetsRenderObserver = null;
  85947. }
  85948. },
  85949. enumerable: true,
  85950. configurable: true
  85951. });
  85952. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  85953. /**
  85954. * Gets the perf counter used for particles render time
  85955. */
  85956. get: function () {
  85957. return this._particlesRenderTime;
  85958. },
  85959. enumerable: true,
  85960. configurable: true
  85961. });
  85962. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  85963. /**
  85964. * Gets the particles render time capture status
  85965. */
  85966. get: function () {
  85967. return this._captureParticlesRenderTime;
  85968. },
  85969. /**
  85970. * Enable or disable the particles render time capture
  85971. */
  85972. set: function (value) {
  85973. var _this = this;
  85974. if (value === this._captureParticlesRenderTime) {
  85975. return;
  85976. }
  85977. this._captureParticlesRenderTime = value;
  85978. if (value) {
  85979. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  85980. BABYLON.Tools.StartPerformanceCounter("Particles");
  85981. _this._particlesRenderTime.beginMonitoring();
  85982. });
  85983. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  85984. BABYLON.Tools.EndPerformanceCounter("Particles");
  85985. _this._particlesRenderTime.endMonitoring(false);
  85986. });
  85987. }
  85988. else {
  85989. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  85990. this._onBeforeParticlesRenderingObserver = null;
  85991. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  85992. this._onAfterParticlesRenderingObserver = null;
  85993. }
  85994. },
  85995. enumerable: true,
  85996. configurable: true
  85997. });
  85998. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  85999. /**
  86000. * Gets the perf counter used for sprites render time
  86001. */
  86002. get: function () {
  86003. return this._spritesRenderTime;
  86004. },
  86005. enumerable: true,
  86006. configurable: true
  86007. });
  86008. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  86009. /**
  86010. * Gets the sprites render time capture status
  86011. */
  86012. get: function () {
  86013. return this._captureSpritesRenderTime;
  86014. },
  86015. /**
  86016. * Enable or disable the sprites render time capture
  86017. */
  86018. set: function (value) {
  86019. var _this = this;
  86020. if (value === this._captureSpritesRenderTime) {
  86021. return;
  86022. }
  86023. this._captureSpritesRenderTime = value;
  86024. if (value) {
  86025. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  86026. BABYLON.Tools.StartPerformanceCounter("Sprites");
  86027. _this._spritesRenderTime.beginMonitoring();
  86028. });
  86029. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  86030. BABYLON.Tools.EndPerformanceCounter("Sprites");
  86031. _this._spritesRenderTime.endMonitoring(false);
  86032. });
  86033. }
  86034. else {
  86035. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  86036. this._onBeforeSpritesRenderingObserver = null;
  86037. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  86038. this._onAfterSpritesRenderingObserver = null;
  86039. }
  86040. },
  86041. enumerable: true,
  86042. configurable: true
  86043. });
  86044. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  86045. /**
  86046. * Gets the perf counter used for physics time
  86047. */
  86048. get: function () {
  86049. return this._physicsTime;
  86050. },
  86051. enumerable: true,
  86052. configurable: true
  86053. });
  86054. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  86055. /**
  86056. * Gets the physics time capture status
  86057. */
  86058. get: function () {
  86059. return this._capturePhysicsTime;
  86060. },
  86061. /**
  86062. * Enable or disable the physics time capture
  86063. */
  86064. set: function (value) {
  86065. var _this = this;
  86066. if (value === this._capturePhysicsTime) {
  86067. return;
  86068. }
  86069. this._capturePhysicsTime = value;
  86070. if (value) {
  86071. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  86072. BABYLON.Tools.StartPerformanceCounter("Physics");
  86073. _this._physicsTime.beginMonitoring();
  86074. });
  86075. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  86076. BABYLON.Tools.EndPerformanceCounter("Physics");
  86077. _this._physicsTime.endMonitoring();
  86078. });
  86079. }
  86080. else {
  86081. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  86082. this._onBeforePhysicsObserver = null;
  86083. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  86084. this._onAfterPhysicsObserver = null;
  86085. }
  86086. },
  86087. enumerable: true,
  86088. configurable: true
  86089. });
  86090. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  86091. /**
  86092. * Gets the perf counter used for animations time
  86093. */
  86094. get: function () {
  86095. return this._animationsTime;
  86096. },
  86097. enumerable: true,
  86098. configurable: true
  86099. });
  86100. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  86101. /**
  86102. * Gets the animations time capture status
  86103. */
  86104. get: function () {
  86105. return this._captureAnimationsTime;
  86106. },
  86107. /**
  86108. * Enable or disable the animations time capture
  86109. */
  86110. set: function (value) {
  86111. var _this = this;
  86112. if (value === this._captureAnimationsTime) {
  86113. return;
  86114. }
  86115. this._captureAnimationsTime = value;
  86116. if (value) {
  86117. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  86118. _this._animationsTime.endMonitoring();
  86119. });
  86120. }
  86121. else {
  86122. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  86123. this._onAfterAnimationsObserver = null;
  86124. }
  86125. },
  86126. enumerable: true,
  86127. configurable: true
  86128. });
  86129. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  86130. /**
  86131. * Gets the perf counter used for frame time capture
  86132. */
  86133. get: function () {
  86134. return this._frameTime;
  86135. },
  86136. enumerable: true,
  86137. configurable: true
  86138. });
  86139. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  86140. /**
  86141. * Gets the frame time capture status
  86142. */
  86143. get: function () {
  86144. return this._captureFrameTime;
  86145. },
  86146. /**
  86147. * Enable or disable the frame time capture
  86148. */
  86149. set: function (value) {
  86150. this._captureFrameTime = value;
  86151. },
  86152. enumerable: true,
  86153. configurable: true
  86154. });
  86155. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  86156. /**
  86157. * Gets the perf counter used for inter-frames time capture
  86158. */
  86159. get: function () {
  86160. return this._interFrameTime;
  86161. },
  86162. enumerable: true,
  86163. configurable: true
  86164. });
  86165. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  86166. /**
  86167. * Gets the inter-frames time capture status
  86168. */
  86169. get: function () {
  86170. return this._captureInterFrameTime;
  86171. },
  86172. /**
  86173. * Enable or disable the inter-frames time capture
  86174. */
  86175. set: function (value) {
  86176. this._captureInterFrameTime = value;
  86177. },
  86178. enumerable: true,
  86179. configurable: true
  86180. });
  86181. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  86182. /**
  86183. * Gets the perf counter used for render time capture
  86184. */
  86185. get: function () {
  86186. return this._renderTime;
  86187. },
  86188. enumerable: true,
  86189. configurable: true
  86190. });
  86191. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  86192. /**
  86193. * Gets the render time capture status
  86194. */
  86195. get: function () {
  86196. return this._captureRenderTime;
  86197. },
  86198. /**
  86199. * Enable or disable the render time capture
  86200. */
  86201. set: function (value) {
  86202. var _this = this;
  86203. if (value === this._captureRenderTime) {
  86204. return;
  86205. }
  86206. this._captureRenderTime = value;
  86207. if (value) {
  86208. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  86209. _this._renderTime.beginMonitoring();
  86210. BABYLON.Tools.StartPerformanceCounter("Main render");
  86211. });
  86212. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  86213. _this._renderTime.endMonitoring(false);
  86214. BABYLON.Tools.EndPerformanceCounter("Main render");
  86215. });
  86216. }
  86217. else {
  86218. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  86219. this._onBeforeDrawPhaseObserver = null;
  86220. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  86221. this._onAfterDrawPhaseObserver = null;
  86222. }
  86223. },
  86224. enumerable: true,
  86225. configurable: true
  86226. });
  86227. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  86228. /**
  86229. * Gets the perf counter used for draw calls
  86230. */
  86231. get: function () {
  86232. return this.scene.getEngine()._drawCalls;
  86233. },
  86234. enumerable: true,
  86235. configurable: true
  86236. });
  86237. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  86238. /**
  86239. * Gets the perf counter used for texture collisions
  86240. */
  86241. get: function () {
  86242. return this.scene.getEngine()._textureCollisions;
  86243. },
  86244. enumerable: true,
  86245. configurable: true
  86246. });
  86247. SceneInstrumentation.prototype.dispose = function () {
  86248. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  86249. this._onAfterRenderObserver = null;
  86250. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  86251. this._onBeforeActiveMeshesEvaluationObserver = null;
  86252. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  86253. this._onAfterActiveMeshesEvaluationObserver = null;
  86254. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  86255. this._onBeforeRenderTargetsRenderObserver = null;
  86256. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  86257. this._onAfterRenderTargetsRenderObserver = null;
  86258. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  86259. this._onBeforeAnimationsObserver = null;
  86260. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  86261. this._onBeforeParticlesRenderingObserver = null;
  86262. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  86263. this._onAfterParticlesRenderingObserver = null;
  86264. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  86265. this._onBeforeSpritesRenderingObserver = null;
  86266. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  86267. this._onAfterSpritesRenderingObserver = null;
  86268. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  86269. this._onBeforeDrawPhaseObserver = null;
  86270. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  86271. this._onAfterDrawPhaseObserver = null;
  86272. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  86273. this._onBeforePhysicsObserver = null;
  86274. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  86275. this._onAfterPhysicsObserver = null;
  86276. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  86277. this._onAfterAnimationsObserver = null;
  86278. this.scene = null;
  86279. };
  86280. return SceneInstrumentation;
  86281. }());
  86282. BABYLON.SceneInstrumentation = SceneInstrumentation;
  86283. })(BABYLON || (BABYLON = {}));
  86284. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  86285. var BABYLON;
  86286. (function (BABYLON) {
  86287. var _TimeToken = /** @class */ (function () {
  86288. function _TimeToken() {
  86289. this._timeElapsedQueryEnded = false;
  86290. }
  86291. return _TimeToken;
  86292. }());
  86293. BABYLON._TimeToken = _TimeToken;
  86294. })(BABYLON || (BABYLON = {}));
  86295. //# sourceMappingURL=babylon.timeToken.js.map
  86296. var BABYLON;
  86297. (function (BABYLON) {
  86298. /**
  86299. * Background material defines definition.
  86300. * @ignore Mainly internal Use
  86301. */
  86302. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  86303. __extends(BackgroundMaterialDefines, _super);
  86304. /**
  86305. * Constructor of the defines.
  86306. */
  86307. function BackgroundMaterialDefines() {
  86308. var _this = _super.call(this) || this;
  86309. /**
  86310. * True if the diffuse texture is in use.
  86311. */
  86312. _this.DIFFUSE = false;
  86313. /**
  86314. * The direct UV channel to use.
  86315. */
  86316. _this.DIFFUSEDIRECTUV = 0;
  86317. /**
  86318. * True if the diffuse texture is in gamma space.
  86319. */
  86320. _this.GAMMADIFFUSE = false;
  86321. /**
  86322. * True if the diffuse texture has opacity in the alpha channel.
  86323. */
  86324. _this.DIFFUSEHASALPHA = false;
  86325. /**
  86326. * True if you want the material to fade to transparent at grazing angle.
  86327. */
  86328. _this.OPACITYFRESNEL = false;
  86329. /**
  86330. * True if an extra blur needs to be added in the reflection.
  86331. */
  86332. _this.REFLECTIONBLUR = false;
  86333. /**
  86334. * True if you want the material to fade to reflection at grazing angle.
  86335. */
  86336. _this.REFLECTIONFRESNEL = false;
  86337. /**
  86338. * True if you want the material to falloff as far as you move away from the scene center.
  86339. */
  86340. _this.REFLECTIONFALLOFF = false;
  86341. /**
  86342. * False if the current Webgl implementation does not support the texture lod extension.
  86343. */
  86344. _this.TEXTURELODSUPPORT = false;
  86345. /**
  86346. * True to ensure the data are premultiplied.
  86347. */
  86348. _this.PREMULTIPLYALPHA = false;
  86349. /**
  86350. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  86351. */
  86352. _this.USERGBCOLOR = false;
  86353. /**
  86354. * True to add noise in order to reduce the banding effect.
  86355. */
  86356. _this.NOISE = false;
  86357. // Image Processing Configuration.
  86358. _this.IMAGEPROCESSING = false;
  86359. _this.VIGNETTE = false;
  86360. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  86361. _this.VIGNETTEBLENDMODEOPAQUE = false;
  86362. _this.TONEMAPPING = false;
  86363. _this.CONTRAST = false;
  86364. _this.COLORCURVES = false;
  86365. _this.COLORGRADING = false;
  86366. _this.COLORGRADING3D = false;
  86367. _this.SAMPLER3DGREENDEPTH = false;
  86368. _this.SAMPLER3DBGRMAP = false;
  86369. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  86370. _this.EXPOSURE = false;
  86371. // Reflection.
  86372. _this.REFLECTION = false;
  86373. _this.REFLECTIONMAP_3D = false;
  86374. _this.REFLECTIONMAP_SPHERICAL = false;
  86375. _this.REFLECTIONMAP_PLANAR = false;
  86376. _this.REFLECTIONMAP_CUBIC = false;
  86377. _this.REFLECTIONMAP_PROJECTION = false;
  86378. _this.REFLECTIONMAP_SKYBOX = false;
  86379. _this.REFLECTIONMAP_EXPLICIT = false;
  86380. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  86381. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  86382. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  86383. _this.INVERTCUBICMAP = false;
  86384. _this.REFLECTIONMAP_OPPOSITEZ = false;
  86385. _this.LODINREFLECTIONALPHA = false;
  86386. _this.GAMMAREFLECTION = false;
  86387. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  86388. // Default BJS.
  86389. _this.MAINUV1 = false;
  86390. _this.MAINUV2 = false;
  86391. _this.UV1 = false;
  86392. _this.UV2 = false;
  86393. _this.CLIPPLANE = false;
  86394. _this.POINTSIZE = false;
  86395. _this.FOG = false;
  86396. _this.NORMAL = false;
  86397. _this.NUM_BONE_INFLUENCERS = 0;
  86398. _this.BonesPerMesh = 0;
  86399. _this.INSTANCES = false;
  86400. _this.SHADOWFLOAT = false;
  86401. _this.rebuild();
  86402. return _this;
  86403. }
  86404. return BackgroundMaterialDefines;
  86405. }(BABYLON.MaterialDefines));
  86406. /**
  86407. * Background material used to create an efficient environement around your scene.
  86408. */
  86409. var BackgroundMaterial = /** @class */ (function (_super) {
  86410. __extends(BackgroundMaterial, _super);
  86411. /**
  86412. * Instantiates a Background Material in the given scene
  86413. * @param name The friendly name of the material
  86414. * @param scene The scene to add the material to
  86415. */
  86416. function BackgroundMaterial(name, scene) {
  86417. var _this = _super.call(this, name, scene) || this;
  86418. /**
  86419. * Key light Color (multiply against the R channel of the environement texture)
  86420. */
  86421. _this.primaryColor = BABYLON.Color3.White();
  86422. /**
  86423. * Key light Level (allowing HDR output of the background)
  86424. */
  86425. _this.primaryLevel = 1;
  86426. /**
  86427. * Secondary light Color (multiply against the G channel of the environement texture)
  86428. */
  86429. _this.secondaryColor = BABYLON.Color3.Gray();
  86430. /**
  86431. * Secondary light Level (allowing HDR output of the background)
  86432. */
  86433. _this.secondaryLevel = 1;
  86434. /**
  86435. * Tertiary light Color (multiply against the B channel of the environement texture)
  86436. */
  86437. _this.tertiaryColor = BABYLON.Color3.Black();
  86438. /**
  86439. * Tertiary light Level (allowing HDR output of the background)
  86440. */
  86441. _this.tertiaryLevel = 1;
  86442. /**
  86443. * Reflection Texture used in the material.
  86444. * Should be author in a specific way for the best result (refer to the documentation).
  86445. */
  86446. _this.reflectionTexture = null;
  86447. /**
  86448. * Reflection Texture level of blur.
  86449. *
  86450. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  86451. * texture twice.
  86452. */
  86453. _this.reflectionBlur = 0;
  86454. /**
  86455. * Diffuse Texture used in the material.
  86456. * Should be author in a specific way for the best result (refer to the documentation).
  86457. */
  86458. _this.diffuseTexture = null;
  86459. _this._shadowLights = null;
  86460. /**
  86461. * Specify the list of lights casting shadow on the material.
  86462. * All scene shadow lights will be included if null.
  86463. */
  86464. _this.shadowLights = null;
  86465. /**
  86466. * For the lights having a blurred shadow generator, this can add a second blur pass in order to reach
  86467. * soft lighting on the background.
  86468. */
  86469. _this.shadowBlurScale = 1;
  86470. /**
  86471. * Helps adjusting the shadow to a softer level if required.
  86472. * 0 means black shadows and 1 means no shadows.
  86473. */
  86474. _this.shadowLevel = 0;
  86475. /**
  86476. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  86477. * It is usually zero but might be interesting to modify according to your setup.
  86478. */
  86479. _this.sceneCenter = BABYLON.Vector3.Zero();
  86480. /**
  86481. * This helps specifying that the material is falling off to the sky box at grazing angle.
  86482. * This helps ensuring a nice transition when the camera goes under the ground.
  86483. */
  86484. _this.opacityFresnel = true;
  86485. /**
  86486. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  86487. * This helps adding a mirror texture on the ground.
  86488. */
  86489. _this.reflectionFresnel = false;
  86490. /**
  86491. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  86492. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  86493. */
  86494. _this.reflectionFalloffDistance = 0.0;
  86495. /**
  86496. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  86497. */
  86498. _this.reflectionAmount = 1.0;
  86499. /**
  86500. * This specifies the weight of the reflection at grazing angle.
  86501. */
  86502. _this.reflectionReflectance0 = 0.05;
  86503. /**
  86504. * This specifies the weight of the reflection at a perpendicular point of view.
  86505. */
  86506. _this.reflectionReflectance90 = 0.5;
  86507. /**
  86508. * Helps to directly use the maps channels instead of their level.
  86509. */
  86510. _this.useRGBColor = true;
  86511. /**
  86512. * This helps reducing the banding effect that could occur on the background.
  86513. */
  86514. _this.enableNoise = false;
  86515. _this._fovMultiplier = 1.0;
  86516. /**
  86517. * Enable the FOV adjustment feature controlled by fovMultiplier.
  86518. * @type {boolean}
  86519. */
  86520. _this.useEquirectangularFOV = false;
  86521. _this._maxSimultaneousLights = 4;
  86522. /**
  86523. * Number of Simultaneous lights allowed on the material.
  86524. */
  86525. _this.maxSimultaneousLights = 4;
  86526. /**
  86527. * Keep track of the image processing observer to allow dispose and replace.
  86528. */
  86529. _this._imageProcessingObserver = null;
  86530. // Temp values kept as cache in the material.
  86531. _this._renderTargets = new BABYLON.SmartArray(16);
  86532. _this._reflectionControls = BABYLON.Vector4.Zero();
  86533. // Setup the default processing configuration to the scene.
  86534. _this._attachImageProcessingConfiguration(null);
  86535. _this.getRenderTargetTextures = function () {
  86536. _this._renderTargets.reset();
  86537. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  86538. _this._renderTargets.push(_this._diffuseTexture);
  86539. }
  86540. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  86541. _this._renderTargets.push(_this._reflectionTexture);
  86542. }
  86543. return _this._renderTargets;
  86544. };
  86545. return _this;
  86546. }
  86547. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  86548. /**
  86549. * Sets the reflection reflectance fresnel values according to the default standard
  86550. * empirically know to work well :-)
  86551. */
  86552. set: function (value) {
  86553. var reflectionWeight = value;
  86554. if (reflectionWeight < 0.5) {
  86555. reflectionWeight = reflectionWeight * 2.0;
  86556. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  86557. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  86558. }
  86559. else {
  86560. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  86561. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  86562. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  86563. }
  86564. },
  86565. enumerable: true,
  86566. configurable: true
  86567. });
  86568. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  86569. /**
  86570. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  86571. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  86572. * Recommended to be keep at 1.0 except for special cases.
  86573. */
  86574. get: function () {
  86575. return this._fovMultiplier;
  86576. },
  86577. set: function (value) {
  86578. if (isNaN(value)) {
  86579. value = 1.0;
  86580. }
  86581. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  86582. },
  86583. enumerable: true,
  86584. configurable: true
  86585. });
  86586. /**
  86587. * Attaches a new image processing configuration to the PBR Material.
  86588. * @param configuration (if null the scene configuration will be use)
  86589. */
  86590. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  86591. var _this = this;
  86592. if (configuration === this._imageProcessingConfiguration) {
  86593. return;
  86594. }
  86595. // Detaches observer.
  86596. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  86597. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  86598. }
  86599. // Pick the scene configuration if needed.
  86600. if (!configuration) {
  86601. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  86602. }
  86603. else {
  86604. this._imageProcessingConfiguration = configuration;
  86605. }
  86606. // Attaches observer.
  86607. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  86608. _this._markAllSubMeshesAsImageProcessingDirty();
  86609. });
  86610. };
  86611. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  86612. /**
  86613. * Gets the image processing configuration used either in this material.
  86614. */
  86615. get: function () {
  86616. return this._imageProcessingConfiguration;
  86617. },
  86618. /**
  86619. * Sets the Default image processing configuration used either in the this material.
  86620. *
  86621. * If sets to null, the scene one is in use.
  86622. */
  86623. set: function (value) {
  86624. this._attachImageProcessingConfiguration(value);
  86625. // Ensure the effect will be rebuilt.
  86626. this._markAllSubMeshesAsTexturesDirty();
  86627. },
  86628. enumerable: true,
  86629. configurable: true
  86630. });
  86631. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  86632. /**
  86633. * Gets wether the color curves effect is enabled.
  86634. */
  86635. get: function () {
  86636. return this.imageProcessingConfiguration.colorCurvesEnabled;
  86637. },
  86638. /**
  86639. * Sets wether the color curves effect is enabled.
  86640. */
  86641. set: function (value) {
  86642. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  86643. },
  86644. enumerable: true,
  86645. configurable: true
  86646. });
  86647. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  86648. /**
  86649. * Gets wether the color grading effect is enabled.
  86650. */
  86651. get: function () {
  86652. return this.imageProcessingConfiguration.colorGradingEnabled;
  86653. },
  86654. /**
  86655. * Gets wether the color grading effect is enabled.
  86656. */
  86657. set: function (value) {
  86658. this.imageProcessingConfiguration.colorGradingEnabled = value;
  86659. },
  86660. enumerable: true,
  86661. configurable: true
  86662. });
  86663. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  86664. /**
  86665. * Gets wether tonemapping is enabled or not.
  86666. */
  86667. get: function () {
  86668. return this._imageProcessingConfiguration.toneMappingEnabled;
  86669. },
  86670. /**
  86671. * Sets wether tonemapping is enabled or not
  86672. */
  86673. set: function (value) {
  86674. this._imageProcessingConfiguration.toneMappingEnabled = value;
  86675. },
  86676. enumerable: true,
  86677. configurable: true
  86678. });
  86679. ;
  86680. ;
  86681. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  86682. /**
  86683. * The camera exposure used on this material.
  86684. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  86685. * This corresponds to a photographic exposure.
  86686. */
  86687. get: function () {
  86688. return this._imageProcessingConfiguration.exposure;
  86689. },
  86690. /**
  86691. * The camera exposure used on this material.
  86692. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  86693. * This corresponds to a photographic exposure.
  86694. */
  86695. set: function (value) {
  86696. this._imageProcessingConfiguration.exposure = value;
  86697. },
  86698. enumerable: true,
  86699. configurable: true
  86700. });
  86701. ;
  86702. ;
  86703. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  86704. /**
  86705. * Gets The camera contrast used on this material.
  86706. */
  86707. get: function () {
  86708. return this._imageProcessingConfiguration.contrast;
  86709. },
  86710. /**
  86711. * Sets The camera contrast used on this material.
  86712. */
  86713. set: function (value) {
  86714. this._imageProcessingConfiguration.contrast = value;
  86715. },
  86716. enumerable: true,
  86717. configurable: true
  86718. });
  86719. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  86720. /**
  86721. * Gets the Color Grading 2D Lookup Texture.
  86722. */
  86723. get: function () {
  86724. return this._imageProcessingConfiguration.colorGradingTexture;
  86725. },
  86726. /**
  86727. * Sets the Color Grading 2D Lookup Texture.
  86728. */
  86729. set: function (value) {
  86730. this.imageProcessingConfiguration.colorGradingTexture = value;
  86731. },
  86732. enumerable: true,
  86733. configurable: true
  86734. });
  86735. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  86736. /**
  86737. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  86738. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  86739. * 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;
  86740. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  86741. */
  86742. get: function () {
  86743. return this.imageProcessingConfiguration.colorCurves;
  86744. },
  86745. /**
  86746. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  86747. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  86748. * 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;
  86749. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  86750. */
  86751. set: function (value) {
  86752. this.imageProcessingConfiguration.colorCurves = value;
  86753. },
  86754. enumerable: true,
  86755. configurable: true
  86756. });
  86757. /**
  86758. * The entire material has been created in order to prevent overdraw.
  86759. * @returns false
  86760. */
  86761. BackgroundMaterial.prototype.needAlphaTesting = function () {
  86762. return true;
  86763. };
  86764. /**
  86765. * The entire material has been created in order to prevent overdraw.
  86766. * @returns true if blending is enable
  86767. */
  86768. BackgroundMaterial.prototype.needAlphaBlending = function () {
  86769. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  86770. };
  86771. /**
  86772. * Checks wether the material is ready to be rendered for a given mesh.
  86773. * @param mesh The mesh to render
  86774. * @param subMesh The submesh to check against
  86775. * @param useInstances Specify wether or not the material is used with instances
  86776. * @returns true if all the dependencies are ready (Textures, Effects...)
  86777. */
  86778. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  86779. var _this = this;
  86780. if (useInstances === void 0) { useInstances = false; }
  86781. if (subMesh.effect && this.isFrozen) {
  86782. if (this._wasPreviouslyReady) {
  86783. return true;
  86784. }
  86785. }
  86786. if (!subMesh._materialDefines) {
  86787. subMesh._materialDefines = new BackgroundMaterialDefines();
  86788. }
  86789. var scene = this.getScene();
  86790. var defines = subMesh._materialDefines;
  86791. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  86792. if (defines._renderId === scene.getRenderId()) {
  86793. return true;
  86794. }
  86795. }
  86796. var engine = scene.getEngine();
  86797. // Lights
  86798. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  86799. defines._needNormals = true;
  86800. // Textures
  86801. if (defines._areTexturesDirty) {
  86802. defines._needUVs = false;
  86803. if (scene.texturesEnabled) {
  86804. if (scene.getEngine().getCaps().textureLOD) {
  86805. defines.TEXTURELODSUPPORT = true;
  86806. }
  86807. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  86808. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  86809. return false;
  86810. }
  86811. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  86812. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  86813. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  86814. defines.OPACITYFRESNEL = this._opacityFresnel;
  86815. }
  86816. else {
  86817. defines.DIFFUSE = false;
  86818. defines.DIFFUSEHASALPHA = false;
  86819. defines.GAMMADIFFUSE = false;
  86820. defines.OPACITYFRESNEL = false;
  86821. }
  86822. var reflectionTexture = this._reflectionTexture;
  86823. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  86824. if (!reflectionTexture.isReadyOrNotBlocking()) {
  86825. return false;
  86826. }
  86827. defines.REFLECTION = true;
  86828. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  86829. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  86830. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  86831. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  86832. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  86833. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  86834. defines.INVERTCUBICMAP = true;
  86835. }
  86836. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  86837. switch (reflectionTexture.coordinatesMode) {
  86838. case BABYLON.Texture.CUBIC_MODE:
  86839. case BABYLON.Texture.INVCUBIC_MODE:
  86840. defines.REFLECTIONMAP_CUBIC = true;
  86841. break;
  86842. case BABYLON.Texture.EXPLICIT_MODE:
  86843. defines.REFLECTIONMAP_EXPLICIT = true;
  86844. break;
  86845. case BABYLON.Texture.PLANAR_MODE:
  86846. defines.REFLECTIONMAP_PLANAR = true;
  86847. break;
  86848. case BABYLON.Texture.PROJECTION_MODE:
  86849. defines.REFLECTIONMAP_PROJECTION = true;
  86850. break;
  86851. case BABYLON.Texture.SKYBOX_MODE:
  86852. defines.REFLECTIONMAP_SKYBOX = true;
  86853. break;
  86854. case BABYLON.Texture.SPHERICAL_MODE:
  86855. defines.REFLECTIONMAP_SPHERICAL = true;
  86856. break;
  86857. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  86858. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  86859. break;
  86860. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  86861. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  86862. break;
  86863. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  86864. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  86865. break;
  86866. }
  86867. if (this.reflectionFresnel) {
  86868. defines.REFLECTIONFRESNEL = true;
  86869. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  86870. this._reflectionControls.x = this.reflectionAmount;
  86871. this._reflectionControls.y = this.reflectionReflectance0;
  86872. this._reflectionControls.z = this.reflectionReflectance90;
  86873. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  86874. }
  86875. else {
  86876. defines.REFLECTIONFRESNEL = false;
  86877. defines.REFLECTIONFALLOFF = false;
  86878. }
  86879. }
  86880. else {
  86881. defines.REFLECTION = false;
  86882. defines.REFLECTIONFALLOFF = false;
  86883. defines.REFLECTIONBLUR = false;
  86884. defines.REFLECTIONMAP_3D = false;
  86885. defines.REFLECTIONMAP_SPHERICAL = false;
  86886. defines.REFLECTIONMAP_PLANAR = false;
  86887. defines.REFLECTIONMAP_CUBIC = false;
  86888. defines.REFLECTIONMAP_PROJECTION = false;
  86889. defines.REFLECTIONMAP_SKYBOX = false;
  86890. defines.REFLECTIONMAP_EXPLICIT = false;
  86891. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  86892. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  86893. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  86894. defines.INVERTCUBICMAP = false;
  86895. defines.REFLECTIONMAP_OPPOSITEZ = false;
  86896. defines.LODINREFLECTIONALPHA = false;
  86897. defines.GAMMAREFLECTION = false;
  86898. }
  86899. }
  86900. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  86901. defines.USERGBCOLOR = this._useRGBColor;
  86902. defines.NOISE = this._enableNoise;
  86903. }
  86904. if (defines._areImageProcessingDirty) {
  86905. if (!this._imageProcessingConfiguration.isReady()) {
  86906. return false;
  86907. }
  86908. this._imageProcessingConfiguration.prepareDefines(defines);
  86909. }
  86910. // Misc.
  86911. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  86912. // Values that need to be evaluated on every frame
  86913. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  86914. // Attribs
  86915. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  86916. if (mesh) {
  86917. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  86918. mesh.createNormals(true);
  86919. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  86920. }
  86921. }
  86922. }
  86923. // Get correct effect
  86924. if (defines.isDirty) {
  86925. defines.markAsProcessed();
  86926. scene.resetCachedMaterial();
  86927. // Fallbacks
  86928. var fallbacks = new BABYLON.EffectFallbacks();
  86929. if (defines.FOG) {
  86930. fallbacks.addFallback(0, "FOG");
  86931. }
  86932. if (defines.POINTSIZE) {
  86933. fallbacks.addFallback(1, "POINTSIZE");
  86934. }
  86935. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  86936. if (defines.NUM_BONE_INFLUENCERS > 0) {
  86937. fallbacks.addCPUSkinningFallback(0, mesh);
  86938. }
  86939. //Attributes
  86940. var attribs = [BABYLON.VertexBuffer.PositionKind];
  86941. if (defines.NORMAL) {
  86942. attribs.push(BABYLON.VertexBuffer.NormalKind);
  86943. }
  86944. if (defines.UV1) {
  86945. attribs.push(BABYLON.VertexBuffer.UVKind);
  86946. }
  86947. if (defines.UV2) {
  86948. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  86949. }
  86950. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  86951. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  86952. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  86953. "vFogInfos", "vFogColor", "pointSize",
  86954. "vClipPlane", "mBones",
  86955. "vPrimaryColor", "vSecondaryColor", "vTertiaryColor",
  86956. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  86957. "shadowLevel", "alpha",
  86958. "vBackgroundCenter", "vReflectionControl",
  86959. "vDiffuseInfos", "diffuseMatrix",
  86960. ];
  86961. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  86962. var uniformBuffers = ["Material", "Scene"];
  86963. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  86964. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  86965. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  86966. uniformsNames: uniforms,
  86967. uniformBuffersNames: uniformBuffers,
  86968. samplers: samplers,
  86969. defines: defines,
  86970. maxSimultaneousLights: this._maxSimultaneousLights
  86971. });
  86972. var onCompiled = function (effect) {
  86973. if (_this.onCompiled) {
  86974. _this.onCompiled(effect);
  86975. }
  86976. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  86977. };
  86978. var join = defines.toString();
  86979. subMesh.setEffect(scene.getEngine().createEffect("background", {
  86980. attributes: attribs,
  86981. uniformsNames: uniforms,
  86982. uniformBuffersNames: uniformBuffers,
  86983. samplers: samplers,
  86984. defines: join,
  86985. fallbacks: fallbacks,
  86986. onCompiled: onCompiled,
  86987. onError: this.onError,
  86988. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  86989. }, engine), defines);
  86990. this.buildUniformLayout();
  86991. }
  86992. if (!subMesh.effect || !subMesh.effect.isReady()) {
  86993. return false;
  86994. }
  86995. defines._renderId = scene.getRenderId();
  86996. this._wasPreviouslyReady = true;
  86997. return true;
  86998. };
  86999. /**
  87000. * Build the uniform buffer used in the material.
  87001. */
  87002. BackgroundMaterial.prototype.buildUniformLayout = function () {
  87003. // Order is important !
  87004. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  87005. this._uniformBuffer.addUniform("vSecondaryColor", 4);
  87006. this._uniformBuffer.addUniform("vTertiaryColor", 4);
  87007. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  87008. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  87009. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  87010. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  87011. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  87012. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  87013. this._uniformBuffer.addUniform("pointSize", 1);
  87014. this._uniformBuffer.addUniform("shadowLevel", 1);
  87015. this._uniformBuffer.addUniform("alpha", 1);
  87016. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  87017. this._uniformBuffer.addUniform("vReflectionControl", 4);
  87018. this._uniformBuffer.create();
  87019. };
  87020. /**
  87021. * Unbind the material.
  87022. */
  87023. BackgroundMaterial.prototype.unbind = function () {
  87024. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  87025. this._uniformBuffer.setTexture("diffuseSampler", null);
  87026. }
  87027. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  87028. this._uniformBuffer.setTexture("reflectionSampler", null);
  87029. }
  87030. _super.prototype.unbind.call(this);
  87031. };
  87032. /**
  87033. * Bind only the world matrix to the material.
  87034. * @param world The world matrix to bind.
  87035. */
  87036. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  87037. this._activeEffect.setMatrix("world", world);
  87038. };
  87039. /**
  87040. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  87041. * @param world The world matrix to bind.
  87042. * @param subMesh The submesh to bind for.
  87043. */
  87044. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  87045. var scene = this.getScene();
  87046. var defines = subMesh._materialDefines;
  87047. if (!defines) {
  87048. return;
  87049. }
  87050. var effect = subMesh.effect;
  87051. if (!effect) {
  87052. return;
  87053. }
  87054. this._activeEffect = effect;
  87055. // Matrices
  87056. this.bindOnlyWorldMatrix(world);
  87057. // Bones
  87058. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  87059. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  87060. if (mustRebind) {
  87061. this._uniformBuffer.bindToEffect(effect, "Material");
  87062. this.bindViewProjection(effect);
  87063. var reflectionTexture = this._reflectionTexture;
  87064. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  87065. // Texture uniforms
  87066. if (scene.texturesEnabled) {
  87067. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  87068. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  87069. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  87070. }
  87071. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  87072. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  87073. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  87074. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  87075. }
  87076. }
  87077. if (this.shadowLevel > 0) {
  87078. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  87079. }
  87080. this._uniformBuffer.updateFloat("alpha", this.alpha);
  87081. // Point size
  87082. if (this.pointsCloud) {
  87083. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  87084. }
  87085. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, this._primaryLevel);
  87086. this._uniformBuffer.updateColor4("vSecondaryColor", this._secondaryColor, this._secondaryLevel);
  87087. this._uniformBuffer.updateColor4("vTertiaryColor", this._tertiaryColor, this._tertiaryLevel);
  87088. }
  87089. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  87090. // Textures
  87091. if (scene.texturesEnabled) {
  87092. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  87093. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  87094. }
  87095. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  87096. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  87097. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  87098. }
  87099. else if (!defines.REFLECTIONBLUR) {
  87100. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  87101. }
  87102. else {
  87103. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  87104. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  87105. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  87106. }
  87107. if (defines.REFLECTIONFRESNEL) {
  87108. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  87109. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  87110. }
  87111. }
  87112. }
  87113. // Clip plane
  87114. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  87115. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  87116. }
  87117. if (mustRebind || !this.isFrozen) {
  87118. if (scene.lightsEnabled) {
  87119. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  87120. }
  87121. // View
  87122. this.bindView(effect);
  87123. // Fog
  87124. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  87125. // image processing
  87126. this._imageProcessingConfiguration.bind(this._activeEffect);
  87127. }
  87128. this._uniformBuffer.update();
  87129. this._afterBind(mesh);
  87130. };
  87131. /**
  87132. * Dispose the material.
  87133. * @param forceDisposeEffect Force disposal of the associated effect.
  87134. * @param forceDisposeTextures Force disposal of the associated textures.
  87135. */
  87136. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  87137. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  87138. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  87139. if (forceDisposeTextures) {
  87140. if (this.diffuseTexture) {
  87141. this.diffuseTexture.dispose();
  87142. }
  87143. if (this.reflectionTexture) {
  87144. this.reflectionTexture.dispose();
  87145. }
  87146. }
  87147. this._renderTargets.dispose();
  87148. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  87149. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  87150. }
  87151. _super.prototype.dispose.call(this, forceDisposeEffect);
  87152. };
  87153. /**
  87154. * Clones the material.
  87155. * @param name The cloned name.
  87156. * @returns The cloned material.
  87157. */
  87158. BackgroundMaterial.prototype.clone = function (name) {
  87159. var _this = this;
  87160. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  87161. };
  87162. /**
  87163. * Serializes the current material to its JSON representation.
  87164. * @returns The JSON representation.
  87165. */
  87166. BackgroundMaterial.prototype.serialize = function () {
  87167. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  87168. serializationObject.customType = "BABYLON.BackgroundMaterial";
  87169. return serializationObject;
  87170. };
  87171. /**
  87172. * Gets the class name of the material
  87173. * @returns "BackgroundMaterial"
  87174. */
  87175. BackgroundMaterial.prototype.getClassName = function () {
  87176. return "BackgroundMaterial";
  87177. };
  87178. /**
  87179. * Parse a JSON input to create back a background material.
  87180. * @param source The JSON data to parse
  87181. * @param scene The scene to create the parsed material in
  87182. * @param rootUrl The root url of the assets the material depends upon
  87183. * @returns the instantiated BackgroundMaterial.
  87184. */
  87185. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  87186. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  87187. };
  87188. /**
  87189. * Standard reflectance value at parallel view angle.
  87190. */
  87191. BackgroundMaterial.StandardReflectance0 = 0.05;
  87192. /**
  87193. * Standard reflectance value at grazing angle.
  87194. */
  87195. BackgroundMaterial.StandardReflectance90 = 0.5;
  87196. __decorate([
  87197. BABYLON.serializeAsColor3()
  87198. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  87199. __decorate([
  87200. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  87201. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  87202. __decorate([
  87203. BABYLON.serialize()
  87204. ], BackgroundMaterial.prototype, "_primaryLevel", void 0);
  87205. __decorate([
  87206. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  87207. ], BackgroundMaterial.prototype, "primaryLevel", void 0);
  87208. __decorate([
  87209. BABYLON.serializeAsColor3()
  87210. ], BackgroundMaterial.prototype, "_secondaryColor", void 0);
  87211. __decorate([
  87212. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  87213. ], BackgroundMaterial.prototype, "secondaryColor", void 0);
  87214. __decorate([
  87215. BABYLON.serialize()
  87216. ], BackgroundMaterial.prototype, "_secondaryLevel", void 0);
  87217. __decorate([
  87218. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  87219. ], BackgroundMaterial.prototype, "secondaryLevel", void 0);
  87220. __decorate([
  87221. BABYLON.serializeAsColor3()
  87222. ], BackgroundMaterial.prototype, "_tertiaryColor", void 0);
  87223. __decorate([
  87224. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  87225. ], BackgroundMaterial.prototype, "tertiaryColor", void 0);
  87226. __decorate([
  87227. BABYLON.serialize()
  87228. ], BackgroundMaterial.prototype, "_tertiaryLevel", void 0);
  87229. __decorate([
  87230. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  87231. ], BackgroundMaterial.prototype, "tertiaryLevel", void 0);
  87232. __decorate([
  87233. BABYLON.serializeAsTexture()
  87234. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  87235. __decorate([
  87236. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87237. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  87238. __decorate([
  87239. BABYLON.serialize()
  87240. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  87241. __decorate([
  87242. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87243. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  87244. __decorate([
  87245. BABYLON.serializeAsTexture()
  87246. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  87247. __decorate([
  87248. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87249. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  87250. __decorate([
  87251. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87252. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  87253. __decorate([
  87254. BABYLON.serialize()
  87255. ], BackgroundMaterial.prototype, "_shadowBlurScale", void 0);
  87256. __decorate([
  87257. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87258. ], BackgroundMaterial.prototype, "shadowBlurScale", void 0);
  87259. __decorate([
  87260. BABYLON.serialize()
  87261. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  87262. __decorate([
  87263. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87264. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  87265. __decorate([
  87266. BABYLON.serializeAsVector3()
  87267. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  87268. __decorate([
  87269. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87270. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  87271. __decorate([
  87272. BABYLON.serialize()
  87273. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  87274. __decorate([
  87275. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87276. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  87277. __decorate([
  87278. BABYLON.serialize()
  87279. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  87280. __decorate([
  87281. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87282. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  87283. __decorate([
  87284. BABYLON.serialize()
  87285. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  87286. __decorate([
  87287. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87288. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  87289. __decorate([
  87290. BABYLON.serialize()
  87291. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  87292. __decorate([
  87293. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87294. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  87295. __decorate([
  87296. BABYLON.serialize()
  87297. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  87298. __decorate([
  87299. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87300. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  87301. __decorate([
  87302. BABYLON.serialize()
  87303. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  87304. __decorate([
  87305. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87306. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  87307. __decorate([
  87308. BABYLON.serialize()
  87309. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  87310. __decorate([
  87311. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87312. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  87313. __decorate([
  87314. BABYLON.serialize()
  87315. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  87316. __decorate([
  87317. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87318. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  87319. __decorate([
  87320. BABYLON.serialize()
  87321. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  87322. __decorate([
  87323. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87324. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  87325. __decorate([
  87326. BABYLON.serializeAsImageProcessingConfiguration()
  87327. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  87328. return BackgroundMaterial;
  87329. }(BABYLON.PushMaterial));
  87330. BABYLON.BackgroundMaterial = BackgroundMaterial;
  87331. })(BABYLON || (BABYLON = {}));
  87332. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  87333. var __assign = (this && this.__assign) || Object.assign || function(t) {
  87334. for (var s, i = 1, n = arguments.length; i < n; i++) {
  87335. s = arguments[i];
  87336. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  87337. t[p] = s[p];
  87338. }
  87339. return t;
  87340. };
  87341. var BABYLON;
  87342. (function (BABYLON) {
  87343. /**
  87344. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  87345. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  87346. * It also helps with the default setup of your imageProcessing configuration.
  87347. */
  87348. var EnvironmentHelper = /** @class */ (function () {
  87349. /**
  87350. * constructor
  87351. * @param options
  87352. * @param scene The scene to add the material to
  87353. */
  87354. function EnvironmentHelper(options, scene) {
  87355. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  87356. this._scene = scene;
  87357. this._setupBackground();
  87358. this._setupImageProcessing();
  87359. }
  87360. /**
  87361. * Creates the default options for the helper.
  87362. */
  87363. EnvironmentHelper._getDefaultOptions = function () {
  87364. return {
  87365. createGround: true,
  87366. groundSize: 15,
  87367. groundTexture: this._groundTextureCDNUrl,
  87368. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  87369. groundOpacity: 0.9,
  87370. enableGroundShadow: true,
  87371. groundShadowLevel: 0.5,
  87372. enableGroundMirror: false,
  87373. groundMirrorSizeRatio: 0.3,
  87374. groundMirrorBlurKernel: 64,
  87375. groundMirrorAmount: 1,
  87376. groundMirrorFresnelWeight: 1,
  87377. groundMirrorFallOffDistance: 0,
  87378. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  87379. groundYBias: 0.00001,
  87380. createSkybox: true,
  87381. skyboxSize: 20,
  87382. skyboxTexture: this._skyboxTextureCDNUrl,
  87383. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  87384. backgroundYRotation: 0,
  87385. sizeAuto: true,
  87386. rootPosition: BABYLON.Vector3.Zero(),
  87387. setupImageProcessing: true,
  87388. environmentTexture: this._environmentTextureCDNUrl,
  87389. cameraExposure: 0.8,
  87390. cameraContrast: 1.2,
  87391. toneMappingEnabled: true,
  87392. };
  87393. };
  87394. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  87395. /**
  87396. * Gets the root mesh created by the helper.
  87397. */
  87398. get: function () {
  87399. return this._rootMesh;
  87400. },
  87401. enumerable: true,
  87402. configurable: true
  87403. });
  87404. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  87405. /**
  87406. * Gets the skybox created by the helper.
  87407. */
  87408. get: function () {
  87409. return this._skybox;
  87410. },
  87411. enumerable: true,
  87412. configurable: true
  87413. });
  87414. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  87415. /**
  87416. * Gets the skybox texture created by the helper.
  87417. */
  87418. get: function () {
  87419. return this._skyboxTexture;
  87420. },
  87421. enumerable: true,
  87422. configurable: true
  87423. });
  87424. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  87425. /**
  87426. * Gets the skybox material created by the helper.
  87427. */
  87428. get: function () {
  87429. return this._skyboxMaterial;
  87430. },
  87431. enumerable: true,
  87432. configurable: true
  87433. });
  87434. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  87435. /**
  87436. * Gets the ground mesh created by the helper.
  87437. */
  87438. get: function () {
  87439. return this._ground;
  87440. },
  87441. enumerable: true,
  87442. configurable: true
  87443. });
  87444. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  87445. /**
  87446. * Gets the ground texture created by the helper.
  87447. */
  87448. get: function () {
  87449. return this._groundTexture;
  87450. },
  87451. enumerable: true,
  87452. configurable: true
  87453. });
  87454. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  87455. /**
  87456. * Gets the ground mirror created by the helper.
  87457. */
  87458. get: function () {
  87459. return this._groundMirror;
  87460. },
  87461. enumerable: true,
  87462. configurable: true
  87463. });
  87464. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  87465. /**
  87466. * Gets the ground mirror render list to helps pushing the meshes
  87467. * you wish in the ground reflection.
  87468. */
  87469. get: function () {
  87470. if (this._groundMirror) {
  87471. return this._groundMirror.renderList;
  87472. }
  87473. return null;
  87474. },
  87475. enumerable: true,
  87476. configurable: true
  87477. });
  87478. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  87479. /**
  87480. * Gets the ground material created by the helper.
  87481. */
  87482. get: function () {
  87483. return this._groundMaterial;
  87484. },
  87485. enumerable: true,
  87486. configurable: true
  87487. });
  87488. /**
  87489. * Updates the background according to the new options
  87490. * @param options
  87491. */
  87492. EnvironmentHelper.prototype.updateOptions = function (options) {
  87493. var newOptions = __assign({}, this._options, options);
  87494. if (this._ground && !newOptions.createGround) {
  87495. this._ground.dispose();
  87496. this._ground = null;
  87497. }
  87498. if (this._groundMaterial && !newOptions.createGround) {
  87499. this._groundMaterial.dispose();
  87500. this._groundMaterial = null;
  87501. }
  87502. if (this._groundTexture) {
  87503. if (this._options.groundTexture != newOptions.groundTexture) {
  87504. this._groundTexture.dispose();
  87505. this._groundTexture = null;
  87506. }
  87507. }
  87508. if (this._skybox && !newOptions.createSkybox) {
  87509. this._skybox.dispose();
  87510. this._skybox = null;
  87511. }
  87512. if (this._skyboxMaterial && !newOptions.createSkybox) {
  87513. this._skyboxMaterial.dispose();
  87514. this._skyboxMaterial = null;
  87515. }
  87516. if (this._skyboxTexture) {
  87517. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  87518. this._skyboxTexture.dispose();
  87519. this._skyboxTexture = null;
  87520. }
  87521. }
  87522. if (this._groundMirror && !newOptions.enableGroundMirror) {
  87523. this._groundMirror.dispose();
  87524. this._groundMirror = null;
  87525. }
  87526. if (this._scene.environmentTexture) {
  87527. if (this._options.environmentTexture != newOptions.environmentTexture) {
  87528. this._scene.environmentTexture.dispose();
  87529. }
  87530. }
  87531. this._options = newOptions;
  87532. this._setupBackground();
  87533. this._setupImageProcessing();
  87534. };
  87535. /**
  87536. * Sets the primary color of all the available elements.
  87537. * @param color
  87538. */
  87539. EnvironmentHelper.prototype.setMainColor = function (color) {
  87540. if (this.groundMaterial) {
  87541. this.groundMaterial.primaryColor = color;
  87542. }
  87543. if (this.skyboxMaterial) {
  87544. this.skyboxMaterial.primaryColor = color;
  87545. }
  87546. if (this.groundMirror) {
  87547. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  87548. }
  87549. };
  87550. /**
  87551. * Setup the image processing according to the specified options.
  87552. */
  87553. EnvironmentHelper.prototype._setupImageProcessing = function () {
  87554. if (this._options.setupImageProcessing) {
  87555. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  87556. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  87557. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  87558. this._setupEnvironmentTexture();
  87559. }
  87560. };
  87561. /**
  87562. * Setup the environment texture according to the specified options.
  87563. */
  87564. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  87565. if (this._scene.environmentTexture) {
  87566. return;
  87567. }
  87568. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  87569. this._scene.environmentTexture = this._options.environmentTexture;
  87570. return;
  87571. }
  87572. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  87573. this._scene.environmentTexture = environmentTexture;
  87574. };
  87575. /**
  87576. * Setup the background according to the specified options.
  87577. */
  87578. EnvironmentHelper.prototype._setupBackground = function () {
  87579. if (!this._rootMesh) {
  87580. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  87581. }
  87582. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  87583. var sceneSize = this._getSceneSize();
  87584. if (this._options.createGround) {
  87585. this._setupGround(sceneSize);
  87586. this._setupGroundMaterial();
  87587. this._setupGroundDiffuseTexture();
  87588. if (this._options.enableGroundMirror) {
  87589. this._setupGroundMirrorTexture(sceneSize);
  87590. }
  87591. this._setupMirrorInGroundMaterial();
  87592. }
  87593. if (this._options.createSkybox) {
  87594. this._setupSkybox(sceneSize);
  87595. this._setupSkyboxMaterial();
  87596. this._setupSkyboxReflectionTexture();
  87597. }
  87598. this._rootMesh.position.x = sceneSize.rootPosition.x;
  87599. this._rootMesh.position.z = sceneSize.rootPosition.z;
  87600. this._rootMesh.position.y = sceneSize.rootPosition.y;
  87601. };
  87602. /**
  87603. * Get the scene sizes according to the setup.
  87604. */
  87605. EnvironmentHelper.prototype._getSceneSize = function () {
  87606. var groundSize = this._options.groundSize;
  87607. var skyboxSize = this._options.skyboxSize;
  87608. var rootPosition = this._options.rootPosition;
  87609. if (!this._scene.meshes || this._scene.meshes.length === 1) {
  87610. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  87611. }
  87612. var sceneExtends = this._scene.getWorldExtends();
  87613. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  87614. if (this._options.sizeAuto) {
  87615. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  87616. this._scene.activeCamera.upperRadiusLimit) {
  87617. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  87618. skyboxSize = groundSize;
  87619. }
  87620. var sceneDiagonalLenght = sceneDiagonal.length();
  87621. if (sceneDiagonalLenght > groundSize) {
  87622. groundSize = sceneDiagonalLenght * 2;
  87623. skyboxSize = groundSize;
  87624. }
  87625. // 10 % bigger.
  87626. groundSize *= 1.1;
  87627. skyboxSize *= 1.5;
  87628. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  87629. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  87630. }
  87631. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  87632. };
  87633. /**
  87634. * Setup the ground according to the specified options.
  87635. */
  87636. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  87637. var _this = this;
  87638. if (!this._ground) {
  87639. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  87640. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  87641. this._ground.parent = this._rootMesh;
  87642. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  87643. }
  87644. this._ground.receiveShadows = this._options.enableGroundShadow;
  87645. };
  87646. /**
  87647. * Setup the ground material according to the specified options.
  87648. */
  87649. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  87650. if (!this._groundMaterial) {
  87651. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  87652. }
  87653. this._groundMaterial.alpha = this._options.groundOpacity;
  87654. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  87655. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  87656. this._groundMaterial.primaryLevel = 1;
  87657. this._groundMaterial.primaryColor = this._options.groundColor;
  87658. this._groundMaterial.secondaryLevel = 0;
  87659. this._groundMaterial.tertiaryLevel = 0;
  87660. this._groundMaterial.useRGBColor = false;
  87661. this._groundMaterial.enableNoise = true;
  87662. if (this._ground) {
  87663. this._ground.material = this._groundMaterial;
  87664. }
  87665. };
  87666. /**
  87667. * Setup the ground diffuse texture according to the specified options.
  87668. */
  87669. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  87670. if (!this._groundMaterial) {
  87671. return;
  87672. }
  87673. if (this._groundTexture) {
  87674. return;
  87675. }
  87676. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  87677. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  87678. return;
  87679. }
  87680. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene);
  87681. diffuseTexture.gammaSpace = false;
  87682. diffuseTexture.hasAlpha = true;
  87683. this._groundMaterial.diffuseTexture = diffuseTexture;
  87684. };
  87685. /**
  87686. * Setup the ground mirror texture according to the specified options.
  87687. */
  87688. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  87689. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  87690. if (!this._groundMirror) {
  87691. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  87692. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  87693. this._groundMirror.anisotropicFilteringLevel = 1;
  87694. this._groundMirror.wrapU = wrapping;
  87695. this._groundMirror.wrapV = wrapping;
  87696. this._groundMirror.gammaSpace = false;
  87697. if (this._groundMirror.renderList) {
  87698. for (var i = 0; i < this._scene.meshes.length; i++) {
  87699. var mesh = this._scene.meshes[i];
  87700. if (mesh !== this._ground &&
  87701. mesh !== this._skybox &&
  87702. mesh !== this._rootMesh) {
  87703. this._groundMirror.renderList.push(mesh);
  87704. }
  87705. }
  87706. }
  87707. }
  87708. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  87709. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  87710. };
  87711. /**
  87712. * Setup the ground to receive the mirror texture.
  87713. */
  87714. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  87715. if (this._groundMaterial) {
  87716. this._groundMaterial.reflectionTexture = this._groundMirror;
  87717. this._groundMaterial.reflectionFresnel = true;
  87718. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  87719. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  87720. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  87721. }
  87722. };
  87723. /**
  87724. * Setup the skybox according to the specified options.
  87725. */
  87726. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  87727. var _this = this;
  87728. if (!this._skybox) {
  87729. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  87730. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  87731. }
  87732. this._skybox.parent = this._rootMesh;
  87733. };
  87734. /**
  87735. * Setup the skybox material according to the specified options.
  87736. */
  87737. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  87738. if (!this._skybox) {
  87739. return;
  87740. }
  87741. if (!this._skyboxMaterial) {
  87742. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  87743. }
  87744. this._skyboxMaterial.useRGBColor = false;
  87745. this._skyboxMaterial.primaryLevel = 1;
  87746. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  87747. this._skyboxMaterial.secondaryLevel = 0;
  87748. this._skyboxMaterial.tertiaryLevel = 0;
  87749. this._skyboxMaterial.enableNoise = true;
  87750. this._skybox.material = this._skyboxMaterial;
  87751. };
  87752. /**
  87753. * Setup the skybox reflection texture according to the specified options.
  87754. */
  87755. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  87756. if (!this._skyboxMaterial) {
  87757. return;
  87758. }
  87759. if (this._skyboxTexture) {
  87760. return;
  87761. }
  87762. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  87763. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  87764. return;
  87765. }
  87766. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene);
  87767. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  87768. this._skyboxTexture.gammaSpace = false;
  87769. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  87770. };
  87771. /**
  87772. * Dispose all the elements created by the Helper.
  87773. */
  87774. EnvironmentHelper.prototype.dispose = function () {
  87775. if (this._groundMaterial) {
  87776. this._groundMaterial.dispose(true, true);
  87777. }
  87778. if (this._skyboxMaterial) {
  87779. this._skyboxMaterial.dispose(true, true);
  87780. }
  87781. this._rootMesh.dispose(false);
  87782. };
  87783. /**
  87784. * Default ground texture URL.
  87785. */
  87786. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  87787. /**
  87788. * Default skybox texture URL.
  87789. */
  87790. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  87791. /**
  87792. * Default environment texture URL.
  87793. */
  87794. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.dds";
  87795. return EnvironmentHelper;
  87796. }());
  87797. BABYLON.EnvironmentHelper = EnvironmentHelper;
  87798. })(BABYLON || (BABYLON = {}));
  87799. //# sourceMappingURL=babylon.environmentHelper.js.map
  87800. BABYLON.Effect.ShadersStore={"defaultVertexShader":"#include<__decl__defaultVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nvarying vec2 vSpecularUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL \nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif\n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<bumpVertex>\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n#include<pointCloudVertex>\n#include<logDepthVertex>\n}","defaultPixelShader":"#include<__decl__defaultFragment>\n#if defined(BUMP) || !defined(NORMAL)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n\n#define RECIPROCAL_PI2 0.15915494\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY \n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\n#if SPECULARDIRECTUV == 1\n#define vSpecularUV vMainUV1\n#elif SPECULARDIRECTUV == 2\n#define vSpecularUV vMainUV2\n#else\nvarying vec2 vSpecularUV;\n#endif\nuniform sampler2D specularSampler;\n#endif\n\n#include<fresnelFunction>\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#include<imageProcessingDeclaration>\n#include<imageProcessingFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(-cross(dFdx(vPositionW),dFdy(vPositionW)));\n#endif\n#include<bumpFragment>\n#ifdef TWOSIDEDLIGHTING\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#endif\n\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV+uvOffset);\nspecularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\n\nvec3 refractionColor=vec3(0.,0.,0.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0)\n{\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb*vRefractionInfos.x;\n}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\nrefractionColor=texture2D(refraction2DSampler,refractionCoords).rgb*vRefractionInfos.x;\n#endif\n#endif\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias).rgb*vReflectionInfos.x;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb*vReflectionInfos.x;\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb*vReflectionInfos.x;\n#endif\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef REFLECTIONOVERALPHA\nalpha=clamp(alpha+dot(reflectionColor,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+emissiveColor+refractionColor,0.0,1.0),alpha);\n#else\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);\n#endif\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n#include<logDepthFragment>\n#include<fogFragment>\n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\ncolor.rgb=toLinearSpace(color.rgb);\n#else\n#ifdef IMAGEPROCESSING\ncolor.rgb=toLinearSpace(color.rgb);\ncolor=applyImageProcessing(color);\n#endif\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\ngl_FragColor=color;\n}","pbrVertexShader":"precision highp float;\n#include<__decl__pbrVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif \n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#if defined(ALBEDO) && ALBEDODIRECTUV == 0\nvarying vec2 vAlbedoUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0\nvarying vec2 vReflectivityUV;\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#include<harmonicsFunctions>\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL\nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvec3 reflectionVector=vec3(reflectionMatrix*vec4(vNormalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\nvEnvironmentIrradiance=environmentIrradianceJones(reflectionVector);\n#endif\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif \n#if defined(ALBEDO) && ALBEDODIRECTUV == 0 \nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0 \nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0 \nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0 \nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0 \nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0 \nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0 \nif (vMicroSurfaceSamplerInfos.x == 0.)\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0 \nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<bumpVertex>\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n\n#include<logDepthVertex>\n}","pbrPixelShader":"#if defined(BUMP) || !defined(NORMAL) || defined(FORCENORMALFORWARD)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LODBASEDMICROSFURACE\n#extension GL_EXT_shader_texture_lod : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nprecision highp float;\n#include<__decl__pbrFragment>\nuniform vec4 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vCameraInfos;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2;\n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\n#if ALBEDODIRECTUV == 1\n#define vAlbedoUV vMainUV1\n#elif ALBEDODIRECTUV == 2\n#define vAlbedoUV vMainUV2\n#else\nvarying vec2 vAlbedoUV;\n#endif\nuniform sampler2D albedoSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY\n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFLECTIVITY\n#if REFLECTIVITYDIRECTUV == 1\n#define vReflectivityUV vMainUV1\n#elif REFLECTIVITYDIRECTUV == 2\n#define vReflectivityUV vMainUV2\n#else\nvarying vec2 vReflectivityUV;\n#endif\nuniform sampler2D reflectivitySampler;\n#endif\n#ifdef MICROSURFACEMAP\n#if MICROSURFACEMAPDIRECTUV == 1\n#define vMicroSurfaceSamplerUV vMainUV1\n#elif MICROSURFACEMAPDIRECTUV == 2\n#define vMicroSurfaceSamplerUV vMainUV2\n#else\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\nuniform sampler2D microSurfaceSampler;\n#endif\n\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\n#define sampleRefraction(s,c) textureCube(s,c)\nuniform samplerCube refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#else\n#define sampleRefraction(s,c) texture2D(s,c)\nuniform sampler2D refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#endif\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#ifdef ENVIRONMENTBRDF\nuniform sampler2D environmentBrdfSampler;\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\n\n#include<shadowsFragmentFunctions>\n#include<pbrFunctions>\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\n\n\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#endif\n#include<bumpFragment>\n#if defined(FORCENORMALFORWARD) && defined(NORMAL)\nvec3 faceNormal=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#if defined(TWOSIDEDLIGHTING)\nfaceNormal=gl_FrontFacing ? faceNormal : -faceNormal;\n#endif\nnormalW*=sign(dot(normalW,faceNormal));\n#endif\n#if defined(TWOSIDEDLIGHTING) && defined(NORMAL)\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n\n\nvec3 surfaceAlbedo=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nvec4 albedoTexture=texture2D(albedoSampler,vAlbedoUV+uvOffset);\n#if defined(ALPHAFROMALBEDO) || defined(ALPHATEST)\nalpha*=albedoTexture.a;\n#endif\nsurfaceAlbedo*=toLinearSpace(albedoTexture.rgb);\nsurfaceAlbedo*=vAlbedoInfos.y;\n#endif\n\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nalpha=getLuminance(opacityMap.rgb);\n#else\nalpha*=opacityMap.a;\n#endif\nalpha*=vOpacityInfos.y;\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#if !defined(LINKREFRACTIONTOTRANSPARENCY) && !defined(ALPHAFRESNEL)\n#ifdef ALPHATEST\nif (alpha<=ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nsurfaceAlbedo*=vColor.rgb;\n#endif\n\nvec3 ambientOcclusionColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nvec3 ambientOcclusionColorMap=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#ifdef AMBIENTINGRAYSCALE\nambientOcclusionColorMap=vec3(ambientOcclusionColorMap.r,ambientOcclusionColorMap.r,ambientOcclusionColorMap.r);\n#endif\nambientOcclusionColor=mix(ambientOcclusionColor,ambientOcclusionColorMap,vAmbientInfos.z);\n#endif\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef METALLICWORKFLOW\nvec2 metallicRoughness=surfaceReflectivityColor.rg;\n#ifdef REFLECTIVITY\nvec4 surfaceMetallicColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\n#ifdef AOSTOREINMETALMAPRED\nvec3 aoStoreInMetalMap=vec3(surfaceMetallicColorMap.r,surfaceMetallicColorMap.r,surfaceMetallicColorMap.r);\nambientOcclusionColor=mix(ambientOcclusionColor,aoStoreInMetalMap,vReflectivityInfos.z);\n#endif\n#ifdef METALLNESSSTOREINMETALMAPBLUE\nmetallicRoughness.r*=surfaceMetallicColorMap.b;\n#else\nmetallicRoughness.r*=surfaceMetallicColorMap.r;\n#endif\n#ifdef ROUGHNESSSTOREINMETALMAPALPHA\nmetallicRoughness.g*=surfaceMetallicColorMap.a;\n#else\n#ifdef ROUGHNESSSTOREINMETALMAPGREEN\nmetallicRoughness.g*=surfaceMetallicColorMap.g;\n#endif\n#endif\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmetallicRoughness.g*=microSurfaceTexel.r;\n#endif\n\nmicroSurface=1.0-metallicRoughness.g;\n\nvec3 baseColor=surfaceAlbedo;\n\n\nconst vec3 DefaultSpecularReflectanceDielectric=vec3(0.04,0.04,0.04);\n\nsurfaceAlbedo=mix(baseColor.rgb*(1.0-DefaultSpecularReflectanceDielectric.r),vec3(0.,0.,0.),metallicRoughness.r);\n\nsurfaceReflectivityColor=mix(DefaultSpecularReflectanceDielectric,baseColor,metallicRoughness.r);\n#else\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\nsurfaceReflectivityColor*=toLinearSpace(surfaceReflectivityColorMap.rgb);\nsurfaceReflectivityColor*=vReflectivityInfos.y;\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface*=surfaceReflectivityColorMap.a;\nmicroSurface*=vReflectivityInfos.z;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface*=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmicroSurface*=microSurfaceTexel.r;\n#endif\n#endif\n#endif\n#endif\n\nmicroSurface=clamp(microSurface,0.,1.);\n\nfloat roughness=1.-microSurface;\n\n#ifdef ALPHAFRESNEL\n#if defined(ALPHATEST) || defined(ALPHABLEND)\n\n\n\nfloat opacityPerceptual=alpha;\n#ifdef LINEARALPHAFRESNEL\nfloat opacity0=opacityPerceptual;\n#else\nfloat opacity0=opacityPerceptual*opacityPerceptual;\n#endif\nfloat opacity90=fresnelGrazingReflectance(opacity0);\nvec3 normalForward=faceforward(normalW,-viewDirectionW,normalW);\n\nalpha=fresnelSchlickEnvironmentGGX(clamp(dot(viewDirectionW,normalForward),0.0,1.0),vec3(opacity0),vec3(opacity90),sqrt(microSurface)).x;\n#ifdef ALPHATEST\nif (alpha<=ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#endif\n\n\nfloat NdotVUnclamped=dot(normalW,viewDirectionW);\nfloat NdotV=clamp(NdotVUnclamped,0.,1.)+0.00001;\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\n\n#ifdef REFRACTION\nvec3 environmentRefraction=vec3(0.,0.,0.);\nvec3 refractionVector=refract(-viewDirectionW,normalW,vRefractionInfos.y);\n#ifdef REFRACTIONMAP_OPPOSITEZ\nrefractionVector.z*=-1.0;\n#endif\n\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nvec3 refractionCoords=refractionVector;\nrefractionCoords=vec3(refractionMatrix*vec4(refractionCoords,0));\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\n#endif\n#ifdef LODINREFRACTIONALPHA\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,1.0);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nrefractionLOD=refractionLOD*vRefractionMicrosurfaceInfos.y+vRefractionMicrosurfaceInfos.z;\n#ifdef LODINREFRACTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticRefractionLOD=UNPACK_LOD(sampleRefraction(refractionSampler,refractionCoords).a);\nfloat requestedRefractionLOD=max(automaticRefractionLOD,refractionLOD);\n#else\nfloat requestedRefractionLOD=refractionLOD;\n#endif\nenvironmentRefraction=sampleRefractionLod(refractionSampler,refractionCoords,requestedRefractionLOD).rgb;\n#else\nfloat lodRefractionNormalized=clamp(refractionLOD/log2(vRefractionMicrosurfaceInfos.x),0.,1.);\nfloat lodRefractionNormalizedDoubled=lodRefractionNormalized*2.0;\nvec3 environmentRefractionMid=sampleRefraction(refractionSampler,refractionCoords).rgb;\nif(lodRefractionNormalizedDoubled<1.0){\nenvironmentRefraction=mix(\nsampleRefraction(refractionSamplerHigh,refractionCoords).rgb,\nenvironmentRefractionMid,\nlodRefractionNormalizedDoubled\n);\n}else{\nenvironmentRefraction=mix(\nenvironmentRefractionMid,\nsampleRefraction(refractionSamplerLow,refractionCoords).rgb,\nlodRefractionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFRACTION\nenvironmentRefraction=toLinearSpace(environmentRefraction.rgb);\n#endif\n\nenvironmentRefraction*=vRefractionInfos.x;\n#endif\n\n#ifdef REFLECTION\nvec3 environmentRadiance=vec3(0.,0.,0.);\nvec3 environmentIrradiance=vec3(0.,0.,0.);\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,1.);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nreflectionLOD=reflectionLOD*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\n#ifdef LODINREFLECTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticReflectionLOD=UNPACK_LOD(sampleReflection(reflectionSampler,reflectionCoords).a);\nfloat requestedReflectionLOD=max(automaticReflectionLOD,reflectionLOD);\n#else\nfloat requestedReflectionLOD=reflectionLOD;\n#endif\nenvironmentRadiance=sampleReflectionLod(reflectionSampler,reflectionCoords,requestedReflectionLOD).rgb;\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD/log2(vReflectionMicrosurfaceInfos.x),0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec3 environmentSpecularMid=sampleReflection(reflectionSampler,reflectionCoords).rgb;\nif(lodReflectionNormalizedDoubled<1.0){\nenvironmentRadiance=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords).rgb,\nenvironmentSpecularMid,\nlodReflectionNormalizedDoubled\n);\n}else{\nenvironmentRadiance=mix(\nenvironmentSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords).rgb,\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFLECTION\nenvironmentRadiance=toLinearSpace(environmentRadiance.rgb);\n#endif\n\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#if defined(NORMAL) && defined(USESPHERICALINVERTEX)\nenvironmentIrradiance=vEnvironmentIrradiance;\n#else\nvec3 irradianceVector=vec3(reflectionMatrix*vec4(normalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nirradianceVector.z*=-1.0;\n#endif\nenvironmentIrradiance=environmentIrradianceJones(irradianceVector);\n#endif\n#endif\n\nenvironmentRadiance*=vReflectionInfos.x;\nenvironmentRadiance*=vReflectionColor.rgb;\nenvironmentIrradiance*=vReflectionColor.rgb;\n#endif\n\n\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\nfloat reflectance90=fresnelGrazingReflectance(reflectance);\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0)*reflectance90;\n\nvec3 diffuseBase=vec3(0.,0.,0.);\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\nlightingInfo info;\nfloat shadow=1.; \nfloat NdotL=-1.;\n#include<lightFragment>[0..maxSimultaneousLights]\n\n#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\n\nvec2 brdfSamplerUV=vec2(NdotV,roughness);\n\nvec4 environmentBrdf=texture2D(environmentBrdfSampler,brdfSamplerUV);\nvec3 specularEnvironmentReflectance=specularEnvironmentR0*environmentBrdf.x+environmentBrdf.y;\n#ifdef RADIANCEOCCLUSION\n#ifdef AMBIENTINGRAYSCALE\nfloat ambientMonochrome=ambientOcclusionColor.r;\n#else\nfloat ambientMonochrome=getLuminance(ambientOcclusionColor);\n#endif\nfloat seo=environmentRadianceOcclusion(ambientMonochrome,NdotVUnclamped);\nspecularEnvironmentReflectance*=seo;\n#endif\n#ifdef HORIZONOCCLUSION\n#ifdef BUMP\n#ifdef REFLECTIONMAP_3D\nfloat eho=environmentHorizonOcclusion(reflectionCoords,normalW);\nspecularEnvironmentReflectance*=eho;\n#endif\n#endif\n#endif\n#else\n\nvec3 specularEnvironmentReflectance=fresnelSchlickEnvironmentGGX(NdotV,specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n#endif\n\n#ifdef REFRACTION\nvec3 refractance=vec3(0.0,0.0,0.0);\nvec3 transmission=vec3(1.0,1.0,1.0);\n#ifdef LINKREFRACTIONTOTRANSPARENCY\n\ntransmission*=(1.0-alpha);\n\n\nvec3 mixedAlbedo=surfaceAlbedo;\nfloat maxChannel=max(max(mixedAlbedo.r,mixedAlbedo.g),mixedAlbedo.b);\nvec3 tint=clamp(maxChannel*mixedAlbedo,0.0,1.0);\n\nsurfaceAlbedo*=alpha;\n\nenvironmentIrradiance*=alpha;\n\nenvironmentRefraction*=tint;\n\nalpha=1.0;\n#endif\n\nvec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);\nspecularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,alpha);\n\ntransmission*=1.0-specularEnvironmentReflectance;\n\nrefractance=transmission;\n#endif\n\n\n\n\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\n\nvec3 finalDiffuse=diffuseBase;\nfinalDiffuse.rgb+=vAmbientColor;\nfinalDiffuse*=surfaceAlbedo.rgb;\nfinalDiffuse=max(finalDiffuse,0.0);\n\n#ifdef REFLECTION\nvec3 finalIrradiance=environmentIrradiance;\nfinalIrradiance*=surfaceAlbedo.rgb;\n#endif\n\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase;\nfinalSpecular=max(finalSpecular,0.0);\n\nvec3 finalSpecularScaled=finalSpecular*vLightingIntensity.x*vLightingIntensity.w;\n#endif\n\n#ifdef REFLECTION\nvec3 finalRadiance=environmentRadiance;\nfinalRadiance*=specularEnvironmentReflectance;\n\nvec3 finalRadianceScaled=finalRadiance*vLightingIntensity.z;\n#endif\n\n#ifdef REFRACTION\nvec3 finalRefraction=environmentRefraction;\nfinalRefraction*=refractance;\n#endif\n\nvec3 finalEmissive=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb;\nfinalEmissive*=toLinearSpace(emissiveColorTex.rgb);\nfinalEmissive*=vEmissiveInfos.y;\n#endif\n\n#ifdef ALPHABLEND\nfloat luminanceOverAlpha=0.0;\n#if defined(REFLECTION) && defined(RADIANCEOVERALPHA)\nluminanceOverAlpha+=getLuminance(finalRadianceScaled);\n#endif\n#if defined(SPECULARTERM) && defined(SPECULAROVERALPHA)\nluminanceOverAlpha+=getLuminance(finalSpecularScaled);\n#endif\n#if defined(RADIANCEOVERALPHA) || defined(SPECULAROVERALPHA)\nalpha=clamp(alpha+luminanceOverAlpha*luminanceOverAlpha,0.,1.);\n#endif\n#endif\n\n\n\nvec4 finalColor=vec4(finalDiffuse*ambientOcclusionColor*vLightingIntensity.x +\n#ifdef REFLECTION\nfinalIrradiance*ambientOcclusionColor*vLightingIntensity.z +\n#endif\n#ifdef SPECULARTERM\n\n\nfinalSpecularScaled +\n#endif\n#ifdef REFLECTION\n\n\nfinalRadianceScaled +\n#endif\n#ifdef REFRACTION\nfinalRefraction*vLightingIntensity.z +\n#endif\nfinalEmissive*vLightingIntensity.y,\nalpha);\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor;\n#else\nfinalColor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n\nfinalColor=max(finalColor,0.0);\n#include<logDepthFragment>\n#include<fogFragment>(color,finalColor)\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\nfinalColor.rgb=clamp(finalColor.rgb,0.,30.0);\n#else\n\nfinalColor=applyImageProcessing(finalColor);\n#endif\n#ifdef PREMULTIPLYALPHA\n\nfinalColor.rgb*=finalColor.a;\n#endif\ngl_FragColor=finalColor;\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n}","spritesVertexShader":"\nattribute vec4 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#include<fogVertexDeclaration>\nvoid main(void) { \nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \nvec2 cornerPos;\nfloat angle=position.w;\nvec2 size=vec2(options.x,options.y);\nvec2 offset=options.zw;\nvec2 uvScale=textureInfos.xy;\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \n\nvColor=color;\n\nvec2 uvOffset=vec2(abs(offset.x-cellInfo.x),1.0-abs(offset.y-cellInfo.y));\nvUV=(uvOffset+cellInfo.zw)*uvScale;\n\n#ifdef FOG\nvFogDistance=viewPos;\n#endif\n}","spritesPixelShader":"uniform bool alphaTest;\nvarying vec4 vColor;\n\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (alphaTest) \n{\nif (color.a<0.95)\ndiscard;\n}\ncolor*=vColor;\n#include<fogFragment>\ngl_FragColor=color;\n}","particlesVertexShader":"\nattribute vec3 position;\nattribute vec4 color;\nattribute vec4 options;\nattribute float cellIndex;\n\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec3 particlesInfos; \n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nvarying float fClipDistance;\n#endif\nvoid main(void) { \nvec3 viewPos=(view*vec4(position,1.0)).xyz; \nvec3 cornerPos;\nfloat size=options.y;\nfloat angle=options.x;\nvec2 offset=options.zw;\ncornerPos=vec3(offset.x-0.5,offset.y-0.5,0.)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \nvColor=color;\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/particlesInfos.z);\nfloat columnOffset=cellIndex-rowOffset*particlesInfos.z;\nvec2 uvScale=particlesInfos.xy;\nvec2 uvOffset=vec2(offset.x ,1.0-offset.y);\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else\nvUV=offset;\n#endif\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*vec4(viewPos,1.0);\nfClipDistance=dot(worldPos,vClipPlane);\n#endif\n}","particlesPixelShader":"\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\nvoid main(void) {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif\nvec4 baseColor=texture2D(diffuseSampler,vUV);\ngl_FragColor=(baseColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n}","colorVertexShader":"\nattribute vec3 position;\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\nuniform mat4 viewProjection;\nuniform mat4 world;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\nvoid main(void) {\nmat4 finalWorld=world;\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n}","colorPixelShader":"#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#else\nuniform vec4 color;\n#endif\nvoid main(void) {\n#ifdef VERTEXCOLOR\ngl_FragColor=vColor;\n#else\ngl_FragColor=color;\n#endif\n}","postprocessVertexShader":"\nattribute vec2 position;\nuniform vec2 scale;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd)*scale;\ngl_Position=vec4(position,0.0,1.0);\n}","passPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\n}","shadowMapVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 biasAndScale;\nuniform vec2 depthValues;\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 worldPos=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*worldPos;\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y))+biasAndScale.x;\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","shadowMapPixelShader":"#ifndef FLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nuniform vec2 biasAndScale;\nuniform vec2 depthValues;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nfloat depth=vDepthMetric;\n#ifdef ESM\ndepth=clamp(exp(-min(87.,biasAndScale.y*depth)),0.,1.);\n#endif\n#ifdef FLOAT\ngl_FragColor=vec4(depth,1.0,1.0,1.0);\n#else\ngl_FragColor=pack(depth);\n#endif\n}","depthBoxBlurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nvoid main(void)\n{\nvec4 colorDepth=vec4(0.0);\nfor (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\ngl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\n}","proceduralVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvPosition=position;\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","depthVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 depthValues;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y));\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","depthPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(vDepthMetric,vDepthMetric*vDepthMetric,0.0,1.0);\n}","ssaoPixelShader":"\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\nuniform float base;\nvec3 normalFromDepth(float depth,vec2 coords)\n{\nvec2 offset1=vec2(0.0,radius);\nvec2 offset2=vec2(radius,0.0);\nfloat depth1=texture2D(textureSampler,coords+offset1).r;\nfloat depth2=texture2D(textureSampler,coords+offset2).r;\nvec3 p1=vec3(offset1,depth1-depth);\nvec3 p2=vec3(offset2,depth2-depth);\nvec3 normal=cross(p1,p2);\nnormal.z=-normal.z;\nreturn normalize(normal);\n}\nvoid main()\n{\nvec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);\nfloat depth=texture2D(textureSampler,vUV).r;\nvec3 position=vec3(vUV,depth);\nvec3 normal=normalFromDepth(depth,vUV);\nfloat radiusDepth=radius/depth;\nfloat occlusion=0.0;\nvec3 ray;\nvec3 hemiRay;\nfloat occlusionDepth;\nfloat difference;\nfor (int i=0; i<SAMPLES; i++)\n{\nray=radiusDepth*reflect(sampleSphere[i],random);\nhemiRay=position+sign(dot(ray,normal))*ray;\nocclusionDepth=texture2D(textureSampler,clamp(hemiRay.xy,vec2(0.001,0.001),vec2(0.999,0.999))).r;\ndifference=depth-occlusionDepth;\nocclusion+=step(fallOff,difference)*(1.0-smoothstep(fallOff,area,difference));\n}\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor.r=result;\ngl_FragColor.g=result;\ngl_FragColor.b=result;\ngl_FragColor.a=1.0;\n}\n#endif\n","ssao2PixelShader":"\nprecision highp float;\nuniform sampler2D textureSampler;\nuniform float near;\nuniform float far;\nuniform float radius;\nvarying vec2 vUV;\nfloat perspectiveDepthToViewZ( const in float invClipZ,const in float near,const in float far ) {\nreturn ( near*far )/( ( far-near )*invClipZ-far );\n}\nfloat viewZToPerspectiveDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( near*far/viewZ+far)/( far-near );\n}\nfloat viewZToOrthographicDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( viewZ+near )/( near-far );\n}\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform sampler2D normalSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float base;\nuniform float xViewport;\nuniform float yViewport;\nuniform float maxZ;\nuniform float minZAspect;\nuniform vec2 texelSize;\nuniform mat4 projection;\nvoid main()\n{\nvec3 random=texture2D(randomSampler,vUV*randTextureTiles).rgb;\nfloat depth=texture2D(textureSampler,vUV).r;\nfloat depthSign=depth/abs(depth);\ndepth=depth*depthSign;\nvec3 normal=texture2D(normalSampler,vUV).rgb; \nfloat occlusion=0.0;\nfloat correctedRadius=min(radius,minZAspect*depth/near);\nvec3 vViewRay=vec3((vUV.x*2.0-1.0)*xViewport,(vUV.y*2.0-1.0)*yViewport,depthSign);\nvec3 origin=vViewRay*depth;\nvec3 rvec=random*2.0-1.0;\nrvec.z=0.0;\nvec3 tangent=normalize(rvec-normal*dot(rvec,normal));\nvec3 bitangent=cross(normal,tangent);\nmat3 tbn=mat3(tangent,bitangent,normal);\nfloat difference;\nif (depth>maxZ) {\ngl_FragColor=vec4(1.0,1.0,1.0,1.0);\nreturn;\n}\nfor (int i=0; i<SAMPLES; ++i) {\n\nvec3 samplePosition=tbn*sampleSphere[i];\nsamplePosition=samplePosition*correctedRadius+origin;\n\nvec4 offset=vec4(samplePosition,1.0);\noffset=projection*offset;\noffset.xyz/=offset.w;\noffset.xy=offset.xy*0.5+0.5;\nif (offset.x<0.0 || offset.y<0.0 || offset.x>1.0 || offset.y>1.0) {\ncontinue;\n}\n\nfloat sampleDepth=abs(texture2D(textureSampler,offset.xy).r);\n\nfloat rangeCheck=abs(depth-sampleDepth)<correctedRadius ? 1.0 : 0.0;\ndifference=depthSign*samplePosition.z-sampleDepth;\n\nocclusion+=(difference>=1e-5 ? 1.0 : 0.0)*rangeCheck;\n}\n\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor=vec4(vec3(result),1.0);\n}\n#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvec4 blur9(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.3846153846)*direction;\nvec2 off2=vec2(3.2307692308)*direction;\ncolor+=texture2D(image,uv)*0.2270270270;\ncolor+=texture2D(image,uv+(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv-(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv+(off2/resolution))*0.0702702703;\ncolor+=texture2D(image,uv-(off2/resolution))*0.0702702703;\nreturn color;\n}\nvec4 blur13(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\ncolor+=texture2D(image,uv)*0.1964825501511404;\ncolor+=texture2D(image,uv+(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv-(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv+(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv-(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv+(off3/resolution))*0.010381362401148057;\ncolor+=texture2D(image,uv-(off3/resolution))*0.010381362401148057;\nreturn color;\n}\nvec4 blur13Bilateral(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\nfloat compareDepth=abs(texture2D(depthSampler,uv).r);\nfloat sampleDepth;\nfloat weight;\nfloat weightSum=30.0;\ncolor+=texture2D(image,uv)*30.0;\nsampleDepth=abs(texture2D(depthSampler,uv+(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off3/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off3/resolution))*weight;\nreturn color/weightSum;\n}\nvoid main()\n{\n#if EXPENSIVE\nfloat compareDepth=abs(texture2D(depthSampler,vUV).r);\nfloat texelsize=1.0/outSize;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 direction=vec2(0.0,1.0);\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=abs(texture2D(depthSampler,samplePos).r);\nfloat weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30000.0);\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n#else\nvec4 color;\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#else\nvec2 direction=vec2(0.0,1.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#endif\ngl_FragColor.rgb=vec3(color.r);\ngl_FragColor.a=1.0;\n#endif\n}\n#endif\n","ssaoCombinePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D originalColor;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,vUV);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\n","chromaticAberrationPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float chromatic_aberration;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nfloat radius2=centered_screen_pos.x*centered_screen_pos.x\n+centered_screen_pos.y*centered_screen_pos.y;\nfloat radius=sqrt(radius2);\nvec4 original=texture2D(textureSampler,vUV);\nif (chromatic_aberration>0.0) {\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*radius*17.0/screen_width;\nfloat ref_shiftY=chromatic_aberration*radius*17.0/screen_height;\n\nvec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);\nvec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);\nvec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);\noriginal.r=texture2D(textureSampler,ref_coords_r).r;\noriginal.g=texture2D(textureSampler,ref_coords_g).g;\noriginal.b=texture2D(textureSampler,ref_coords_b).b;\n}\ngl_FragColor=original;\n}","lensHighlightsPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float gain;\nuniform float threshold;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvec4 highlightColor(vec4 color) {\nvec4 highlight=color;\nfloat luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));\nfloat lum_threshold;\nif (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\nhighlight*=luminance*gain;\nhighlight.a=1.0;\nreturn highlight;\n}\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\n\nif (gain == -1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nreturn;\n}\nfloat w=2.0/screen_width;\nfloat h=2.0/screen_height;\nfloat weight=1.0;\n\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;\ngl_FragColor=blurred;\n\n}","depthOfFieldPixelShader":"\n\n\n\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform bool dof_enabled;\n\nuniform float screen_distance; \nuniform float aperture;\nuniform float darken;\nuniform float edge_blur;\nuniform bool highlights;\n\nuniform float near;\nuniform float far;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \n\nvec2 centered_screen_pos;\nvec2 distorted_coords;\nfloat radius2;\nfloat radius;\n\nvec2 rand(vec2 co)\n{\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));\nfloat noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));\nreturn clamp(vec2(noise1,noise2),0.0,1.0);\n}\n\nvec2 getDistortedCoords(vec2 coords) {\nif (distortion == 0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);\nvec2 dist_coords=vec2(0.5,0.5);\ndist_coords.x=0.5+direction.x*radius2*1.0;\ndist_coords.y=0.5+direction.y*radius2*1.0;\nfloat dist_amount=clamp(distortion*0.23,0.0,1.0);\ndist_coords=mix(coords,dist_coords,dist_amount);\nreturn dist_coords;\n}\n\nfloat sampleScreen(inout vec4 color,const in vec2 offset,const in float weight) {\n\nvec2 coords=distorted_coords;\nfloat angle=rand(coords*100.0).x*TWOPI;\ncoords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));\ncolor+=texture2D(textureSampler,coords)*weight;\nreturn weight;\n}\n\nfloat getBlurLevel(float size) {\nreturn min(3.0,ceil(size/1.0));\n}\n\nvec4 getBlurColor(float size) {\nvec4 col=texture2D(textureSampler,distorted_coords);\nif (size == 0.0) { return col; }\n\n\nfloat blur_level=getBlurLevel(size);\nfloat w=(size/screen_width);\nfloat h=(size/screen_height);\nfloat total_weight=1.0;\nvec2 sample_coords;\ntotal_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);\ntotal_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);\ntotal_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);\ntotal_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);\ntotal_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);\ntotal_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);\ntotal_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);\ntotal_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);\ntotal_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);\nif (blur_level>1.0) {\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);\ntotal_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);\ntotal_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);\ntotal_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);\ntotal_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);\ntotal_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);\ntotal_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);\ntotal_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);\ntotal_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);\n}\nif (blur_level>2.0) {\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);\ntotal_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);\ntotal_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);\ntotal_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);\ntotal_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);\ntotal_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);\ntotal_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);\ntotal_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);\ntotal_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);\n}\ncol/=total_weight; \n\nif (darken>0.0) {\ncol.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);\n}\n\n\n\n\nreturn col;\n}\nvoid main(void)\n{\n\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nradius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;\nradius=sqrt(radius2);\ndistorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \n\n\nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));\n\nif (dof_enabled == false || coc<0.07) { coc=0.0; }\n\nfloat edge_blur_amount=0.0;\nif (edge_blur>0.0) {\nedge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;\n}\n\nfloat blur_amount=max(edge_blur_amount,coc);\n\nif (blur_amount == 0.0) {\ngl_FragColor=texture2D(textureSampler,distorted_coords);\n}\nelse {\n\ngl_FragColor=getBlurColor(blur_amount*1.7);\n\nif (highlights) {\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;\n}\nif (blur_noise) {\n\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;\nvec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);\ngl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;\n}\n}\n\nif (grain_amount>0.0) {\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);\ngl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;\n}\n}\n","standardPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(PASS_POST_PROCESS)\nvoid main(void)\n{\nvec4 color=texture2D(textureSampler,vUV);\ngl_FragColor=color;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nuniform sampler2D lensSampler;\nuniform float exposure;\nvoid main(void)\n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\ncolour*=exposure;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\ncolour+=colour*texture2D(lensSampler,vUV).rgb;\nvec4 finalColor=vec4(colour.rgb,1.0)+texture2D(otherSampler,vUV);\ngl_FragColor=finalColor;\n}\n#endif\n#if defined(VLS)\n#define PI 3.1415926535897932384626433832795\nuniform mat4 shadowViewProjection;\nuniform mat4 lightWorld;\nuniform vec3 cameraPosition;\nuniform vec3 sunDirection;\nuniform vec3 sunColor;\nuniform vec2 depthValues;\nuniform float scatteringCoefficient;\nuniform float scatteringPower;\nuniform sampler2D shadowMapSampler;\nuniform sampler2D positionSampler;\nfloat computeScattering(float lightDotView)\n{\nfloat result=1.0-scatteringCoefficient*scatteringCoefficient;\nresult/=(4.0*PI*pow(1.0+scatteringCoefficient*scatteringCoefficient-(2.0*scatteringCoefficient)*lightDotView,1.5));\nreturn result;\n}\nvoid main(void)\n{\n\nvec3 worldPos=texture2D(positionSampler,vUV).rgb;\nvec3 startPosition=cameraPosition;\nvec3 rayVector=worldPos-startPosition;\nfloat rayLength=length(rayVector);\nvec3 rayDirection=rayVector/rayLength;\nfloat stepLength=rayLength/NB_STEPS;\nvec3 stepL=rayDirection*stepLength;\nvec3 currentPosition=startPosition;\nvec3 accumFog=vec3(0.0);\nfor (int i=0; i<int(NB_STEPS); i++)\n{\nvec4 worldInShadowCameraSpace=shadowViewProjection*vec4(currentPosition,1.0);\nfloat depthMetric=(worldInShadowCameraSpace.z+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depthMetric,0.0,1.0);\nworldInShadowCameraSpace.xyz/=worldInShadowCameraSpace.w;\nworldInShadowCameraSpace.xyz=0.5*worldInShadowCameraSpace.xyz+vec3(0.5);\nfloat shadowMapValue=texture2D(shadowMapSampler,worldInShadowCameraSpace.xy).r;\nif (shadowMapValue>shadowPixelDepth)\naccumFog+=sunColor*computeScattering(dot(rayDirection,sunDirection));\ncurrentPosition+=stepL;\n}\naccumFog/=NB_STEPS;\nvec3 color=accumFog*scatteringPower;\ngl_FragColor=vec4(color*exp(color) ,1.0);\n}\n#endif\n#if defined(VLSMERGE)\nuniform sampler2D originalSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(originalSampler,vUV)+texture2D(textureSampler,vUV);\n}\n#endif\n#if defined(LUMINANCE)\nuniform vec2 lumOffsets[4];\nvoid main()\n{\nfloat average=0.0;\nvec4 color=vec4(0.0);\nfloat maximum=-1e20;\nvec3 weight=vec3(0.299,0.587,0.114);\nfor (int i=0; i<4; i++)\n{\ncolor=texture2D(textureSampler,vUV+ lumOffsets[i]);\n\nfloat GreyValue=dot(color.rgb,vec3(0.33,0.33,0.33));\n\n#ifdef WEIGHTED_AVERAGE\nfloat GreyValue=dot(color.rgb,weight);\n#endif\n#ifdef BRIGHTNESS\nfloat GreyValue=max(color.r,max(color.g,color.b));\n#endif\n#ifdef HSL_COMPONENT\nfloat GreyValue=0.5*(max(color.r,max(color.g,color.b))+min(color.r,min(color.g,color.b)));\n#endif\n#ifdef MAGNITUDE\nfloat GreyValue=length(color.rgb);\n#endif\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_FragColor=vec4(average,maximum,0.0,1.0);\n}\n#endif\n#if defined(LUMINANCE_DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLER\nvec4 pack(float value) {\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(value*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvoid main()\n{\nvec4 color=vec4(0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++)\n{\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifdef FINAL_DOWN_SAMPLER\ngl_FragColor=pack(average);\n#else\ngl_FragColor=vec4(average,average,0.0,1.0);\n#endif\n}\n#endif\n#if defined(HDR)\nuniform sampler2D textureAdderSampler;\nuniform float averageLuminance;\nvoid main()\n{\nvec4 color=texture2D(textureAdderSampler,vUV);\nvec4 adjustedColor=color/averageLuminance;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(LENS_FLARE)\n#define GHOSTS 3\nuniform sampler2D lensColorSampler;\nuniform float strength;\nuniform float ghostDispersal;\nuniform float haloWidth;\nuniform vec2 resolution;\nuniform float distortionStrength;\nfloat hash(vec2 p)\n{\nfloat h=dot(p,vec2(127.1,311.7));\nreturn -1.0+2.0*fract(sin(h)*43758.5453123);\n}\nfloat noise(in vec2 p)\n{\nvec2 i=floor(p);\nvec2 f=fract(p);\nvec2 u=f*f*(3.0-2.0*f);\nreturn mix(mix(hash(i+vec2(0.0,0.0)),\nhash(i+vec2(1.0,0.0)),u.x),\nmix(hash(i+vec2(0.0,1.0)),\nhash(i+vec2(1.0,1.0)),u.x),u.y);\n}\nfloat fbm(vec2 p)\n{\nfloat f=0.0;\nf+=0.5000*noise(p); p*=2.02;\nf+=0.2500*noise(p); p*=2.03;\nf+=0.1250*noise(p); p*=2.01;\nf+=0.0625*noise(p); p*=2.04;\nf/=0.9375;\nreturn f;\n}\nvec3 pattern(vec2 uv)\n{\nvec2 p=-1.0+2.0*uv;\nfloat p2=dot(p,p);\nfloat f=fbm(vec2(15.0*p2))/2.0;\nfloat r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));\nfloat g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));\nfloat b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));\nreturn (1.0-f)*vec3(r,g,b);\n}\nfloat luminance(vec3 color)\n{\nreturn dot(color.rgb,vec3(0.2126,0.7152,0.0722));\n}\nvec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion)\n{\nreturn vec4(\ntexture2D(tex,texcoord+direction*distortion.r).r,\ntexture2D(tex,texcoord+direction*distortion.g).g,\ntexture2D(tex,texcoord+direction*distortion.b).b,\n1.0\n);\n}\nvoid main(void)\n{\nvec2 uv=-vUV+vec2(1.0);\nvec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;\nvec2 texelSize=1.0/resolution;\nvec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);\nvec4 result=vec4(0.0);\nfloat ghostIndice=1.0;\nfor (int i=0; i<GHOSTS; ++i)\n{\nvec2 offset=fract(uv+ghostDir*ghostIndice);\nfloat weight=length(vec2(0.5)-offset)/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,offset,normalize(ghostDir),distortion)*weight*strength;\nghostIndice+=1.0;\n}\nvec2 haloVec=normalize(ghostDir)*haloWidth;\nfloat weight=length(vec2(0.5)-fract(uv+haloVec))/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,fract(uv+haloVec),normalize(ghostDir),distortion)*weight*strength;\nresult*=texture2D(lensColorSampler,vec2(length(vec2(0.5)-uv)/length(vec2(0.5))));\ngl_FragColor=result;\n}\n#endif\n#if defined(LENS_FLARE_COMPOSE)\nuniform sampler2D otherSampler;\nuniform sampler2D lensDirtSampler;\nuniform sampler2D lensStarSampler;\nuniform mat4 lensStarMatrix;\nvoid main(void)\n{\nvec2 lensFlareCoords=(lensStarMatrix*vec4(vUV,1.0,1.0)).xy;\nvec4 lensMod=texture2D(lensDirtSampler,vUV);\nlensMod+=texture2D(lensStarSampler,vUV);\nvec4 result=texture2D(textureSampler,vUV)*lensMod;\ngl_FragColor=texture2D(otherSampler,vUV)+result;\n}\n#endif\n#if defined(DEPTH_OF_FIELD)\nuniform sampler2D otherSampler;\nuniform sampler2D depthSampler;\nuniform float distance;\nvoid main(void)\n{\nvec4 sharp=texture2D(otherSampler,vUV);\nvec4 blur=texture2D(textureSampler,vUV);\nfloat dist=clamp(texture2D(depthSampler,vUV).r*distance,0.0,1.0);\nfloat factor=0.0;\nif (dist<0.05)\nfactor=1.0;\nelse if (dist<0.1)\nfactor=20.0*(0.1-dist);\nelse if (dist<0.5)\nfactor=0.0;\nelse\nfactor=2.0*(dist-0.5);\nfactor=clamp(factor,0.0,0.90);\ngl_FragColor=mix(sharp,blur,factor);\n}\n#endif\n#if defined(MOTION_BLUR)\nuniform mat4 inverseViewProjection;\nuniform mat4 prevViewProjection;\nuniform vec2 screenSize;\nuniform float motionScale;\nuniform float motionStrength;\nuniform sampler2D depthSampler;\nvoid main(void)\n{\nvec2 texelSize=1.0/screenSize;\nfloat depth=texture2D(depthSampler,vUV).r;\nvec4 cpos=vec4(vUV*2.0-1.0,depth,1.0);\ncpos=cpos*inverseViewProjection;\nvec4 ppos=cpos*prevViewProjection;\nppos.xyz/=ppos.w;\nppos.xy=ppos.xy*0.5+0.5;\nvec2 velocity=(ppos.xy-vUV)*motionScale*motionStrength;\nfloat speed=length(velocity/texelSize);\nint nSamples=int(clamp(speed,1.0,MAX_MOTION_SAMPLES));\nvec4 result=texture2D(textureSampler,vUV);\nfor (int i=1; i<int(MAX_MOTION_SAMPLES); ++i) {\nif (i>=nSamples)\nbreak;\nvec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);\nresult+=texture2D(textureSampler,offset1);\n}\ngl_FragColor=result/float(nSamples);\n}\n#endif\n","fxaaVertexShader":"\nattribute vec2 position;\nuniform vec2 texelSize;\n\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd);\nsampleCoordS=vUV+vec2( 0.0,1.0)*texelSize;\nsampleCoordE=vUV+vec2( 1.0,0.0)*texelSize;\nsampleCoordN=vUV+vec2( 0.0,-1.0)*texelSize;\nsampleCoordW=vUV+vec2(-1.0,0.0)*texelSize;\nsampleCoordNW=vUV+vec2(-1.0,-1.0)*texelSize;\nsampleCoordSE=vUV+vec2( 1.0,1.0)*texelSize;\nsampleCoordNE=vUV+vec2( 1.0,-1.0)*texelSize;\nsampleCoordSW=vUV+vec2(-1.0,1.0)*texelSize;\ngl_Position=vec4(position,0.0,1.0);\n}","fxaaPixelShader":"uniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst float fxaaQualitySubpix=1.0;\nconst float fxaaQualityEdgeThreshold=0.166;\nconst float fxaaQualityEdgeThresholdMin=0.0833;\nconst vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722);\n#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients)\nvoid main(){\nvec2 posM;\nposM.x=vUV.x;\nposM.y=vUV.y;\nvec4 rgbyM=texture2D(textureSampler,vUV,0.0);\nfloat lumaM=FxaaLuma(rgbyM);\nfloat lumaS=FxaaLuma(texture2D(textureSampler,sampleCoordS,0.0));\nfloat lumaE=FxaaLuma(texture2D(textureSampler,sampleCoordE,0.0));\nfloat lumaN=FxaaLuma(texture2D(textureSampler,sampleCoordN,0.0));\nfloat lumaW=FxaaLuma(texture2D(textureSampler,sampleCoordW,0.0));\nfloat maxSM=max(lumaS,lumaM);\nfloat minSM=min(lumaS,lumaM);\nfloat maxESM=max(lumaE,maxSM);\nfloat minESM=min(lumaE,minSM);\nfloat maxWN=max(lumaN,lumaW);\nfloat minWN=min(lumaN,lumaW);\nfloat rangeMax=max(maxWN,maxESM);\nfloat rangeMin=min(minWN,minESM);\nfloat rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;\nfloat range=rangeMax-rangeMin;\nfloat rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled);\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\nreturn;\n}\nfloat lumaNW=FxaaLuma(texture2D(textureSampler,sampleCoordNW,0.0));\nfloat lumaSE=FxaaLuma(texture2D(textureSampler,sampleCoordSE,0.0));\nfloat lumaNE=FxaaLuma(texture2D(textureSampler,sampleCoordNE,0.0));\nfloat lumaSW=FxaaLuma(texture2D(textureSampler,sampleCoordSW,0.0));\nfloat lumaNS=lumaN+lumaS;\nfloat lumaWE=lumaW+lumaE;\nfloat subpixRcpRange=1.0/range;\nfloat subpixNSWE=lumaNS+lumaWE;\nfloat edgeHorz1=(-2.0*lumaM)+lumaNS;\nfloat edgeVert1=(-2.0*lumaM)+lumaWE;\nfloat lumaNESE=lumaNE+lumaSE;\nfloat lumaNWNE=lumaNW+lumaNE;\nfloat edgeHorz2=(-2.0*lumaE)+lumaNESE;\nfloat edgeVert2=(-2.0*lumaN)+lumaNWNE;\nfloat lumaNWSW=lumaNW+lumaSW;\nfloat lumaSWSE=lumaSW+lumaSE;\nfloat edgeHorz4=(abs(edgeHorz1)*2.0)+abs(edgeHorz2);\nfloat edgeVert4=(abs(edgeVert1)*2.0)+abs(edgeVert2);\nfloat edgeHorz3=(-2.0*lumaW)+lumaNWSW;\nfloat edgeVert3=(-2.0*lumaS)+lumaSWSE;\nfloat edgeHorz=abs(edgeHorz3)+edgeHorz4;\nfloat edgeVert=abs(edgeVert3)+edgeVert4;\nfloat subpixNWSWNESE=lumaNWSW+lumaNESE;\nfloat lengthSign=texelSize.x;\nbool horzSpan=edgeHorz>=edgeVert;\nfloat subpixA=subpixNSWE*2.0+subpixNWSWNESE;\nif (!horzSpan)\n{\nlumaN=lumaW;\n}\nif (!horzSpan) \n{\nlumaS=lumaE;\n}\nif (horzSpan) \n{\nlengthSign=texelSize.y;\n}\nfloat subpixB=(subpixA*(1.0/12.0))-lumaM;\nfloat gradientN=lumaN-lumaM;\nfloat gradientS=lumaS-lumaM;\nfloat lumaNN=lumaN+lumaM;\nfloat lumaSS=lumaS+lumaM;\nbool pairN=abs(gradientN)>=abs(gradientS);\nfloat gradient=max(abs(gradientN),abs(gradientS));\nif (pairN)\n{\nlengthSign=-lengthSign;\n}\nfloat subpixC=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);\nvec2 posB;\nposB.x=posM.x;\nposB.y=posM.y;\nvec2 offNP;\noffNP.x=(!horzSpan) ? 0.0 : texelSize.x;\noffNP.y=(horzSpan) ? 0.0 : texelSize.y;\nif (!horzSpan) \n{\nposB.x+=lengthSign*0.5;\n}\nif (horzSpan)\n{\nposB.y+=lengthSign*0.5;\n}\nvec2 posN;\nposN.x=posB.x-offNP.x*1.5;\nposN.y=posB.y-offNP.y*1.5;\nvec2 posP;\nposP.x=posB.x+offNP.x*1.5;\nposP.y=posB.y+offNP.y*1.5;\nfloat subpixD=((-2.0)*subpixC)+3.0;\nfloat lumaEndN=FxaaLuma(texture2D(textureSampler,posN,0.0));\nfloat subpixE=subpixC*subpixC;\nfloat lumaEndP=FxaaLuma(texture2D(textureSampler,posP,0.0));\nif (!pairN) \n{\nlumaNN=lumaSS;\n}\nfloat gradientScaled=gradient*1.0/4.0;\nfloat lumaMM=lumaM-lumaNN*0.5;\nfloat subpixF=subpixD*subpixE;\nbool lumaMLTZero=lumaMM<0.0;\nlumaEndN-=lumaNN*0.5;\nlumaEndP-=lumaNN*0.5;\nbool doneN=abs(lumaEndN)>=gradientScaled;\nbool doneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) \n{\nposN.x-=offNP.x*3.0;\n}\nif (!doneN) \n{\nposN.y-=offNP.y*3.0;\n}\nbool doneNP=(!doneN) || (!doneP);\nif (!doneP) \n{\nposP.x+=offNP.x*3.0;\n}\nif (!doneP)\n{\nposP.y+=offNP.y*3.0;\n}\nif (doneNP)\n{\nif (!doneN) lumaEndN=FxaaLuma(texture2D(textureSampler,posN.xy,0.0));\nif (!doneP) lumaEndP=FxaaLuma(texture2D(textureSampler,posP.xy,0.0));\nif (!doneN) lumaEndN=lumaEndN-lumaNN*0.5;\nif (!doneP) lumaEndP=lumaEndP-lumaNN*0.5;\ndoneN=abs(lumaEndN)>=gradientScaled;\ndoneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) posN.x-=offNP.x*12.0;\nif (!doneN) posN.y-=offNP.y*12.0;\ndoneNP=(!doneN) || (!doneP);\nif (!doneP) posP.x+=offNP.x*12.0;\nif (!doneP) posP.y+=offNP.y*12.0;\n}\nfloat dstN=posM.x-posN.x;\nfloat dstP=posP.x-posM.x;\nif (!horzSpan)\n{\ndstN=posM.y-posN.y;\n}\nif (!horzSpan) \n{\ndstP=posP.y-posM.y;\n}\nbool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;\nfloat spanLength=(dstP+dstN);\nbool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;\nfloat spanLengthRcp=1.0/spanLength;\nbool directionN=dstN<dstP;\nfloat dst=min(dstN,dstP);\nbool goodSpan=directionN ? goodSpanN : goodSpanP;\nfloat subpixG=subpixF*subpixF;\nfloat pixelOffset=(dst*(-spanLengthRcp))+0.5;\nfloat subpixH=subpixG*fxaaQualitySubpix;\nfloat pixelOffsetGood=goodSpan ? pixelOffset : 0.0;\nfloat pixelOffsetSubpix=max(pixelOffsetGood,subpixH);\nif (!horzSpan)\n{\nposM.x+=pixelOffsetSubpix*lengthSign;\n}\nif (horzSpan)\n{\nposM.y+=pixelOffsetSubpix*lengthSign;\n}\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n}","circleOfConfusionPixelShader":"\nuniform sampler2D depthSampler;\n\nvarying vec2 vUV;\n\nuniform vec2 cameraMinMaxZ;\n\nuniform float focusDistance;\nuniform float cocPrecalculation;\nfloat sampleDistance(const in vec2 offset) {\nfloat depth=texture2D(depthSampler,offset).r; \nreturn (cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth)*1000.0; \n}\nvoid main(void)\n{\nfloat pixelDistance=sampleDistance(vUV);\nfloat coc=abs(cocPrecalculation* ((focusDistance-pixelDistance)/pixelDistance));\ncoc=clamp(coc,0.0,1.0);\ngl_FragColor=vec4(coc,texture2D(depthSampler,vUV).r,coc,1.0);\n}\n","depthOfFieldMergePixelShader":"\nuniform sampler2D textureSampler;\nuniform sampler2D originalSampler;\nuniform sampler2D circleOfConfusionSampler;\n#if BLUR_LEVEL>0\nuniform sampler2D blurStep1;\n#endif\n#if BLUR_LEVEL>1\nuniform sampler2D blurStep2;\n#endif\n\nvarying vec2 vUV;\nvoid main(void)\n{\nfloat coc=texture2D(circleOfConfusionSampler,vUV).r;\nvec4 original=texture2D(originalSampler,vUV);\n#if BLUR_LEVEL == 0\nvec4 blurred1=texture2D(textureSampler,vUV);\ngl_FragColor=mix(original,blurred1,coc);\n#endif\n#if BLUR_LEVEL == 1\nvec4 blurred1=texture2D(blurStep1,vUV);\nvec4 blurred2=texture2D(textureSampler,vUV); \nif(coc<0.5){\ngl_FragColor=mix(original,blurred1,coc/0.5);\n}else{\ngl_FragColor=mix(blurred1,blurred2,(coc-0.5)/0.5);\n}\n#endif\n#if BLUR_LEVEL == 2\nvec4 blurred1=texture2D(blurStep1,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\nvec4 blurred3=texture2D(textureSampler,vUV);\nif(coc<0.33){\ngl_FragColor=mix(original,blurred1,coc/0.33);\n}else if(coc<0.66){\ngl_FragColor=mix(blurred1,blurred2,(coc-0.33)/0.33);\n}else{\ngl_FragColor=mix(blurred2,blurred3,(coc-0.66)/0.34);\n}\n#endif\n}\n","geometryVertexShader":"precision highp float;\nprecision highp int;\n#include<bonesDeclaration>\n#include<instancesDeclaration>\nattribute vec3 position;\nattribute vec3 normal;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nvarying vec2 uv;\n#endif\n#ifdef UV2\nvarying vec2 uv2;\n#endif\n#endif\n\nuniform mat4 viewProjection;\nuniform mat4 view;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 pos=vec4(finalWorld*vec4(position,1.0));\nvNormalV=normalize(vec3((view*finalWorld)*vec4(normal,0.0)));\nvViewPos=view*pos;\n#ifdef POSITION\nvPosition=pos.xyz/pos.w;\n#endif\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","geometryPixelShader":"#extension GL_EXT_draw_buffers : require\nprecision highp float;\nprecision highp int;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef POSITION\n#include<mrtFragmentDeclaration>[3]\n#else\n#include<mrtFragmentDeclaration>[2]\n#endif\nvoid main() {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragData[0]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);\n\ngl_FragData[1]=vec4(normalize(vNormalV),1.0);\n\n#ifdef POSITION\ngl_FragData[2]=vec4(vPosition,1.0);\n#endif\n}","refractionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\nvoid main() {\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;\nvec2 uv=vUV-vec2(0.5);\nvec2 offset=uv*depth*ref;\nvec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;\ngl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);\n}","blackAndWhitePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float degree;\nvoid main(void) \n{\nvec3 color=texture2D(textureSampler,vUV).rgb;\nfloat luminance=dot(color,vec3(0.3,0.59,0.11)); \nvec3 blackAndWhite=vec3(luminance,luminance,luminance);\ngl_FragColor=vec4(color-((color-blackAndWhite)*degree),1.0);\n}","convolutionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform float kernel[9];\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];\nfloat kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];\nif (kernelWeight<=0.0) {\nkernelWeight=1.0;\n}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);\n}","filterPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform mat4 kernelMatrix;\nvoid main(void)\n{\nvec3 baseColor=texture2D(textureSampler,vUV).rgb;\nvec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;\ngl_FragColor=vec4(updatedColor,1.0);\n}","volumetricLightScatteringPixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\nvarying vec2 vUV;\nvoid main(void) {\nvec2 tc=vUV;\nvec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);\ndeltaTexCoord*=1.0/float(NUM_SAMPLES)*density;\nfloat illuminationDecay=1.0;\nvec4 color=texture2D(lightScatteringSampler,tc)*0.4;\nfor(int i=0; i<NUM_SAMPLES; i++) {\ntc-=deltaTexCoord;\nvec4 dataSample=texture2D(lightScatteringSampler,tc)*0.4;\ndataSample*=illuminationDecay*weight;\ncolor+=dataSample;\nilluminationDecay*=decay;\n}\nvec4 realColor=texture2D(textureSampler,vUV);\ngl_FragColor=((vec4((vec3(color.r,color.g,color.b)*exposure),1))+(realColor*(1.5-0.4)));\n}\n","volumetricLightScatteringPassPixelShader":"#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\n#endif\n#if defined(ALPHATEST)\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void)\n{\n#if defined(ALPHATEST)\nvec4 diffuseColor=texture2D(diffuseSampler,vUV);\nif (diffuseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\n","colorCorrectionPixelShader":"\nuniform sampler2D textureSampler; \nuniform sampler2D colorTable; \n\nvarying vec2 vUV;\n\nconst float SLICE_COUNT=16.0; \n\nvec4 sampleAs3DTexture(sampler2D textureSampler,vec3 uv,float width) {\nfloat sliceSize=1.0/width; \nfloat slicePixelSize=sliceSize/width; \nfloat sliceInnerSize=slicePixelSize*(width-1.0); \nfloat zSlice0=min(floor(uv.z*width),width-1.0);\nfloat zSlice1=min(zSlice0+1.0,width-1.0);\nfloat xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;\nfloat s0=xOffset+(zSlice0*sliceSize);\nfloat s1=xOffset+(zSlice1*sliceSize);\nvec4 slice0Color=texture2D(textureSampler,vec2(s0,uv.y));\nvec4 slice1Color=texture2D(textureSampler,vec2(s1,uv.y));\nfloat zOffset=mod(uv.z*width,1.0);\nvec4 result=mix(slice0Color,slice1Color,zOffset);\nreturn result;\n}\nvoid main(void)\n{\nvec4 screen_color=texture2D(textureSampler,vUV);\ngl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);\n}","tonemapPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst float A=0.15;\nconst float B=0.50;\nconst float C=0.10;\nconst float D=0.20;\nconst float E=0.02;\nconst float F=0.30;\nconst float W=11.2;\n#endif\nfloat Luminance(vec3 c)\n{\nreturn dot(c,vec3(0.22,0.707,0.071));\n}\nvoid main(void) \n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \nfloat lumTm=lum*_ExposureAdjustment;\nfloat scale=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nconst float ExposureBias=2.0;\nvec3 x=ExposureBias*colour;\nvec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;\nx=vec3(W,W,W);\nvec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);\ncolour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour=vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\n#endif\ngl_FragColor=vec4(colour.rgb,1.0);\n}","displayPassPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(passSampler,vUV);\n}","highlightsPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nconst vec3 RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nvoid main(void) \n{\nvec4 tex=texture2D(textureSampler,vUV);\nvec3 c=tex.rgb;\nfloat luma=dot(c.rgb,RGBLuminanceCoefficients);\n\n\ngl_FragColor=vec4(pow(c,vec3(25.0-luma*15.0)),tex.a); \n}","imageProcessingPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\nvoid main(void)\n{\nvec4 result=texture2D(textureSampler,vUV);\n#ifdef IMAGEPROCESSING\n#ifndef FROMLINEARSPACE\n\nresult.rgb=toLinearSpace(result.rgb);\n#endif\nresult=applyImageProcessing(result);\n#else\n\n#ifdef FROMLINEARSPACE\nresult=applyImageProcessing(result);\n#endif\n#endif\ngl_FragColor=result;\n}","kernelBlurVertexShader":"\nattribute vec2 position;\n\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nsampleCenter=(position*madd+madd);\n#include<kernelBlurVertex>[0..varyingCount]\ngl_Position=vec4(position,0.0,1.0);\n}","kernelBlurPixelShader":"\nuniform sampler2D textureSampler;\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#ifdef DOF\nuniform sampler2D circleOfConfusionSampler;\nuniform vec2 cameraMinMaxZ;\nfloat sampleDistance(const in vec2 offset) {\nfloat depth=texture2D(circleOfConfusionSampler,offset).g; \nreturn cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth; \n}\n#endif\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\n#ifdef PACKEDFLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nvoid main(void)\n{\n#ifdef DOF\nfloat sumOfWeights=0.0; \nfloat sampleDepth=0.0;\nfloat factor=0.0;\nfloat centerSampleDepth=sampleDistance(sampleCenter);\n#endif\nfloat computedWeight=0.0;\n#ifdef PACKEDFLOAT \nfloat blend=0.;\n#else\nvec4 blend=vec4(0.);\n#endif\n#include<kernelBlurFragment>[0..varyingCount]\n#include<kernelBlurFragment2>[0..depCount]\n#ifdef PACKEDFLOAT\ngl_FragColor=pack(blend);\n#else\ngl_FragColor=blend;\n#endif\n#ifdef DOF\n\nif(sumOfWeights == 0.0){\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor/=sumOfWeights;\n#endif\n}","lensFlareVertexShader":"\nattribute vec2 position;\n\nuniform mat4 viewportMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=position*madd+madd;\ngl_Position=viewportMatrix*vec4(position,0.0,1.0);\n}","lensFlarePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\ngl_FragColor=baseColor*color;\n}","anaglyphPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\nvoid main(void)\n{\nvec4 leftFrag=texture2D(leftSampler,vUV);\nleftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);\nvec4 rightFrag=texture2D(textureSampler,vUV);\nrightFrag=vec4(rightFrag.r,1.0,1.0,1.0);\ngl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);\n}","stereoscopicInterlacePixelShader":"const vec3 TWO=vec3(2.0,2.0,2.0);\nvarying vec2 vUV;\nuniform sampler2D camASampler;\nuniform sampler2D textureSampler;\nuniform vec2 stepSize;\nvoid main(void)\n{\nbool useCamB;\nvec2 texCoord1;\nvec2 texCoord2;\nvec3 frag1;\nvec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;\ntexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\ntexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;\ntexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\ntexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n\nif (useCamB){\nfrag1=texture2D(textureSampler,texCoord1).rgb;\nfrag2=texture2D(textureSampler,texCoord2).rgb;\n}else{\nfrag1=texture2D(camASampler ,texCoord1).rgb;\nfrag2=texture2D(camASampler ,texCoord2).rgb;\n}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);\n}","vrDistortionCorrectionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\nvec2 HmdWarp(vec2 in01) {\nvec2 theta=(in01-LensCenter)*ScaleIn; \nfloat rSq=theta.x*theta.x+theta.y*theta.y;\nvec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);\nreturn LensCenter+Scale*rvector;\n}\nvoid main(void)\n{\nvec2 tc=HmdWarp(vUV);\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,0.0);\nelse{\ngl_FragColor=texture2D(textureSampler,tc);\n}\n}","glowBlurPostProcessPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\n\nfloat getLuminance(vec3 color)\n{\nreturn dot(color,vec3(0.2126,0.7152,0.0722));\n}\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\n\nvec4 texel=texture2D(textureSampler,start+texelOffset);\nbaseColor.a+=texel.a*weights[i];\n\nfloat luminance=getLuminance(baseColor.rgb);\nfloat luminanceTexel=getLuminance(texel.rgb);\nfloat choice=step(luminanceTexel,luminance);\nbaseColor.rgb=choice*baseColor.rgb+(1.0-choice)*texel.rgb;\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}","glowMapGenerationPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform sampler2D emissiveSampler;\n#endif\nuniform vec4 color;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUVDiffuse).a<0.4)\ndiscard;\n#endif\n#ifdef EMISSIVE\ngl_FragColor=texture2D(emissiveSampler,vUVEmissive)*color;\n#else\ngl_FragColor=color;\n#endif\n}","glowMapGenerationVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform mat4 diffuseMatrix;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform mat4 emissiveMatrix;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(position,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef DIFFUSEUV1\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef DIFFUSEUV2\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef EMISSIVE\n#ifdef EMISSIVEUV1\nvUVEmissive=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef EMISSIVEUV2\nvUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","glowMapMergePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#ifdef EMISSIVE\nuniform sampler2D textureSampler2;\n#endif\n\nuniform float offset;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef EMISSIVE\nbaseColor+=texture2D(textureSampler2,vUV);\nbaseColor*=offset;\n#else\nbaseColor.a=abs(offset-baseColor.a);\n#ifdef STROKE\nfloat alpha=smoothstep(.0,.1,baseColor.a);\nbaseColor.a=alpha;\nbaseColor.rgb=baseColor.rgb*alpha;\n#endif\n#endif\ngl_FragColor=baseColor;\n}","glowMapMergeVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) {\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","lineVertexShader":"\nattribute vec3 position;\nattribute vec4 normal;\n\nuniform mat4 worldViewProjection;\nuniform float width;\nuniform float aspectRatio;\nvoid main(void) {\nvec4 viewPosition=worldViewProjection*vec4(position,1.0);\nvec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);\nvec2 currentScreen=viewPosition.xy/viewPosition.w;\nvec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;\ncurrentScreen.x*=aspectRatio;\nnextScreen.x*=aspectRatio;\nvec2 dir=normalize(nextScreen-currentScreen);\nvec2 normalDir=vec2(-dir.y,dir.x);\nnormalDir*=width/2.0;\nnormalDir.x/=aspectRatio;\nvec4 offset=vec4(normalDir*normal.w,0.0,0.0);\ngl_Position=viewPosition+offset;\n}","linePixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","outlineVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#include<bonesDeclaration>\n\nuniform float offset;\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#include<logDepthDeclaration>\nvoid main(void)\n{\nvec3 offsetPosition=position+normal*offset;\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(offsetPosition,1.0);\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#include<logDepthVertex>\n}\n","outlinePixelShader":"#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nuniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#include<logDepthFragment>\ngl_FragColor=color;\n}","layerVertexShader":"\nattribute vec2 position;\n\nuniform vec2 scale;\nuniform vec2 offset;\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvec2 shiftedPosition=position*scale+offset;\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\ngl_Position=vec4(shiftedPosition,0.0,1.0);\n}","layerPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n}","backgroundVertexShader":"precision highp float;\n#include<__decl__backgroundVertex>\n#include<helperFunctions>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normal);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#ifdef EQUIRECTANGULAR_RELFECTION_FOV\nmat3 screenToWorld=inverseMat3(mat3(finalWorld*viewProjection));\nvec3 segment=mix(vDirectionW,screenToWorld*vec3(0.0,0.0,1.0),abs(fFovMultiplier-1.0));\nif (fFovMultiplier<=1.0) {\nvDirectionW=normalize(segment);\n} else {\nvDirectionW=normalize(vDirectionW+(vDirectionW-segment));\n}\n#endif\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0 \nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n}\n","backgroundPixelShader":"#ifdef TEXTURELODSUPPORT\n#extension GL_EXT_shader_texture_lod : enable\n#endif\nprecision highp float;\n#include<__decl__backgroundFragment>\n#define RECIPROCAL_PI2 0.15915494\n\nuniform vec3 vEyePosition;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2; \n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n\n#ifndef SHADOWONLY\n#define SHADOWONLY;\n#endif\n#include<imageProcessingDeclaration>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<helperFunctions>\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n#include<imageProcessingFunctions>\n#include<clipPlaneFragmentDeclaration>\n\n#include<fogFragmentDeclaration>\n#ifdef REFLECTIONFRESNEL\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n#endif\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(0.0,1.0,0.0);\n#endif\n\nfloat shadow=1.;\nfloat globalShadow=0.;\nfloat shadowLightCount=0.;\n#include<lightFragment>[0..maxSimultaneousLights]\n#ifdef SHADOWINUSE\nglobalShadow/=shadowLightCount;\n#else\nglobalShadow=1.0;\n#endif\n\nvec3 reflectionColor=vec3(1.,1.,1.);\n#ifdef REFLECTION\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#ifdef REFLECTIONBLUR\nfloat reflectionLOD=vReflectionInfos.y;\n#ifdef TEXTURELODSUPPORT\n\nreflectionLOD=reflectionLOD*log2(vReflectionMicrosurfaceInfos.x)*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\nreflectionColor=sampleReflectionLod(reflectionSampler,reflectionCoords,reflectionLOD).rgb;\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD,0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec3 reflectionSpecularMid=sampleReflection(reflectionSampler,reflectionCoords).rgb;\nif(lodReflectionNormalizedDoubled<1.0){\nreflectionColor=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords).rgb,\nreflectionSpecularMid,\nlodReflectionNormalizedDoubled\n);\n} else {\nreflectionColor=mix(\nreflectionSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords).rgb,\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#else\nvec4 reflectionSample=sampleReflection(reflectionSampler,reflectionCoords);\nreflectionColor=reflectionSample.rgb;\n#endif\n#ifdef GAMMAREFLECTION\nreflectionColor=toLinearSpace(reflectionColor.rgb);\n#endif\n\nreflectionColor*=vReflectionInfos.x;\n#endif\n\nvec3 diffuseColor=vec3(1.,1.,1.);\nfloat finalAlpha=alpha;\n#ifdef DIFFUSE\nvec4 diffuseMap=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef GAMMADIFFUSE\ndiffuseMap.rgb=toLinearSpace(diffuseMap.rgb);\n#endif\n\ndiffuseMap.rgb*=vDiffuseInfos.y;\n#ifdef DIFFUSEHASALPHA\nfinalAlpha*=diffuseMap.a;\n#endif\ndiffuseColor=diffuseMap.rgb;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 colorBase=diffuseColor;\n#else\nvec3 colorBase=reflectionColor*diffuseColor;\n#endif\ncolorBase=max(colorBase,0.0);\n\n#ifdef USERGBCOLOR\nvec3 finalColor=colorBase;\n#else\nvec3 finalColor=colorBase.r*vPrimaryColor.rgb*vPrimaryColor.a;\nfinalColor+=colorBase.g*vSecondaryColor.rgb*vSecondaryColor.a;\nfinalColor+=colorBase.b*vTertiaryColor.rgb*vTertiaryColor.a;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 reflectionAmount=vReflectionControl.xxx;\nvec3 reflectionReflectance0=vReflectionControl.yyy;\nvec3 reflectionReflectance90=vReflectionControl.zzz;\nfloat VdotN=dot(normalize(vEyePosition),normalW);\nvec3 planarReflectionFresnel=fresnelSchlickEnvironmentGGX(clamp(VdotN,0.0,1.0),reflectionReflectance0,reflectionReflectance90,1.0);\nreflectionAmount*=planarReflectionFresnel;\n#ifdef REFLECTIONFALLOFF\nfloat reflectionDistanceFalloff=1.0-clamp(length(vPositionW.xyz-vBackgroundCenter)*vReflectionControl.w,0.0,1.0);\nreflectionDistanceFalloff*=reflectionDistanceFalloff;\nreflectionAmount*=reflectionDistanceFalloff;\n#endif\nfinalColor=mix(finalColor,reflectionColor,clamp(reflectionAmount,0.,1.));\n#endif\n#ifdef OPACITYFRESNEL\nfloat viewAngleToFloor=dot(normalW,normalize(vEyePosition-vBackgroundCenter));\n\nconst float startAngle=0.1;\nfloat fadeFactor=clamp(viewAngleToFloor/startAngle,0.0,1.0);\nfinalAlpha*=fadeFactor*fadeFactor;\n#endif\n\n#ifdef SHADOWINUSE\nfinalColor=mix(finalColor*shadowLevel,finalColor,globalShadow);\n#endif\n\nvec4 color=vec4(finalColor,finalAlpha);\n#include<fogFragment>\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\ncolor.rgb=clamp(color.rgb,0.,30.0);\n#else\n\ncolor=applyImageProcessing(color);\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#ifdef NOISE\ncolor.rgb=dither(vPositionW.xy,color.rgb);\n#endif\ngl_FragColor=color;\n}\n"};
  87801. BABYLON.Effect.IncludesShadersStore={"depthPrePass":"#ifdef DEPTHPREPASS\ngl_FragColor=vec4(0.,0.,0.,1.0);\nreturn;\n#endif","bonesDeclaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nattribute vec4 matricesIndicesExtra;\nattribute vec4 matricesWeightsExtra;\n#endif\n#endif","instancesDeclaration":"#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif","pointCloudVertexDeclaration":"#ifdef POINTSIZE\nuniform float pointSize;\n#endif","bumpVertexDeclaration":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#endif\n","clipPlaneVertexDeclaration":"#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif","fogVertexDeclaration":"#ifdef FOG\nvarying vec3 vFogDistance;\n#endif","morphTargetsVertexGlobalDeclaration":"#ifdef MORPHTARGETS\nuniform float morphTargetInfluences[NUM_MORPH_INFLUENCERS];\n#endif","morphTargetsVertexDeclaration":"#ifdef MORPHTARGETS\nattribute vec3 position{X};\n#ifdef MORPHTARGETS_NORMAL\nattribute vec3 normal{X};\n#endif\n#ifdef MORPHTARGETS_TANGENT\nattribute vec3 tangent{X};\n#endif\n#endif","logDepthDeclaration":"#ifdef LOGARITHMICDEPTH\nuniform float logarithmicDepthConstant;\nvarying float vFragmentDepth;\n#endif","morphTargetsVertex":"#ifdef MORPHTARGETS\npositionUpdated+=(position{X}-position)*morphTargetInfluences[{X}];\n#ifdef MORPHTARGETS_NORMAL\nnormalUpdated+=(normal{X}-normal)*morphTargetInfluences[{X}];\n#endif\n#ifdef MORPHTARGETS_TANGENT\ntangentUpdated.xyz+=(tangent{X}-tangent.xyz)*morphTargetInfluences[{X}];\n#endif\n#endif","instancesVertex":"#ifdef INSTANCES\nmat4 finalWorld=mat4(world0,world1,world2,world3);\n#else\nmat4 finalWorld=world;\n#endif","bonesVertex":"#if NUM_BONE_INFLUENCERS>0\nmat4 influence;\ninfluence=mBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence+=mBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence+=mBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence+=mBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif \nfinalWorld=finalWorld*influence;\n#endif","bumpVertex":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL)\nvec3 tbnNormal=normalize(normalUpdated);\nvec3 tbnTangent=normalize(tangentUpdated.xyz);\nvec3 tbnBitangent=cross(tbnNormal,tbnTangent)*tangentUpdated.w;\nvTBN=mat3(finalWorld)*mat3(tbnTangent,tbnBitangent,tbnNormal);\n#endif\n#endif","clipPlaneVertex":"#ifdef CLIPPLANE\nfClipDistance=dot(worldPos,vClipPlane);\n#endif","fogVertex":"#ifdef FOG\nvFogDistance=(view*worldPos).xyz;\n#endif","shadowsVertex":"#ifdef SHADOWS\n#if defined(SHADOW{X}) && !defined(SHADOWCUBE{X})\nvPositionFromLight{X}=lightMatrix{X}*worldPos;\nvDepthMetric{X}=((vPositionFromLight{X}.z+light{X}.depthValues.x)/(light{X}.depthValues.y));\n#endif\n#endif","pointCloudVertex":"#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif","logDepthVertex":"#ifdef LOGARITHMICDEPTH\nvFragmentDepth=1.0+gl_Position.w;\ngl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\n#endif","helperFunctions":"const float PI=3.1415926535897932384626433832795;\nconst float LinearEncodePowerApprox=2.2;\nconst float GammaEncodePowerApprox=1.0/LinearEncodePowerApprox;\nconst vec3 LuminanceEncodeApprox=vec3(0.2126,0.7152,0.0722);\nmat3 transposeMat3(mat3 inMatrix) {\nvec3 i0=inMatrix[0];\nvec3 i1=inMatrix[1];\nvec3 i2=inMatrix[2];\nmat3 outMatrix=mat3(\nvec3(i0.x,i1.x,i2.x),\nvec3(i0.y,i1.y,i2.y),\nvec3(i0.z,i1.z,i2.z)\n);\nreturn outMatrix;\n}\n\nmat3 inverseMat3(mat3 inMatrix) {\nfloat a00=inMatrix[0][0],a01=inMatrix[0][1],a02=inMatrix[0][2];\nfloat a10=inMatrix[1][0],a11=inMatrix[1][1],a12=inMatrix[1][2];\nfloat a20=inMatrix[2][0],a21=inMatrix[2][1],a22=inMatrix[2][2];\nfloat b01=a22*a11-a12*a21;\nfloat b11=-a22*a10+a12*a20;\nfloat b21=a21*a10-a11*a20;\nfloat det=a00*b01+a01*b11+a02*b21;\nreturn mat3(b01,(-a22*a01+a02*a21),(a12*a01-a02*a11),\nb11,(a22*a00-a02*a20),(-a12*a00+a02*a10),\nb21,(-a21*a00+a01*a20),(a11*a00-a01*a10))/det;\n}\nfloat computeFallOff(float value,vec2 clipSpace,float frustumEdgeFalloff)\n{\nfloat mask=smoothstep(1.0-frustumEdgeFalloff,1.0,clamp(dot(clipSpace,clipSpace),0.,1.));\nreturn mix(value,1.0,mask);\n}\nvec3 applyEaseInOut(vec3 x){\nreturn x*x*(3.0-2.0*x);\n}\nvec3 toLinearSpace(vec3 color)\n{\nreturn pow(color,vec3(LinearEncodePowerApprox));\n}\nvec3 toGammaSpace(vec3 color)\n{\nreturn pow(color,vec3(GammaEncodePowerApprox));\n}\nfloat square(float value)\n{\nreturn value*value;\n}\nfloat getLuminance(vec3 color)\n{\nreturn clamp(dot(color,LuminanceEncodeApprox),0.,1.);\n}\n\nfloat getRand(vec2 seed) {\nreturn fract(sin(dot(seed.xy ,vec2(12.9898,78.233)))*43758.5453);\n}\nvec3 dither(vec2 seed,vec3 color) {\nfloat rand=getRand(seed);\ncolor+=mix(-0.5/255.0,0.5/255.0,rand);\ncolor=max(color,0.0);\nreturn color;\n}","lightFragmentDeclaration":"#ifdef LIGHT{X}\nuniform vec4 vLightData{X};\nuniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec3 vLightSpecular{X};\n#else\nvec3 vLightSpecular{X}=vec3(0.);\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\nuniform sampler2D shadowSampler{X};\nuniform mat4 lightMatrix{X};\n#endif\nuniform vec4 shadowsInfo{X};\nuniform vec2 depthValues{X};\n#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};\n#endif\n#ifdef HEMILIGHT{X}\nuniform vec3 vLightGround{X};\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#endif","lightsFragmentFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n#ifdef NDOTL\nfloat ndl;\n#endif\n};\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 lightVectorW;\nfloat attenuation=1.0;\nif (lightData.w == 0.)\n{\nvec3 direction=lightData.xyz-vPositionW;\nattenuation=max(0.,1.0-length(direction)/range);\nlightVectorW=normalize(direction);\n}\nelse\n{\nlightVectorW=normalize(-lightData.xyz);\n}\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 direction=lightData.xyz-vPositionW;\nvec3 lightVectorW=normalize(direction);\nfloat attenuation=max(0.,1.0-length(direction)/range);\n\nfloat cosAngle=max(0.,dot(lightDirection.xyz,-lightVectorW));\nif (cosAngle>=lightDirection.w)\n{\ncosAngle=max(0.,pow(cosAngle,lightData.w));\nattenuation*=cosAngle;\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nresult.diffuse=vec3(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3(0.);\n#endif\n#ifdef NDOTL\nresult.ndl=0.;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {\nlightingInfo result;\n\nfloat ndl=dot(vNormal,lightData.xyz)*0.5+0.5;\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=mix(groundColor,diffuseColor,ndl);\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightData.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor;\n#endif\nreturn result;\n}\nvec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){\nvec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);\nstrq/=strq.w;\nvec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;\n#ifdef PBR\ntextureColor=toLinearSpace(textureColor);\n#endif\nreturn textureColor;\n}","lightUboDeclaration":"#ifdef LIGHT{X}\nuniform Light{X}\n{\nvec4 vLightData;\nvec4 vLightDiffuse;\nvec3 vLightSpecular;\n#ifdef SPOTLIGHT{X}\nvec4 vLightDirection;\n#endif\n#ifdef HEMILIGHT{X}\nvec3 vLightGround;\n#endif\nvec4 shadowsInfo;\nvec2 depthValues;\n} light{X};\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\nuniform sampler2D shadowSampler{X};\nuniform mat4 lightMatrix{X};\n#endif\n#endif\n#endif","defaultVertexDeclaration":"\nuniform mat4 viewProjection;\nuniform mat4 view;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n","defaultFragmentDeclaration":"uniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifndef REFRACTIONMAP_3D\nuniform mat4 refractionMatrix;\n#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;\nuniform vec4 refractionRightColor;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\n#endif\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_SKYBOX\n#else\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#endif","defaultUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nvec4 diffuseLeftColor;\nvec4 diffuseRightColor;\nvec4 opacityParts;\nvec4 reflectionLeftColor;\nvec4 reflectionRightColor;\nvec4 refractionLeftColor;\nvec4 refractionRightColor;\nvec4 emissiveLeftColor; \nvec4 emissiveRightColor;\nvec2 vDiffuseInfos;\nvec2 vAmbientInfos;\nvec2 vOpacityInfos;\nvec2 vReflectionInfos;\nvec3 vReflectionPosition;\nvec3 vReflectionSize;\nvec2 vEmissiveInfos;\nvec2 vLightmapInfos;\nvec2 vSpecularInfos;\nvec3 vBumpInfos;\nmat4 diffuseMatrix;\nmat4 ambientMatrix;\nmat4 opacityMatrix;\nmat4 reflectionMatrix;\nmat4 emissiveMatrix;\nmat4 lightmapMatrix;\nmat4 specularMatrix;\nmat4 bumpMatrix; \nvec4 vTangentSpaceParams;\nmat4 refractionMatrix;\nvec4 vRefractionInfos;\nvec4 vSpecularColor;\nvec3 vEmissiveColor;\nvec4 vDiffuseColor;\nfloat pointSize; \n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","shadowsFragmentFunctions":"#ifdef SHADOWS\n#ifndef SHADOWFLOAT\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x;\n#endif\nif (depth>shadow)\n{\nreturn darkness;\n}\nreturn 1.0;\n}\nfloat computeShadowWithPCFCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat visibility=1.;\nvec3 poissonDisk[4];\npoissonDisk[0]=vec3(-1.0,1.0,-1.0);\npoissonDisk[1]=vec3(1.0,-1.0,-1.0);\npoissonDisk[2]=vec3(-1.0,-1.0,-1.0);\npoissonDisk[3]=vec3(1.0,-1.0,1.0);\n\n#ifndef SHADOWFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<depth) visibility-=0.25;\n#else\nif (textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<depth) visibility-=0.25;\n#endif\nreturn min(1.0,visibility+darkness);\n}\nfloat computeShadowWithESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness); \nreturn esm;\n}\nfloat computeShadowWithCloseESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn esm;\n}\nfloat computeShadow(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadow=texture2D(shadowSampler,uv).x;\n#endif\nif (shadowPixelDepth>shadow)\n{\nreturn computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff);\n}\nreturn 1.;\n}\nfloat computeShadowWithPCF(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float mapSize,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\nfloat visibility=1.;\nvec2 poissonDisk[4];\npoissonDisk[0]=vec2(-0.94201624,-0.39906216);\npoissonDisk[1]=vec2(0.94558609,-0.76890725);\npoissonDisk[2]=vec2(-0.094184101,-0.92938870);\npoissonDisk[3]=vec2(0.34495938,0.29387760);\n\n#ifndef SHADOWFLOAT\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<shadowPixelDepth) visibility-=0.25;\n#else\nif (texture2D(shadowSampler,uv+poissonDisk[0]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[1]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[2]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[3]*mapSize).x<shadowPixelDepth) visibility-=0.25;\n#endif\nreturn computeFallOff(min(1.0,visibility+darkness),clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithCloseESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0); \n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\n#endif\n","fresnelFunction":"#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection,vec3 worldNormal,float bias,float power)\n{\nfloat fresnelTerm=pow(bias+abs(dot(viewDirection,worldNormal)),power);\nreturn clamp(fresnelTerm,0.,1.);\n}\n#endif","reflectionFunction":"#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\nvec3 parallaxCorrectNormal( vec3 vertexPos,vec3 origVec,vec3 cubeSize,vec3 cubePos ) {\n\nvec3 invOrigVec=vec3(1.0,1.0,1.0)/origVec;\nvec3 halfSize=cubeSize*0.5;\nvec3 intersecAtMaxPlane=(cubePos+halfSize-vertexPos)*invOrigVec;\nvec3 intersecAtMinPlane=(cubePos-halfSize-vertexPos)*invOrigVec;\n\nvec3 largestIntersec=max(intersecAtMaxPlane,intersecAtMinPlane);\n\nfloat distance=min(min(largestIntersec.x,largestIntersec.y),largestIntersec.z);\n\nvec3 intersectPositionWS=vertexPos+origVec*distance;\n\nreturn intersectPositionWS-cubePos;\n}\n#endif\nvec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvec3 direction=vDirectionW;\nfloat t=clamp(direction.y*-0.5+0.5,0.,1.0);\nfloat s=atan(direction.z,direction.x)*RECIPROCAL_PI2+0.5;\n#ifdef REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED\nreturn vec3(1.0-s,t,0);\n#else\nreturn vec3(s,t,0);\n#endif\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\nvec3 cameraToVertex=normalize(worldPos.xyz-vEyePosition.xyz);\nvec3 r=reflect(cameraToVertex,worldNormal);\nfloat t=clamp(r.y*-0.5+0.5,0.,1.0);\nfloat s=atan(r.z,r.x)*RECIPROCAL_PI2+0.5;\nreturn vec3(s,t,0);\n#endif\n#ifdef REFLECTIONMAP_SPHERICAL\nvec3 viewDir=normalize(vec3(view*worldPos));\nvec3 viewNormal=normalize(vec3(view*vec4(worldNormal,0.0)));\nvec3 r=reflect(viewDir,viewNormal);\nr.z=r.z-1.0;\nfloat m=2.0*length(r);\nreturn vec3(r.x/m+0.5,1.0-r.y/m-0.5,0);\n#endif\n#ifdef REFLECTIONMAP_PLANAR\nvec3 viewDir=worldPos.xyz-vEyePosition.xyz;\nvec3 coords=normalize(reflect(viewDir,worldNormal));\nreturn vec3(reflectionMatrix*vec4(coords,1));\n#endif\n#ifdef REFLECTIONMAP_CUBIC\nvec3 viewDir=worldPos.xyz-vEyePosition.xyz;\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef INVERTCUBICMAP\ncoords.y=1.0-coords.y;\n#endif\n#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\ncoords=parallaxCorrectNormal(worldPos.xyz,coords,vReflectionSize,vReflectionPosition );\n#endif\nreturn vec3(reflectionMatrix*vec4(coords,0));\n#endif\n#ifdef REFLECTIONMAP_PROJECTION\nreturn vec3(reflectionMatrix*(view*worldPos));\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nreturn vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\nreturn vec3(0,0,0);\n#endif\n}","imageProcessingDeclaration":"#ifdef EXPOSURE\nuniform float exposureLinear;\n#endif\n#ifdef CONTRAST\nuniform float contrast;\n#endif\n#ifdef VIGNETTE\nuniform vec2 vInverseScreenSize;\nuniform vec4 vignetteSettings1;\nuniform vec4 vignetteSettings2;\n#endif\n#ifdef COLORCURVES\nuniform vec4 vCameraColorCurveNegative;\nuniform vec4 vCameraColorCurveNeutral;\nuniform vec4 vCameraColorCurvePositive;\n#endif\n#ifdef COLORGRADING\n#ifdef COLORGRADING3D\nuniform highp sampler3D txColorTransform;\n#else\nuniform sampler2D txColorTransform;\n#endif\nuniform vec4 colorTransformSettings;\n#endif","imageProcessingFunctions":"#if defined(COLORGRADING) && !defined(COLORGRADING3D)\n\nvec3 sampleTexture3D(sampler2D colorTransform,vec3 color,vec2 sampler3dSetting)\n{\nfloat sliceSize=2.0*sampler3dSetting.x; \n#ifdef SAMPLER3DGREENDEPTH\nfloat sliceContinuous=(color.g-sampler3dSetting.x)*sampler3dSetting.y;\n#else\nfloat sliceContinuous=(color.b-sampler3dSetting.x)*sampler3dSetting.y;\n#endif\nfloat sliceInteger=floor(sliceContinuous);\n\n\nfloat sliceFraction=sliceContinuous-sliceInteger;\n#ifdef SAMPLER3DGREENDEPTH\nvec2 sliceUV=color.rb;\n#else\nvec2 sliceUV=color.rg;\n#endif\nsliceUV.x*=sliceSize;\nsliceUV.x+=sliceInteger*sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice0Color=texture2D(colorTransform,sliceUV);\nsliceUV.x+=sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice1Color=texture2D(colorTransform,sliceUV);\nvec3 result=mix(slice0Color.rgb,slice1Color.rgb,sliceFraction);\n#ifdef SAMPLER3DBGRMAP\ncolor.rgb=result.rgb;\n#else\ncolor.rgb=result.bgr;\n#endif\nreturn color;\n}\n#endif\nvec4 applyImageProcessing(vec4 result) {\n#ifdef EXPOSURE\nresult.rgb*=exposureLinear;\n#endif\n#ifdef VIGNETTE\n\nvec2 viewportXY=gl_FragCoord.xy*vInverseScreenSize;\nviewportXY=viewportXY*2.0-1.0;\nvec3 vignetteXY1=vec3(viewportXY*vignetteSettings1.xy+vignetteSettings1.zw,1.0);\nfloat vignetteTerm=dot(vignetteXY1,vignetteXY1);\nfloat vignette=pow(vignetteTerm,vignetteSettings2.w);\n\nvec3 vignetteColor=vignetteSettings2.rgb;\n#ifdef VIGNETTEBLENDMODEMULTIPLY\nvec3 vignetteColorMultiplier=mix(vignetteColor,vec3(1,1,1),vignette);\nresult.rgb*=vignetteColorMultiplier;\n#endif\n#ifdef VIGNETTEBLENDMODEOPAQUE\nresult.rgb=mix(vignetteColor,result.rgb,vignette);\n#endif\n#endif\n#ifdef TONEMAPPING\nconst float tonemappingCalibration=1.590579;\nresult.rgb=1.0-exp2(-tonemappingCalibration*result.rgb);\n#endif\n\nresult.rgb=toGammaSpace(result.rgb);\nresult.rgb=clamp(result.rgb,0.0,1.0);\n#ifdef CONTRAST\n\nvec3 resultHighContrast=applyEaseInOut(result.rgb);\nif (contrast<1.0) {\n\nresult.rgb=mix(vec3(0.5,0.5,0.5),result.rgb,contrast);\n} else {\n\nresult.rgb=mix(result.rgb,resultHighContrast,contrast-1.0);\n}\n#endif\n\n#ifdef COLORGRADING\nvec3 colorTransformInput=result.rgb*colorTransformSettings.xxx+colorTransformSettings.yyy;\n#ifdef COLORGRADING3D\nvec3 colorTransformOutput=texture(txColorTransform,colorTransformInput).rgb;\n#else\nvec3 colorTransformOutput=sampleTexture3D(txColorTransform,colorTransformInput,colorTransformSettings.yz).rgb;\n#endif\nresult.rgb=mix(result.rgb,colorTransformOutput,colorTransformSettings.www);\n#endif\n#ifdef COLORCURVES\n\nfloat luma=getLuminance(result.rgb);\nvec2 curveMix=clamp(vec2(luma*3.0-1.5,luma*-3.0+1.5),vec2(0.0),vec2(1.0));\nvec4 colorCurve=vCameraColorCurveNeutral+curveMix.x*vCameraColorCurvePositive-curveMix.y*vCameraColorCurveNegative;\nresult.rgb*=colorCurve.rgb;\nresult.rgb=mix(vec3(luma),result.rgb,colorCurve.a);\n#endif\nreturn result;\n}","bumpFragmentFunctions":"#ifdef BUMP\n#if BUMPDIRECTUV == 1\n#define vBumpUV vMainUV1\n#elif BUMPDIRECTUV == 2\n#define vBumpUV vMainUV2\n#else\nvarying vec2 vBumpUV;\n#endif\nuniform sampler2D bumpSampler;\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n\nmat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv)\n{\n\nuv=gl_FrontFacing ? uv : -uv;\n\nvec3 dp1=dFdx(p);\nvec3 dp2=dFdy(p);\nvec2 duv1=dFdx(uv);\nvec2 duv2=dFdy(uv);\n\nvec3 dp2perp=cross(dp2,normal);\nvec3 dp1perp=cross(normal,dp1);\nvec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;\nvec3 bitangent=dp2perp*duv1.y+dp1perp*duv2.y;\n\ntangent*=vTangentSpaceParams.x;\nbitangent*=vTangentSpaceParams.y;\n\nfloat invmax=inversesqrt(max(dot(tangent,tangent),dot(bitangent,bitangent)));\nreturn mat3(tangent*invmax,bitangent*invmax,normal);\n}\nvec3 perturbNormal(mat3 cotangentFrame,vec2 uv)\n{\nvec3 map=texture2D(bumpSampler,uv).xyz;\nmap=map*2.0-1.0;\n#ifdef NORMALXYSCALE\nmap=normalize(map*vec3(vBumpInfos.y,vBumpInfos.y,1.0));\n#endif\nreturn normalize(cotangentFrame*map);\n}\n#ifdef PARALLAX\nconst float minSamples=4.;\nconst float maxSamples=15.;\nconst int iMaxSamples=15;\n\nvec2 parallaxOcclusion(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale) {\nfloat parallaxLimit=length(vViewDirCoT.xy)/vViewDirCoT.z;\nparallaxLimit*=parallaxScale;\nvec2 vOffsetDir=normalize(vViewDirCoT.xy);\nvec2 vMaxOffset=vOffsetDir*parallaxLimit;\nfloat numSamples=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));\nfloat stepSize=1.0/numSamples;\n\nfloat currRayHeight=1.0;\nvec2 vCurrOffset=vec2(0,0);\nvec2 vLastOffset=vec2(0,0);\nfloat lastSampledHeight=1.0;\nfloat currSampledHeight=1.0;\nfor (int i=0; i<iMaxSamples; i++)\n{\ncurrSampledHeight=texture2D(bumpSampler,vBumpUV+vCurrOffset).w;\n\nif (currSampledHeight>currRayHeight)\n{\nfloat delta1=currSampledHeight-currRayHeight;\nfloat delta2=(currRayHeight+stepSize)-lastSampledHeight;\nfloat ratio=delta1/(delta1+delta2);\nvCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;\n\nbreak;\n}\nelse\n{\ncurrRayHeight-=stepSize;\nvLastOffset=vCurrOffset;\nvCurrOffset+=stepSize*vMaxOffset;\nlastSampledHeight=currSampledHeight;\n}\n}\nreturn vCurrOffset;\n}\nvec2 parallaxOffset(vec3 viewDir,float heightScale)\n{\n\nfloat height=texture2D(bumpSampler,vBumpUV).w;\nvec2 texCoordOffset=heightScale*viewDir.xy*height;\nreturn -texCoordOffset;\n}\n#endif\n#endif","clipPlaneFragmentDeclaration":"#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif","fogFragmentDeclaration":"#ifdef FOG\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying vec3 vFogDistance;\nfloat CalcFogFactor()\n{\nfloat fogCoeff=1.0;\nfloat fogStart=vFogInfos.y;\nfloat fogEnd=vFogInfos.z;\nfloat fogDensity=vFogInfos.w;\nfloat fogDistance=length(vFogDistance);\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff=(fogEnd-fogDistance)/(fogEnd-fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDistance*fogDensity*fogDensity);\n}\nreturn clamp(fogCoeff,0.0,1.0);\n}\n#endif","clipPlaneFragment":"#ifdef CLIPPLANE\nif (fClipDistance>0.0)\n{\ndiscard;\n}\n#endif","bumpFragment":"vec2 uvOffset=vec2(0.0,0.0);\n#if defined(BUMP) || defined(PARALLAX)\n#ifdef NORMALXYSCALE\nfloat normalScale=1.0;\n#else \nfloat normalScale=vBumpInfos.y;\n#endif\n#if defined(TANGENT) && defined(NORMAL)\nmat3 TBN=vTBN;\n#else\nmat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,vBumpUV);\n#endif\n#endif\n#ifdef PARALLAX\nmat3 invTBN=transposeMat3(TBN);\n#ifdef PARALLAXOCCLUSION\nuvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,vBumpUV,vBumpInfos.z);\n#else\nuvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z);\n#endif\n#endif\n#ifdef BUMP\nnormalW=perturbNormal(TBN,vBumpUV+uvOffset);\n#endif","lightFragment":"#ifdef LIGHT{X}\n#if defined(SHADOWONLY) || (defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X}))\n\n#else\n#ifdef PBR\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#else\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,glossiness);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\ninfo.diffuse*=computeProjectionTextureDiffuseLighting(projectionLightSampler{X},textureProjectionMatrix{X});\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCLOSEESM{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithCloseESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithCloseESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#else\n#ifdef SHADOWESM{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#else \n#ifdef SHADOWPCF{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithPCFCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadowWithPCF(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#else\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadow(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#endif\n#endif\n#endif\n#ifdef SHADOWONLY\n#ifndef SHADOWINUSE\n#define SHADOWINUSE\n#endif\nglobalShadow+=shadow;\nshadowLightCount+=1.0;\n#endif\n#else\nshadow=1.;\n#endif\n#ifndef SHADOWONLY\n#ifdef CUSTOMUSERLIGHTING\ndiffuseBase+=computeCustomDiffuseLighting(info,diffuseBase,shadow);\n#ifdef SPECULARTERM\nspecularBase+=computeCustomSpecularLighting(info,specularBase,shadow);\n#endif\n#elif defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\ndiffuseBase+=lightmapColor*shadow;\n#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nspecularBase+=info.specular*shadow*lightmapColor;\n#endif\n#endif\n#else\ndiffuseBase+=info.diffuse*shadow;\n#ifdef SPECULARTERM\nspecularBase+=info.specular*shadow;\n#endif\n#endif\n#endif\n#endif","logDepthFragment":"#ifdef LOGARITHMICDEPTH\ngl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5;\n#endif","fogFragment":"#ifdef FOG\nfloat fog=CalcFogFactor();\ncolor.rgb=fog*color.rgb+(1.0-fog)*vFogColor;\n#endif","pbrVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef ALBEDO\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#ifdef REFLECTIVITY \nuniform vec3 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform mat4 microSurfaceSamplerMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n","pbrFragmentDeclaration":"uniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\n\nuniform vec4 vLightingIntensity;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\n\n#ifdef ALBEDO\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef REFLECTIVITY\nuniform vec3 vReflectivityInfos;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\n#endif\n\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif","pbrUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec2 vAlbedoInfos;\nuniform vec3 vAmbientInfos;\nuniform vec2 vOpacityInfos;\nuniform vec2 vEmissiveInfos;\nuniform vec2 vLightmapInfos;\nuniform vec3 vReflectivityInfos;\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform vec4 vRefractionInfos;\nuniform vec2 vReflectionInfos;\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \nuniform vec3 vBumpInfos;\nuniform mat4 albedoMatrix;\nuniform mat4 ambientMatrix;\nuniform mat4 opacityMatrix;\nuniform mat4 emissiveMatrix;\nuniform mat4 lightmapMatrix;\nuniform mat4 reflectivityMatrix;\nuniform mat4 microSurfaceSamplerMatrix;\nuniform mat4 bumpMatrix;\nuniform vec2 vTangentSpaceParams;\nuniform mat4 refractionMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\nuniform vec4 vLightingIntensity;\nuniform vec3 vRefractionMicrosurfaceInfos;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\nuniform float pointSize;\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","pbrFunctions":"\n#define RECIPROCAL_PI2 0.15915494\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\n\nconst float kRougnhessToAlphaScale=0.1;\nconst float kRougnhessToAlphaOffset=0.29248125;\nfloat convertRoughnessToAverageSlope(float roughness)\n{\n\nconst float kMinimumVariance=0.0005;\nfloat alphaG=square(roughness)+kMinimumVariance;\nreturn alphaG;\n}\n\nfloat smithVisibilityG1_TrowbridgeReitzGGX(float dot,float alphaG)\n{\nfloat tanSquared=(1.0-dot*dot)/(dot*dot);\nreturn 2.0/(1.0+sqrt(1.0+alphaG*alphaG*tanSquared));\n}\nfloat smithVisibilityG_TrowbridgeReitzGGX_Walter(float NdotL,float NdotV,float alphaG)\n{\nreturn smithVisibilityG1_TrowbridgeReitzGGX(NdotL,alphaG)*smithVisibilityG1_TrowbridgeReitzGGX(NdotV,alphaG);\n}\n\n\nfloat normalDistributionFunction_TrowbridgeReitzGGX(float NdotH,float alphaG)\n{\n\n\n\nfloat a2=square(alphaG);\nfloat d=NdotH*NdotH*(a2-1.0)+1.0;\nreturn a2/(PI*d*d);\n}\nvec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90)\n{\nreturn reflectance0+(reflectance90-reflectance0)*pow(clamp(1.0-VdotH,0.,1.),5.0);\n}\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n\nvec3 computeSpecularTerm(float NdotH,float NdotL,float NdotV,float VdotH,float roughness,vec3 reflectance0,vec3 reflectance90)\n{\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\nfloat distribution=normalDistributionFunction_TrowbridgeReitzGGX(NdotH,alphaG);\nfloat visibility=smithVisibilityG_TrowbridgeReitzGGX_Walter(NdotL,NdotV,alphaG);\nvisibility/=(4.0*NdotL*NdotV); \nfloat specTerm=max(0.,visibility*distribution)*NdotL;\nvec3 fresnel=fresnelSchlickGGX(VdotH,reflectance0,reflectance90);\nreturn fresnel*specTerm;\n}\nfloat computeDiffuseTerm(float NdotL,float NdotV,float VdotH,float roughness)\n{\n\n\nfloat diffuseFresnelNV=pow(clamp(1.0-NdotL,0.000001,1.),5.0);\nfloat diffuseFresnelNL=pow(clamp(1.0-NdotV,0.000001,1.),5.0);\nfloat diffuseFresnel90=0.5+2.0*VdotH*VdotH*roughness;\nfloat fresnel =\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNL) *\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNV);\nreturn fresnel*NdotL/PI;\n}\nfloat adjustRoughnessFromLightProperties(float roughness,float lightRadius,float lightDistance)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\n\nfloat lightRoughness=lightRadius/lightDistance;\n\nfloat totalRoughness=clamp(lightRoughness+roughness,0.,1.);\nreturn totalRoughness;\n#else\nreturn roughness;\n#endif\n}\nfloat computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor)\n{\nconst float kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;\nfloat reflectivityLuminance=getLuminance(reflectivityColor);\nfloat reflectivityLuma=sqrt(reflectivityLuminance);\nmicroSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;\nreturn microSurface;\n}\n\n\nfloat fresnelGrazingReflectance(float reflectance0) {\nfloat reflectance90=clamp(reflectance0*25.0,0.0,1.0);\nreturn reflectance90;\n}\n\n\n#define UNPACK_LOD(x) (1.0-x)*255.0\nfloat getLodFromAlphaG(float cubeMapDimensionPixels,float alphaG,float NdotV) {\nfloat microsurfaceAverageSlope=alphaG;\n\n\n\n\n\n\nmicrosurfaceAverageSlope*=sqrt(abs(NdotV));\nfloat microsurfaceAverageSlopeTexels=microsurfaceAverageSlope*cubeMapDimensionPixels;\nfloat lod=log2(microsurfaceAverageSlopeTexels);\nreturn lod;\n}\nfloat environmentRadianceOcclusion(float ambientOcclusion,float NdotVUnclamped) {\n\n\nfloat temp=NdotVUnclamped+ambientOcclusion;\nreturn clamp(square(temp)-1.0+ambientOcclusion,0.0,1.0);\n}\nfloat environmentHorizonOcclusion(vec3 reflection,vec3 normal) {\n\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflection.z*=-1.0;\n#endif\nfloat temp=clamp( 1.0+1.1*dot(reflection,normal),0.0,1.0);\nreturn square(temp);\n}","harmonicsFunctions":"#ifdef USESPHERICALFROMREFLECTIONMAP\nuniform vec3 vSphericalX;\nuniform vec3 vSphericalY;\nuniform vec3 vSphericalZ;\nuniform vec3 vSphericalXX_ZZ;\nuniform vec3 vSphericalYY_ZZ;\nuniform vec3 vSphericalZZ;\nuniform vec3 vSphericalXY;\nuniform vec3 vSphericalYZ;\nuniform vec3 vSphericalZX;\nvec3 quaternionVectorRotation_ScaledSqrtTwo(vec4 Q,vec3 V){\nvec3 T=cross(Q.xyz,V);\nT+=Q.www*V;\nreturn cross(Q.xyz,T)+V;\n}\nvec3 environmentIrradianceJones(vec3 normal)\n{\n\n\n\n\n\n\n\n\n\nfloat Nx=normal.x;\nfloat Ny=normal.y;\nfloat Nz=normal.z;\nvec3 C1=vSphericalZZ.rgb;\nvec3 Cx=vSphericalX.rgb;\nvec3 Cy=vSphericalY.rgb;\nvec3 Cz=vSphericalZ.rgb;\nvec3 Cxx_zz=vSphericalXX_ZZ.rgb;\nvec3 Cyy_zz=vSphericalYY_ZZ.rgb;\nvec3 Cxy=vSphericalXY.rgb;\nvec3 Cyz=vSphericalYZ.rgb;\nvec3 Czx=vSphericalZX.rgb;\nvec3 a1=Cyy_zz*Ny+Cy;\nvec3 a2=Cyz*Nz+a1;\nvec3 b1=Czx*Nz+Cx;\nvec3 b2=Cxy*Ny+b1;\nvec3 b3=Cxx_zz*Nx+b2;\nvec3 t1=Cz*Nz+C1;\nvec3 t2=a2*Ny+t1;\nvec3 t3=b3*Nx+t2;\nreturn t3;\n}\n#endif","pbrLightFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n};\nfloat computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range)\n{ \n#ifdef USEPHYSICALLIGHTFALLOFF\nfloat lightDistanceFalloff=1.0/((lightDistanceSquared+0.001));\n#else\nfloat lightDistanceFalloff=max(0.,1.0-length(lightOffset)/range);\n#endif\nreturn lightDistanceFalloff;\n}\nfloat computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent)\n{\nfloat falloff=0.0;\n#ifdef USEPHYSICALLIGHTFALLOFF\nconst float kMinusLog2ConeAngleIntensityRatio=6.64385618977; \n\n\n\n\n\nfloat concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);\n\n\nvec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);\nfalloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));\n#else\nfloat cosAngle=max(0.000000000000001,dot(-lightDirection,directionToLightCenterW));\nif (cosAngle>=cosHalfAngle)\n{\nfalloff=max(0.,pow(cosAngle,exponent));\n}\n#endif\nreturn falloff;\n}\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\nvec3 lightDirection;\nfloat attenuation=1.0;\nfloat lightDistance;\n\nif (lightData.w == 0.)\n{\nvec3 lightOffset=lightData.xyz-vPositionW;\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nattenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\nlightDistance=sqrt(lightDistanceSquared);\nlightDirection=normalize(lightOffset);\n}\n\nelse\n{\nlightDistance=length(-lightData.xyz);\nlightDirection=normalize(-lightData.xyz);\n}\n\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+lightDirection);\nNdotL=clamp(dot(vNormal,lightDirection),0.00000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\nvec3 lightOffset=lightData.xyz-vPositionW;\nvec3 directionToLightCenterW=normalize(lightOffset);\n\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nfloat attenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\n\nfloat directionalAttenuation=computeDirectionalLightFalloff(lightDirection.xyz,directionToLightCenterW,lightDirection.w,lightData.w);\nattenuation*=directionalAttenuation;\n\nfloat lightDistance=sqrt(lightDistanceSquared);\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+directionToLightCenterW);\nNdotL=clamp(dot(vNormal,directionToLightCenterW),0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\n\n\n\nNdotL=dot(vNormal,lightData.xyz)*0.5+0.5;\nresult.diffuse=mix(groundColor,diffuseColor,NdotL);\n#ifdef SPECULARTERM\n\nvec3 lightVectorW=normalize(lightData.xyz);\nvec3 H=normalize(viewDirectionW+lightVectorW);\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nNdotL=clamp(NdotL,0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor;\n#endif\nreturn result;\n}","mrtFragmentDeclaration":"#if __VERSION__>=200\nlayout(location=0) out vec4 glFragData[{X}];\n#endif\n","bones300Declaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nin vec4 matricesIndices;\nin vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nin vec4 matricesIndicesExtra;\nin vec4 matricesWeightsExtra;\n#endif\n#endif","instances300Declaration":"#ifdef INSTANCES\nin vec4 world0;\nin vec4 world1;\nin vec4 world2;\nin vec4 world3;\n#else\nuniform mat4 world;\n#endif","kernelBlurFragment":"#ifdef DOF\nsampleDepth=sampleDistance(sampleCoord{X});\nfactor=clamp(1.0-((centerSampleDepth-sampleDepth)/centerSampleDepth),0.0,1.0);\ncomputedWeight=KERNEL_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCoord{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCoord{X})*computedWeight;\n#endif","kernelBlurFragment2":"#ifdef DOF\nsampleDepth=sampleDistance(sampleCoord{X});\nfactor=clamp(1.0-((centerSampleDepth-sampleDepth)/centerSampleDepth),0.0,1.0);\ncomputedWeight=KERNEL_DEP_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_DEP_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})*computedWeight;\n#endif","kernelBlurVaryingDeclaration":"varying vec2 sampleCoord{X};","kernelBlurVertex":"sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};","backgroundVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\nuniform float shadowLevel;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif","backgroundFragmentDeclaration":" uniform vec4 vPrimaryColor;\nuniform vec4 vSecondaryColor;\nuniform vec4 vTertiaryColor;\nuniform float shadowLevel;\nuniform float alpha;\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif","backgroundUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec4 vPrimaryColor;\nuniform vec4 vSecondaryColor;\nuniform vec4 vTertiaryColor;\nuniform vec2 vDiffuseInfos;\nuniform vec2 vReflectionInfos;\nuniform mat4 diffuseMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\nuniform float pointSize;\nuniform float shadowLevel;\nuniform float alpha;\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};"};
  87802. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  87803. var BABYLON;
  87804. (function (BABYLON) {
  87805. var GridMaterialDefines = /** @class */ (function (_super) {
  87806. __extends(GridMaterialDefines, _super);
  87807. function GridMaterialDefines() {
  87808. var _this = _super.call(this) || this;
  87809. _this.TRANSPARENT = false;
  87810. _this.FOG = false;
  87811. _this.PREMULTIPLYALPHA = false;
  87812. _this.rebuild();
  87813. return _this;
  87814. }
  87815. return GridMaterialDefines;
  87816. }(BABYLON.MaterialDefines));
  87817. /**
  87818. * The grid materials allows you to wrap any shape with a grid.
  87819. * Colors are customizable.
  87820. */
  87821. var GridMaterial = /** @class */ (function (_super) {
  87822. __extends(GridMaterial, _super);
  87823. /**
  87824. * constructor
  87825. * @param name The name given to the material in order to identify it afterwards.
  87826. * @param scene The scene the material is used in.
  87827. */
  87828. function GridMaterial(name, scene) {
  87829. var _this = _super.call(this, name, scene) || this;
  87830. /**
  87831. * Main color of the grid (e.g. between lines)
  87832. */
  87833. _this.mainColor = BABYLON.Color3.Black();
  87834. /**
  87835. * Color of the grid lines.
  87836. */
  87837. _this.lineColor = BABYLON.Color3.Teal();
  87838. /**
  87839. * The scale of the grid compared to unit.
  87840. */
  87841. _this.gridRatio = 1.0;
  87842. /**
  87843. * Allows setting an offset for the grid lines.
  87844. */
  87845. _this.gridOffset = BABYLON.Vector3.Zero();
  87846. /**
  87847. * The frequency of thicker lines.
  87848. */
  87849. _this.majorUnitFrequency = 10;
  87850. /**
  87851. * The visibility of minor units in the grid.
  87852. */
  87853. _this.minorUnitVisibility = 0.33;
  87854. /**
  87855. * The grid opacity outside of the lines.
  87856. */
  87857. _this.opacity = 1.0;
  87858. /**
  87859. * Determine RBG output is premultiplied by alpha value.
  87860. */
  87861. _this.preMultiplyAlpha = false;
  87862. _this._gridControl = new BABYLON.Vector4(_this.gridRatio, _this.majorUnitFrequency, _this.minorUnitVisibility, _this.opacity);
  87863. return _this;
  87864. }
  87865. /**
  87866. * Returns wehter or not the grid requires alpha blending.
  87867. */
  87868. GridMaterial.prototype.needAlphaBlending = function () {
  87869. return this.opacity < 1.0;
  87870. };
  87871. GridMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  87872. return this.needAlphaBlending();
  87873. };
  87874. GridMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  87875. if (this.isFrozen) {
  87876. if (this._wasPreviouslyReady && subMesh.effect) {
  87877. return true;
  87878. }
  87879. }
  87880. if (!subMesh._materialDefines) {
  87881. subMesh._materialDefines = new GridMaterialDefines();
  87882. }
  87883. var defines = subMesh._materialDefines;
  87884. var scene = this.getScene();
  87885. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  87886. if (this._renderId === scene.getRenderId()) {
  87887. return true;
  87888. }
  87889. }
  87890. if (defines.TRANSPARENT !== (this.opacity < 1.0)) {
  87891. defines.TRANSPARENT = !defines.TRANSPARENT;
  87892. defines.markAsUnprocessed();
  87893. }
  87894. if (defines.PREMULTIPLYALPHA != this.preMultiplyAlpha) {
  87895. defines.PREMULTIPLYALPHA = !defines.PREMULTIPLYALPHA;
  87896. defines.markAsUnprocessed();
  87897. }
  87898. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, false, this.fogEnabled, false, defines);
  87899. // Get correct effect
  87900. if (defines.isDirty) {
  87901. defines.markAsProcessed();
  87902. scene.resetCachedMaterial();
  87903. // Attributes
  87904. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  87905. // Defines
  87906. var join = defines.toString();
  87907. subMesh.setEffect(scene.getEngine().createEffect("grid", attribs, ["projection", "worldView", "mainColor", "lineColor", "gridControl", "gridOffset", "vFogInfos", "vFogColor", "world", "view"], [], join, undefined, this.onCompiled, this.onError), defines);
  87908. }
  87909. if (!subMesh.effect || !subMesh.effect.isReady()) {
  87910. return false;
  87911. }
  87912. this._renderId = scene.getRenderId();
  87913. this._wasPreviouslyReady = true;
  87914. return true;
  87915. };
  87916. GridMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  87917. var scene = this.getScene();
  87918. var defines = subMesh._materialDefines;
  87919. if (!defines) {
  87920. return;
  87921. }
  87922. var effect = subMesh.effect;
  87923. if (!effect) {
  87924. return;
  87925. }
  87926. this._activeEffect = effect;
  87927. // Matrices
  87928. this.bindOnlyWorldMatrix(world);
  87929. this._activeEffect.setMatrix("worldView", world.multiply(scene.getViewMatrix()));
  87930. this._activeEffect.setMatrix("view", scene.getViewMatrix());
  87931. this._activeEffect.setMatrix("projection", scene.getProjectionMatrix());
  87932. // Uniforms
  87933. if (this._mustRebind(scene, effect)) {
  87934. this._activeEffect.setColor3("mainColor", this.mainColor);
  87935. this._activeEffect.setColor3("lineColor", this.lineColor);
  87936. this._activeEffect.setVector3("gridOffset", this.gridOffset);
  87937. this._gridControl.x = this.gridRatio;
  87938. this._gridControl.y = Math.round(this.majorUnitFrequency);
  87939. this._gridControl.z = this.minorUnitVisibility;
  87940. this._gridControl.w = this.opacity;
  87941. this._activeEffect.setVector4("gridControl", this._gridControl);
  87942. }
  87943. // Fog
  87944. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  87945. this._afterBind(mesh, this._activeEffect);
  87946. };
  87947. GridMaterial.prototype.dispose = function (forceDisposeEffect) {
  87948. _super.prototype.dispose.call(this, forceDisposeEffect);
  87949. };
  87950. GridMaterial.prototype.clone = function (name) {
  87951. var _this = this;
  87952. return BABYLON.SerializationHelper.Clone(function () { return new GridMaterial(name, _this.getScene()); }, this);
  87953. };
  87954. GridMaterial.prototype.serialize = function () {
  87955. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  87956. serializationObject.customType = "BABYLON.GridMaterial";
  87957. return serializationObject;
  87958. };
  87959. GridMaterial.prototype.getClassName = function () {
  87960. return "GridMaterial";
  87961. };
  87962. GridMaterial.Parse = function (source, scene, rootUrl) {
  87963. return BABYLON.SerializationHelper.Parse(function () { return new GridMaterial(source.name, scene); }, source, scene, rootUrl);
  87964. };
  87965. __decorate([
  87966. BABYLON.serializeAsColor3()
  87967. ], GridMaterial.prototype, "mainColor", void 0);
  87968. __decorate([
  87969. BABYLON.serializeAsColor3()
  87970. ], GridMaterial.prototype, "lineColor", void 0);
  87971. __decorate([
  87972. BABYLON.serialize()
  87973. ], GridMaterial.prototype, "gridRatio", void 0);
  87974. __decorate([
  87975. BABYLON.serializeAsColor3()
  87976. ], GridMaterial.prototype, "gridOffset", void 0);
  87977. __decorate([
  87978. BABYLON.serialize()
  87979. ], GridMaterial.prototype, "majorUnitFrequency", void 0);
  87980. __decorate([
  87981. BABYLON.serialize()
  87982. ], GridMaterial.prototype, "minorUnitVisibility", void 0);
  87983. __decorate([
  87984. BABYLON.serialize()
  87985. ], GridMaterial.prototype, "opacity", void 0);
  87986. __decorate([
  87987. BABYLON.serialize()
  87988. ], GridMaterial.prototype, "preMultiplyAlpha", void 0);
  87989. return GridMaterial;
  87990. }(BABYLON.PushMaterial));
  87991. BABYLON.GridMaterial = GridMaterial;
  87992. })(BABYLON || (BABYLON = {}));
  87993. //# sourceMappingURL=babylon.gridmaterial.js.map
  87994. 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}";
  87995. 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}";
  87996. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  87997. var BABYLON;
  87998. (function (BABYLON) {
  87999. var GLTFLoaderCoordinateSystemMode;
  88000. (function (GLTFLoaderCoordinateSystemMode) {
  88001. /**
  88002. * Automatically convert the glTF right-handed data to the appropriate system based on the current coordinate system mode of the scene.
  88003. */
  88004. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["AUTO"] = 0] = "AUTO";
  88005. /**
  88006. * Sets the useRightHandedSystem flag on the scene.
  88007. */
  88008. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["FORCE_RIGHT_HANDED"] = 1] = "FORCE_RIGHT_HANDED";
  88009. })(GLTFLoaderCoordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode || (BABYLON.GLTFLoaderCoordinateSystemMode = {}));
  88010. var GLTFLoaderAnimationStartMode;
  88011. (function (GLTFLoaderAnimationStartMode) {
  88012. /**
  88013. * No animation will start.
  88014. */
  88015. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["NONE"] = 0] = "NONE";
  88016. /**
  88017. * The first animation will start.
  88018. */
  88019. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["FIRST"] = 1] = "FIRST";
  88020. /**
  88021. * All animations will start.
  88022. */
  88023. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["ALL"] = 2] = "ALL";
  88024. })(GLTFLoaderAnimationStartMode = BABYLON.GLTFLoaderAnimationStartMode || (BABYLON.GLTFLoaderAnimationStartMode = {}));
  88025. var GLTFLoaderState;
  88026. (function (GLTFLoaderState) {
  88027. GLTFLoaderState[GLTFLoaderState["Loading"] = 0] = "Loading";
  88028. GLTFLoaderState[GLTFLoaderState["Ready"] = 1] = "Ready";
  88029. GLTFLoaderState[GLTFLoaderState["Complete"] = 2] = "Complete";
  88030. })(GLTFLoaderState = BABYLON.GLTFLoaderState || (BABYLON.GLTFLoaderState = {}));
  88031. var GLTFFileLoader = /** @class */ (function () {
  88032. function GLTFFileLoader() {
  88033. // #region Common options
  88034. /**
  88035. * Raised when the asset has been parsed.
  88036. * The data.json property stores the glTF JSON.
  88037. * The data.bin property stores the BIN chunk from a glTF binary or null if the input is not a glTF binary.
  88038. */
  88039. this.onParsedObservable = new BABYLON.Observable();
  88040. // #endregion
  88041. // #region V2 options
  88042. /**
  88043. * The coordinate system mode (AUTO, FORCE_RIGHT_HANDED).
  88044. */
  88045. this.coordinateSystemMode = GLTFLoaderCoordinateSystemMode.AUTO;
  88046. /**
  88047. * The animation start mode (NONE, FIRST, ALL).
  88048. */
  88049. this.animationStartMode = GLTFLoaderAnimationStartMode.FIRST;
  88050. /**
  88051. * Set to true to compile materials before raising the success callback.
  88052. */
  88053. this.compileMaterials = false;
  88054. /**
  88055. * Set to true to also compile materials with clip planes.
  88056. */
  88057. this.useClipPlane = false;
  88058. /**
  88059. * Set to true to compile shadow generators before raising the success callback.
  88060. */
  88061. this.compileShadowGenerators = false;
  88062. /**
  88063. * Raised when the loader creates a mesh after parsing the glTF properties of the mesh.
  88064. */
  88065. this.onMeshLoadedObservable = new BABYLON.Observable();
  88066. /**
  88067. * Raised when the loader creates a texture after parsing the glTF properties of the texture.
  88068. */
  88069. this.onTextureLoadedObservable = new BABYLON.Observable();
  88070. /**
  88071. * Raised when the loader creates a material after parsing the glTF properties of the material.
  88072. */
  88073. this.onMaterialLoadedObservable = new BABYLON.Observable();
  88074. /**
  88075. * Raised when the asset is completely loaded, immediately before the loader is disposed.
  88076. * For assets with LODs, raised when all of the LODs are complete.
  88077. * For assets without LODs, raised when the model is complete, immediately after onSuccess.
  88078. */
  88079. this.onCompleteObservable = new BABYLON.Observable();
  88080. /**
  88081. * Raised when the loader is disposed.
  88082. */
  88083. this.onDisposeObservable = new BABYLON.Observable();
  88084. /**
  88085. * Raised after a loader extension is created.
  88086. * Set additional options for a loader extension in this event.
  88087. */
  88088. this.onExtensionLoadedObservable = new BABYLON.Observable();
  88089. // #endregion
  88090. this._loader = null;
  88091. this.name = "gltf";
  88092. this.extensions = {
  88093. ".gltf": { isBinary: false },
  88094. ".glb": { isBinary: true }
  88095. };
  88096. }
  88097. Object.defineProperty(GLTFFileLoader.prototype, "onParsed", {
  88098. set: function (callback) {
  88099. if (this._onParsedObserver) {
  88100. this.onParsedObservable.remove(this._onParsedObserver);
  88101. }
  88102. this._onParsedObserver = this.onParsedObservable.add(callback);
  88103. },
  88104. enumerable: true,
  88105. configurable: true
  88106. });
  88107. Object.defineProperty(GLTFFileLoader.prototype, "onMeshLoaded", {
  88108. set: function (callback) {
  88109. if (this._onMeshLoadedObserver) {
  88110. this.onMeshLoadedObservable.remove(this._onMeshLoadedObserver);
  88111. }
  88112. this._onMeshLoadedObserver = this.onMeshLoadedObservable.add(callback);
  88113. },
  88114. enumerable: true,
  88115. configurable: true
  88116. });
  88117. Object.defineProperty(GLTFFileLoader.prototype, "onTextureLoaded", {
  88118. set: function (callback) {
  88119. if (this._onTextureLoadedObserver) {
  88120. this.onTextureLoadedObservable.remove(this._onTextureLoadedObserver);
  88121. }
  88122. this._onTextureLoadedObserver = this.onTextureLoadedObservable.add(callback);
  88123. },
  88124. enumerable: true,
  88125. configurable: true
  88126. });
  88127. Object.defineProperty(GLTFFileLoader.prototype, "onMaterialLoaded", {
  88128. set: function (callback) {
  88129. if (this._onMaterialLoadedObserver) {
  88130. this.onMaterialLoadedObservable.remove(this._onMaterialLoadedObserver);
  88131. }
  88132. this._onMaterialLoadedObserver = this.onMaterialLoadedObservable.add(callback);
  88133. },
  88134. enumerable: true,
  88135. configurable: true
  88136. });
  88137. Object.defineProperty(GLTFFileLoader.prototype, "onComplete", {
  88138. set: function (callback) {
  88139. if (this._onCompleteObserver) {
  88140. this.onCompleteObservable.remove(this._onCompleteObserver);
  88141. }
  88142. this._onCompleteObserver = this.onCompleteObservable.add(callback);
  88143. },
  88144. enumerable: true,
  88145. configurable: true
  88146. });
  88147. Object.defineProperty(GLTFFileLoader.prototype, "onDispose", {
  88148. set: function (callback) {
  88149. if (this._onDisposeObserver) {
  88150. this.onDisposeObservable.remove(this._onDisposeObserver);
  88151. }
  88152. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  88153. },
  88154. enumerable: true,
  88155. configurable: true
  88156. });
  88157. Object.defineProperty(GLTFFileLoader.prototype, "onExtensionLoaded", {
  88158. set: function (callback) {
  88159. if (this._onExtensionLoadedObserver) {
  88160. this.onExtensionLoadedObservable.remove(this._onExtensionLoadedObserver);
  88161. }
  88162. this._onExtensionLoadedObserver = this.onExtensionLoadedObservable.add(callback);
  88163. },
  88164. enumerable: true,
  88165. configurable: true
  88166. });
  88167. Object.defineProperty(GLTFFileLoader.prototype, "loaderState", {
  88168. /**
  88169. * The loader state or null if not active.
  88170. */
  88171. get: function () {
  88172. return this._loader ? this._loader.state : null;
  88173. },
  88174. enumerable: true,
  88175. configurable: true
  88176. });
  88177. /**
  88178. * Disposes the loader, releases resources during load, and cancels any outstanding requests.
  88179. */
  88180. GLTFFileLoader.prototype.dispose = function () {
  88181. if (this._loader) {
  88182. this._loader.dispose();
  88183. this._loader = null;
  88184. }
  88185. this.onMeshLoadedObservable.clear();
  88186. this.onTextureLoadedObservable.clear();
  88187. this.onMaterialLoadedObservable.clear();
  88188. this.onDisposeObservable.notifyObservers(this);
  88189. this.onDisposeObservable.clear();
  88190. };
  88191. GLTFFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  88192. var _this = this;
  88193. return Promise.resolve().then(function () {
  88194. var loaderData = _this._parse(data);
  88195. _this._loader = _this._getLoader(loaderData);
  88196. return _this._loader.importMeshAsync(meshesNames, scene, loaderData, rootUrl, onProgress);
  88197. });
  88198. };
  88199. GLTFFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  88200. var _this = this;
  88201. return Promise.resolve().then(function () {
  88202. var loaderData = _this._parse(data);
  88203. _this._loader = _this._getLoader(loaderData);
  88204. return _this._loader.loadAsync(scene, loaderData, rootUrl, onProgress);
  88205. });
  88206. };
  88207. GLTFFileLoader.prototype.loadAssetContainerAsync = function (scene, data, rootUrl, onProgress) {
  88208. var _this = this;
  88209. return Promise.resolve().then(function () {
  88210. var loaderData = _this._parse(data);
  88211. _this._loader = _this._getLoader(loaderData);
  88212. return _this._loader.importMeshAsync(null, scene, loaderData, rootUrl, onProgress).then(function (result) {
  88213. var container = new BABYLON.AssetContainer(scene);
  88214. Array.prototype.push.apply(container.meshes, result.meshes);
  88215. Array.prototype.push.apply(container.particleSystems, result.particleSystems);
  88216. Array.prototype.push.apply(container.skeletons, result.skeletons);
  88217. container.removeAllFromScene();
  88218. return container;
  88219. });
  88220. });
  88221. };
  88222. GLTFFileLoader.prototype.canDirectLoad = function (data) {
  88223. return ((data.indexOf("scene") !== -1) && (data.indexOf("node") !== -1));
  88224. };
  88225. GLTFFileLoader.prototype.createPlugin = function () {
  88226. return new GLTFFileLoader();
  88227. };
  88228. GLTFFileLoader.prototype._parse = function (data) {
  88229. var parsedData;
  88230. if (data instanceof ArrayBuffer) {
  88231. parsedData = GLTFFileLoader._parseBinary(data);
  88232. }
  88233. else {
  88234. parsedData = {
  88235. json: JSON.parse(data),
  88236. bin: null
  88237. };
  88238. }
  88239. this.onParsedObservable.notifyObservers(parsedData);
  88240. this.onParsedObservable.clear();
  88241. return parsedData;
  88242. };
  88243. GLTFFileLoader.prototype._getLoader = function (loaderData) {
  88244. var _this = this;
  88245. var loaderVersion = { major: 2, minor: 0 };
  88246. var asset = loaderData.json.asset || {};
  88247. var version = GLTFFileLoader._parseVersion(asset.version);
  88248. if (!version) {
  88249. throw new Error("Invalid version: " + asset.version);
  88250. }
  88251. if (asset.minVersion !== undefined) {
  88252. var minVersion = GLTFFileLoader._parseVersion(asset.minVersion);
  88253. if (!minVersion) {
  88254. throw new Error("Invalid minimum version: " + asset.minVersion);
  88255. }
  88256. if (GLTFFileLoader._compareVersion(minVersion, loaderVersion) > 0) {
  88257. throw new Error("Incompatible minimum version: " + asset.minVersion);
  88258. }
  88259. }
  88260. var createLoaders = {
  88261. 1: GLTFFileLoader.CreateGLTFLoaderV1,
  88262. 2: GLTFFileLoader.CreateGLTFLoaderV2
  88263. };
  88264. var createLoader = createLoaders[version.major];
  88265. if (!createLoader) {
  88266. throw new Error("Unsupported version: " + asset.version);
  88267. }
  88268. var loader = createLoader();
  88269. loader.coordinateSystemMode = this.coordinateSystemMode;
  88270. loader.animationStartMode = this.animationStartMode;
  88271. loader.compileMaterials = this.compileMaterials;
  88272. loader.useClipPlane = this.useClipPlane;
  88273. loader.compileShadowGenerators = this.compileShadowGenerators;
  88274. loader.onMeshLoadedObservable.add(function (mesh) { return _this.onMeshLoadedObservable.notifyObservers(mesh); });
  88275. loader.onTextureLoadedObservable.add(function (texture) { return _this.onTextureLoadedObservable.notifyObservers(texture); });
  88276. loader.onMaterialLoadedObservable.add(function (material) { return _this.onMaterialLoadedObservable.notifyObservers(material); });
  88277. loader.onExtensionLoadedObservable.add(function (extension) { return _this.onExtensionLoadedObservable.notifyObservers(extension); });
  88278. loader.onCompleteObservable.add(function () {
  88279. _this.onMeshLoadedObservable.clear();
  88280. _this.onTextureLoadedObservable.clear();
  88281. _this.onMaterialLoadedObservable.clear();
  88282. _this.onCompleteObservable.notifyObservers(_this);
  88283. _this.onCompleteObservable.clear();
  88284. });
  88285. return loader;
  88286. };
  88287. GLTFFileLoader._parseBinary = function (data) {
  88288. var Binary = {
  88289. Magic: 0x46546C67
  88290. };
  88291. var binaryReader = new BinaryReader(data);
  88292. var magic = binaryReader.readUint32();
  88293. if (magic !== Binary.Magic) {
  88294. throw new Error("Unexpected magic: " + magic);
  88295. }
  88296. var version = binaryReader.readUint32();
  88297. switch (version) {
  88298. case 1: return GLTFFileLoader._parseV1(binaryReader);
  88299. case 2: return GLTFFileLoader._parseV2(binaryReader);
  88300. }
  88301. throw new Error("Unsupported version: " + version);
  88302. };
  88303. GLTFFileLoader._parseV1 = function (binaryReader) {
  88304. var ContentFormat = {
  88305. JSON: 0
  88306. };
  88307. var length = binaryReader.readUint32();
  88308. if (length != binaryReader.getLength()) {
  88309. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  88310. }
  88311. var contentLength = binaryReader.readUint32();
  88312. var contentFormat = binaryReader.readUint32();
  88313. var content;
  88314. switch (contentFormat) {
  88315. case ContentFormat.JSON: {
  88316. content = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(contentLength)));
  88317. break;
  88318. }
  88319. default: {
  88320. throw new Error("Unexpected content format: " + contentFormat);
  88321. }
  88322. }
  88323. var bytesRemaining = binaryReader.getLength() - binaryReader.getPosition();
  88324. var body = binaryReader.readUint8Array(bytesRemaining);
  88325. return {
  88326. json: content,
  88327. bin: body
  88328. };
  88329. };
  88330. GLTFFileLoader._parseV2 = function (binaryReader) {
  88331. var ChunkFormat = {
  88332. JSON: 0x4E4F534A,
  88333. BIN: 0x004E4942
  88334. };
  88335. var length = binaryReader.readUint32();
  88336. if (length !== binaryReader.getLength()) {
  88337. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  88338. }
  88339. // JSON chunk
  88340. var chunkLength = binaryReader.readUint32();
  88341. var chunkFormat = binaryReader.readUint32();
  88342. if (chunkFormat !== ChunkFormat.JSON) {
  88343. throw new Error("First chunk format is not JSON");
  88344. }
  88345. var json = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(chunkLength)));
  88346. // Look for BIN chunk
  88347. var bin = null;
  88348. while (binaryReader.getPosition() < binaryReader.getLength()) {
  88349. var chunkLength_1 = binaryReader.readUint32();
  88350. var chunkFormat_1 = binaryReader.readUint32();
  88351. switch (chunkFormat_1) {
  88352. case ChunkFormat.JSON: {
  88353. throw new Error("Unexpected JSON chunk");
  88354. }
  88355. case ChunkFormat.BIN: {
  88356. bin = binaryReader.readUint8Array(chunkLength_1);
  88357. break;
  88358. }
  88359. default: {
  88360. // ignore unrecognized chunkFormat
  88361. binaryReader.skipBytes(chunkLength_1);
  88362. break;
  88363. }
  88364. }
  88365. }
  88366. return {
  88367. json: json,
  88368. bin: bin
  88369. };
  88370. };
  88371. GLTFFileLoader._parseVersion = function (version) {
  88372. if (version === "1.0" || version === "1.0.1") {
  88373. return {
  88374. major: 1,
  88375. minor: 0
  88376. };
  88377. }
  88378. var match = (version + "").match(/^(\d+)\.(\d+)/);
  88379. if (!match) {
  88380. return null;
  88381. }
  88382. return {
  88383. major: parseInt(match[1]),
  88384. minor: parseInt(match[2])
  88385. };
  88386. };
  88387. GLTFFileLoader._compareVersion = function (a, b) {
  88388. if (a.major > b.major)
  88389. return 1;
  88390. if (a.major < b.major)
  88391. return -1;
  88392. if (a.minor > b.minor)
  88393. return 1;
  88394. if (a.minor < b.minor)
  88395. return -1;
  88396. return 0;
  88397. };
  88398. GLTFFileLoader._decodeBufferToText = function (buffer) {
  88399. var result = "";
  88400. var length = buffer.byteLength;
  88401. for (var i = 0; i < length; i++) {
  88402. result += String.fromCharCode(buffer[i]);
  88403. }
  88404. return result;
  88405. };
  88406. // #endregion
  88407. // #region V1 options
  88408. GLTFFileLoader.IncrementalLoading = true;
  88409. GLTFFileLoader.HomogeneousCoordinates = false;
  88410. return GLTFFileLoader;
  88411. }());
  88412. BABYLON.GLTFFileLoader = GLTFFileLoader;
  88413. var BinaryReader = /** @class */ (function () {
  88414. function BinaryReader(arrayBuffer) {
  88415. this._arrayBuffer = arrayBuffer;
  88416. this._dataView = new DataView(arrayBuffer);
  88417. this._byteOffset = 0;
  88418. }
  88419. BinaryReader.prototype.getPosition = function () {
  88420. return this._byteOffset;
  88421. };
  88422. BinaryReader.prototype.getLength = function () {
  88423. return this._arrayBuffer.byteLength;
  88424. };
  88425. BinaryReader.prototype.readUint32 = function () {
  88426. var value = this._dataView.getUint32(this._byteOffset, true);
  88427. this._byteOffset += 4;
  88428. return value;
  88429. };
  88430. BinaryReader.prototype.readUint8Array = function (length) {
  88431. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  88432. this._byteOffset += length;
  88433. return value;
  88434. };
  88435. BinaryReader.prototype.skipBytes = function (length) {
  88436. this._byteOffset += length;
  88437. };
  88438. return BinaryReader;
  88439. }());
  88440. if (BABYLON.SceneLoader) {
  88441. BABYLON.SceneLoader.RegisterPlugin(new GLTFFileLoader());
  88442. }
  88443. })(BABYLON || (BABYLON = {}));
  88444. //# sourceMappingURL=babylon.glTFFileLoader.js.map
  88445. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  88446. var BABYLON;
  88447. (function (BABYLON) {
  88448. var GLTF1;
  88449. (function (GLTF1) {
  88450. /**
  88451. * Enums
  88452. */
  88453. var EComponentType;
  88454. (function (EComponentType) {
  88455. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  88456. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  88457. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  88458. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  88459. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  88460. })(EComponentType = GLTF1.EComponentType || (GLTF1.EComponentType = {}));
  88461. var EShaderType;
  88462. (function (EShaderType) {
  88463. EShaderType[EShaderType["FRAGMENT"] = 35632] = "FRAGMENT";
  88464. EShaderType[EShaderType["VERTEX"] = 35633] = "VERTEX";
  88465. })(EShaderType = GLTF1.EShaderType || (GLTF1.EShaderType = {}));
  88466. var EParameterType;
  88467. (function (EParameterType) {
  88468. EParameterType[EParameterType["BYTE"] = 5120] = "BYTE";
  88469. EParameterType[EParameterType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  88470. EParameterType[EParameterType["SHORT"] = 5122] = "SHORT";
  88471. EParameterType[EParameterType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  88472. EParameterType[EParameterType["INT"] = 5124] = "INT";
  88473. EParameterType[EParameterType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  88474. EParameterType[EParameterType["FLOAT"] = 5126] = "FLOAT";
  88475. EParameterType[EParameterType["FLOAT_VEC2"] = 35664] = "FLOAT_VEC2";
  88476. EParameterType[EParameterType["FLOAT_VEC3"] = 35665] = "FLOAT_VEC3";
  88477. EParameterType[EParameterType["FLOAT_VEC4"] = 35666] = "FLOAT_VEC4";
  88478. EParameterType[EParameterType["INT_VEC2"] = 35667] = "INT_VEC2";
  88479. EParameterType[EParameterType["INT_VEC3"] = 35668] = "INT_VEC3";
  88480. EParameterType[EParameterType["INT_VEC4"] = 35669] = "INT_VEC4";
  88481. EParameterType[EParameterType["BOOL"] = 35670] = "BOOL";
  88482. EParameterType[EParameterType["BOOL_VEC2"] = 35671] = "BOOL_VEC2";
  88483. EParameterType[EParameterType["BOOL_VEC3"] = 35672] = "BOOL_VEC3";
  88484. EParameterType[EParameterType["BOOL_VEC4"] = 35673] = "BOOL_VEC4";
  88485. EParameterType[EParameterType["FLOAT_MAT2"] = 35674] = "FLOAT_MAT2";
  88486. EParameterType[EParameterType["FLOAT_MAT3"] = 35675] = "FLOAT_MAT3";
  88487. EParameterType[EParameterType["FLOAT_MAT4"] = 35676] = "FLOAT_MAT4";
  88488. EParameterType[EParameterType["SAMPLER_2D"] = 35678] = "SAMPLER_2D";
  88489. })(EParameterType = GLTF1.EParameterType || (GLTF1.EParameterType = {}));
  88490. var ETextureWrapMode;
  88491. (function (ETextureWrapMode) {
  88492. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  88493. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  88494. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  88495. })(ETextureWrapMode = GLTF1.ETextureWrapMode || (GLTF1.ETextureWrapMode = {}));
  88496. var ETextureFilterType;
  88497. (function (ETextureFilterType) {
  88498. ETextureFilterType[ETextureFilterType["NEAREST"] = 9728] = "NEAREST";
  88499. ETextureFilterType[ETextureFilterType["LINEAR"] = 9728] = "LINEAR";
  88500. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  88501. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  88502. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  88503. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  88504. })(ETextureFilterType = GLTF1.ETextureFilterType || (GLTF1.ETextureFilterType = {}));
  88505. var ETextureFormat;
  88506. (function (ETextureFormat) {
  88507. ETextureFormat[ETextureFormat["ALPHA"] = 6406] = "ALPHA";
  88508. ETextureFormat[ETextureFormat["RGB"] = 6407] = "RGB";
  88509. ETextureFormat[ETextureFormat["RGBA"] = 6408] = "RGBA";
  88510. ETextureFormat[ETextureFormat["LUMINANCE"] = 6409] = "LUMINANCE";
  88511. ETextureFormat[ETextureFormat["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA";
  88512. })(ETextureFormat = GLTF1.ETextureFormat || (GLTF1.ETextureFormat = {}));
  88513. var ECullingType;
  88514. (function (ECullingType) {
  88515. ECullingType[ECullingType["FRONT"] = 1028] = "FRONT";
  88516. ECullingType[ECullingType["BACK"] = 1029] = "BACK";
  88517. ECullingType[ECullingType["FRONT_AND_BACK"] = 1032] = "FRONT_AND_BACK";
  88518. })(ECullingType = GLTF1.ECullingType || (GLTF1.ECullingType = {}));
  88519. var EBlendingFunction;
  88520. (function (EBlendingFunction) {
  88521. EBlendingFunction[EBlendingFunction["ZERO"] = 0] = "ZERO";
  88522. EBlendingFunction[EBlendingFunction["ONE"] = 1] = "ONE";
  88523. EBlendingFunction[EBlendingFunction["SRC_COLOR"] = 768] = "SRC_COLOR";
  88524. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_COLOR"] = 769] = "ONE_MINUS_SRC_COLOR";
  88525. EBlendingFunction[EBlendingFunction["DST_COLOR"] = 774] = "DST_COLOR";
  88526. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_COLOR"] = 775] = "ONE_MINUS_DST_COLOR";
  88527. EBlendingFunction[EBlendingFunction["SRC_ALPHA"] = 770] = "SRC_ALPHA";
  88528. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_ALPHA"] = 771] = "ONE_MINUS_SRC_ALPHA";
  88529. EBlendingFunction[EBlendingFunction["DST_ALPHA"] = 772] = "DST_ALPHA";
  88530. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_ALPHA"] = 773] = "ONE_MINUS_DST_ALPHA";
  88531. EBlendingFunction[EBlendingFunction["CONSTANT_COLOR"] = 32769] = "CONSTANT_COLOR";
  88532. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_COLOR"] = 32770] = "ONE_MINUS_CONSTANT_COLOR";
  88533. EBlendingFunction[EBlendingFunction["CONSTANT_ALPHA"] = 32771] = "CONSTANT_ALPHA";
  88534. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_ALPHA"] = 32772] = "ONE_MINUS_CONSTANT_ALPHA";
  88535. EBlendingFunction[EBlendingFunction["SRC_ALPHA_SATURATE"] = 776] = "SRC_ALPHA_SATURATE";
  88536. })(EBlendingFunction = GLTF1.EBlendingFunction || (GLTF1.EBlendingFunction = {}));
  88537. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  88538. })(BABYLON || (BABYLON = {}));
  88539. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  88540. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  88541. var BABYLON;
  88542. (function (BABYLON) {
  88543. var GLTF1;
  88544. (function (GLTF1) {
  88545. /**
  88546. * Tokenizer. Used for shaders compatibility
  88547. * Automatically map world, view, projection, worldViewProjection, attributes and so on
  88548. */
  88549. var ETokenType;
  88550. (function (ETokenType) {
  88551. ETokenType[ETokenType["IDENTIFIER"] = 1] = "IDENTIFIER";
  88552. ETokenType[ETokenType["UNKNOWN"] = 2] = "UNKNOWN";
  88553. ETokenType[ETokenType["END_OF_INPUT"] = 3] = "END_OF_INPUT";
  88554. })(ETokenType || (ETokenType = {}));
  88555. var Tokenizer = /** @class */ (function () {
  88556. function Tokenizer(toParse) {
  88557. this._pos = 0;
  88558. this.isLetterOrDigitPattern = /^[a-zA-Z0-9]+$/;
  88559. this._toParse = toParse;
  88560. this._maxPos = toParse.length;
  88561. }
  88562. Tokenizer.prototype.getNextToken = function () {
  88563. if (this.isEnd())
  88564. return ETokenType.END_OF_INPUT;
  88565. this.currentString = this.read();
  88566. this.currentToken = ETokenType.UNKNOWN;
  88567. if (this.currentString === "_" || this.isLetterOrDigitPattern.test(this.currentString)) {
  88568. this.currentToken = ETokenType.IDENTIFIER;
  88569. this.currentIdentifier = this.currentString;
  88570. while (!this.isEnd() && (this.isLetterOrDigitPattern.test(this.currentString = this.peek()) || this.currentString === "_")) {
  88571. this.currentIdentifier += this.currentString;
  88572. this.forward();
  88573. }
  88574. }
  88575. return this.currentToken;
  88576. };
  88577. Tokenizer.prototype.peek = function () {
  88578. return this._toParse[this._pos];
  88579. };
  88580. Tokenizer.prototype.read = function () {
  88581. return this._toParse[this._pos++];
  88582. };
  88583. Tokenizer.prototype.forward = function () {
  88584. this._pos++;
  88585. };
  88586. Tokenizer.prototype.isEnd = function () {
  88587. return this._pos >= this._maxPos;
  88588. };
  88589. return Tokenizer;
  88590. }());
  88591. /**
  88592. * Values
  88593. */
  88594. var glTFTransforms = ["MODEL", "VIEW", "PROJECTION", "MODELVIEW", "MODELVIEWPROJECTION", "JOINTMATRIX"];
  88595. var babylonTransforms = ["world", "view", "projection", "worldView", "worldViewProjection", "mBones"];
  88596. var glTFAnimationPaths = ["translation", "rotation", "scale"];
  88597. var babylonAnimationPaths = ["position", "rotationQuaternion", "scaling"];
  88598. /**
  88599. * Parse
  88600. */
  88601. var parseBuffers = function (parsedBuffers, gltfRuntime) {
  88602. for (var buf in parsedBuffers) {
  88603. var parsedBuffer = parsedBuffers[buf];
  88604. gltfRuntime.buffers[buf] = parsedBuffer;
  88605. gltfRuntime.buffersCount++;
  88606. }
  88607. };
  88608. var parseShaders = function (parsedShaders, gltfRuntime) {
  88609. for (var sha in parsedShaders) {
  88610. var parsedShader = parsedShaders[sha];
  88611. gltfRuntime.shaders[sha] = parsedShader;
  88612. gltfRuntime.shaderscount++;
  88613. }
  88614. };
  88615. var parseObject = function (parsedObjects, runtimeProperty, gltfRuntime) {
  88616. for (var object in parsedObjects) {
  88617. var parsedObject = parsedObjects[object];
  88618. gltfRuntime[runtimeProperty][object] = parsedObject;
  88619. }
  88620. };
  88621. /**
  88622. * Utils
  88623. */
  88624. var normalizeUVs = function (buffer) {
  88625. if (!buffer) {
  88626. return;
  88627. }
  88628. for (var i = 0; i < buffer.length / 2; i++) {
  88629. buffer[i * 2 + 1] = 1.0 - buffer[i * 2 + 1];
  88630. }
  88631. };
  88632. var getAttribute = function (attributeParameter) {
  88633. if (attributeParameter.semantic === "NORMAL") {
  88634. return "normal";
  88635. }
  88636. else if (attributeParameter.semantic === "POSITION") {
  88637. return "position";
  88638. }
  88639. else if (attributeParameter.semantic === "JOINT") {
  88640. return "matricesIndices";
  88641. }
  88642. else if (attributeParameter.semantic === "WEIGHT") {
  88643. return "matricesWeights";
  88644. }
  88645. else if (attributeParameter.semantic === "COLOR") {
  88646. return "color";
  88647. }
  88648. else if (attributeParameter.semantic && attributeParameter.semantic.indexOf("TEXCOORD_") !== -1) {
  88649. var channel = Number(attributeParameter.semantic.split("_")[1]);
  88650. return "uv" + (channel === 0 ? "" : channel + 1);
  88651. }
  88652. return null;
  88653. };
  88654. /**
  88655. * Loads and creates animations
  88656. */
  88657. var loadAnimations = function (gltfRuntime) {
  88658. for (var anim in gltfRuntime.animations) {
  88659. var animation = gltfRuntime.animations[anim];
  88660. if (!animation.channels || !animation.samplers) {
  88661. continue;
  88662. }
  88663. var lastAnimation = null;
  88664. for (var i = 0; i < animation.channels.length; i++) {
  88665. // Get parameters and load buffers
  88666. var channel = animation.channels[i];
  88667. var sampler = animation.samplers[channel.sampler];
  88668. if (!sampler) {
  88669. continue;
  88670. }
  88671. var inputData = null;
  88672. var outputData = null;
  88673. if (animation.parameters) {
  88674. inputData = animation.parameters[sampler.input];
  88675. outputData = animation.parameters[sampler.output];
  88676. }
  88677. else {
  88678. inputData = sampler.input;
  88679. outputData = sampler.output;
  88680. }
  88681. var bufferInput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[inputData]);
  88682. var bufferOutput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[outputData]);
  88683. var targetID = channel.target.id;
  88684. var targetNode = gltfRuntime.scene.getNodeByID(targetID);
  88685. if (targetNode === null) {
  88686. targetNode = gltfRuntime.scene.getNodeByName(targetID);
  88687. }
  88688. if (targetNode === null) {
  88689. BABYLON.Tools.Warn("Creating animation named " + anim + ". But cannot find node named " + targetID + " to attach to");
  88690. continue;
  88691. }
  88692. var isBone = targetNode instanceof BABYLON.Bone;
  88693. // Get target path (position, rotation or scaling)
  88694. var targetPath = channel.target.path;
  88695. var targetPathIndex = glTFAnimationPaths.indexOf(targetPath);
  88696. if (targetPathIndex !== -1) {
  88697. targetPath = babylonAnimationPaths[targetPathIndex];
  88698. }
  88699. // Determine animation type
  88700. var animationType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  88701. if (!isBone) {
  88702. if (targetPath === "rotationQuaternion") {
  88703. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  88704. targetNode.rotationQuaternion = new BABYLON.Quaternion();
  88705. }
  88706. else {
  88707. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  88708. }
  88709. }
  88710. // Create animation and key frames
  88711. var babylonAnimation = null;
  88712. var keys = [];
  88713. var arrayOffset = 0;
  88714. var modifyKey = false;
  88715. if (isBone && lastAnimation && lastAnimation.getKeys().length === bufferInput.length) {
  88716. babylonAnimation = lastAnimation;
  88717. modifyKey = true;
  88718. }
  88719. if (!modifyKey) {
  88720. babylonAnimation = new BABYLON.Animation(anim, isBone ? "_matrix" : targetPath, 1, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  88721. }
  88722. // For each frame
  88723. for (var j = 0; j < bufferInput.length; j++) {
  88724. var value = null;
  88725. if (targetPath === "rotationQuaternion") {
  88726. value = BABYLON.Quaternion.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2], bufferOutput[arrayOffset + 3]]);
  88727. arrayOffset += 4;
  88728. }
  88729. else {
  88730. value = BABYLON.Vector3.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2]]);
  88731. arrayOffset += 3;
  88732. }
  88733. if (isBone) {
  88734. var bone = targetNode;
  88735. var translation = BABYLON.Vector3.Zero();
  88736. var rotationQuaternion = new BABYLON.Quaternion();
  88737. var scaling = BABYLON.Vector3.Zero();
  88738. // Warning on decompose
  88739. var mat = bone.getBaseMatrix();
  88740. if (modifyKey && lastAnimation) {
  88741. mat = lastAnimation.getKeys()[j].value;
  88742. }
  88743. mat.decompose(scaling, rotationQuaternion, translation);
  88744. if (targetPath === "position") {
  88745. translation = value;
  88746. }
  88747. else if (targetPath === "rotationQuaternion") {
  88748. rotationQuaternion = value;
  88749. }
  88750. else {
  88751. scaling = value;
  88752. }
  88753. value = BABYLON.Matrix.Compose(scaling, rotationQuaternion, translation);
  88754. }
  88755. if (!modifyKey) {
  88756. keys.push({
  88757. frame: bufferInput[j],
  88758. value: value
  88759. });
  88760. }
  88761. else if (lastAnimation) {
  88762. lastAnimation.getKeys()[j].value = value;
  88763. }
  88764. }
  88765. // Finish
  88766. if (!modifyKey && babylonAnimation) {
  88767. babylonAnimation.setKeys(keys);
  88768. targetNode.animations.push(babylonAnimation);
  88769. }
  88770. lastAnimation = babylonAnimation;
  88771. gltfRuntime.scene.stopAnimation(targetNode);
  88772. gltfRuntime.scene.beginAnimation(targetNode, 0, bufferInput[bufferInput.length - 1], true, 1.0);
  88773. }
  88774. }
  88775. };
  88776. /**
  88777. * Returns the bones transformation matrix
  88778. */
  88779. var configureBoneTransformation = function (node) {
  88780. var mat = null;
  88781. if (node.translation || node.rotation || node.scale) {
  88782. var scale = BABYLON.Vector3.FromArray(node.scale || [1, 1, 1]);
  88783. var rotation = BABYLON.Quaternion.FromArray(node.rotation || [0, 0, 0, 1]);
  88784. var position = BABYLON.Vector3.FromArray(node.translation || [0, 0, 0]);
  88785. mat = BABYLON.Matrix.Compose(scale, rotation, position);
  88786. }
  88787. else {
  88788. mat = BABYLON.Matrix.FromArray(node.matrix);
  88789. }
  88790. return mat;
  88791. };
  88792. /**
  88793. * Returns the parent bone
  88794. */
  88795. var getParentBone = function (gltfRuntime, skins, jointName, newSkeleton) {
  88796. // Try to find
  88797. for (var i = 0; i < newSkeleton.bones.length; i++) {
  88798. if (newSkeleton.bones[i].name === jointName) {
  88799. return newSkeleton.bones[i];
  88800. }
  88801. }
  88802. // Not found, search in gltf nodes
  88803. var nodes = gltfRuntime.nodes;
  88804. for (var nde in nodes) {
  88805. var node = nodes[nde];
  88806. if (!node.jointName) {
  88807. continue;
  88808. }
  88809. var children = node.children;
  88810. for (var i = 0; i < children.length; i++) {
  88811. var child = gltfRuntime.nodes[children[i]];
  88812. if (!child.jointName) {
  88813. continue;
  88814. }
  88815. if (child.jointName === jointName) {
  88816. var mat = configureBoneTransformation(node);
  88817. var bone = new BABYLON.Bone(node.name || "", newSkeleton, getParentBone(gltfRuntime, skins, node.jointName, newSkeleton), mat);
  88818. bone.id = nde;
  88819. return bone;
  88820. }
  88821. }
  88822. }
  88823. return null;
  88824. };
  88825. /**
  88826. * Returns the appropriate root node
  88827. */
  88828. var getNodeToRoot = function (nodesToRoot, id) {
  88829. for (var i = 0; i < nodesToRoot.length; i++) {
  88830. var nodeToRoot = nodesToRoot[i];
  88831. for (var j = 0; j < nodeToRoot.node.children.length; j++) {
  88832. var child = nodeToRoot.node.children[j];
  88833. if (child === id) {
  88834. return nodeToRoot.bone;
  88835. }
  88836. }
  88837. }
  88838. return null;
  88839. };
  88840. /**
  88841. * Returns the node with the joint name
  88842. */
  88843. var getJointNode = function (gltfRuntime, jointName) {
  88844. var nodes = gltfRuntime.nodes;
  88845. var node = nodes[jointName];
  88846. if (node) {
  88847. return {
  88848. node: node,
  88849. id: jointName
  88850. };
  88851. }
  88852. for (var nde in nodes) {
  88853. node = nodes[nde];
  88854. if (node.jointName === jointName) {
  88855. return {
  88856. node: node,
  88857. id: nde
  88858. };
  88859. }
  88860. }
  88861. return null;
  88862. };
  88863. /**
  88864. * Checks if a nodes is in joints
  88865. */
  88866. var nodeIsInJoints = function (skins, id) {
  88867. for (var i = 0; i < skins.jointNames.length; i++) {
  88868. if (skins.jointNames[i] === id) {
  88869. return true;
  88870. }
  88871. }
  88872. return false;
  88873. };
  88874. /**
  88875. * Fills the nodes to root for bones and builds hierarchy
  88876. */
  88877. var getNodesToRoot = function (gltfRuntime, newSkeleton, skins, nodesToRoot) {
  88878. // Creates nodes for root
  88879. for (var nde in gltfRuntime.nodes) {
  88880. var node = gltfRuntime.nodes[nde];
  88881. var id = nde;
  88882. if (!node.jointName || nodeIsInJoints(skins, node.jointName)) {
  88883. continue;
  88884. }
  88885. // Create node to root bone
  88886. var mat = configureBoneTransformation(node);
  88887. var bone = new BABYLON.Bone(node.name || "", newSkeleton, null, mat);
  88888. bone.id = id;
  88889. nodesToRoot.push({ bone: bone, node: node, id: id });
  88890. }
  88891. // Parenting
  88892. for (var i = 0; i < nodesToRoot.length; i++) {
  88893. var nodeToRoot = nodesToRoot[i];
  88894. var children = nodeToRoot.node.children;
  88895. for (var j = 0; j < children.length; j++) {
  88896. var child = null;
  88897. for (var k = 0; k < nodesToRoot.length; k++) {
  88898. if (nodesToRoot[k].id === children[j]) {
  88899. child = nodesToRoot[k];
  88900. break;
  88901. }
  88902. }
  88903. if (child) {
  88904. child.bone._parent = nodeToRoot.bone;
  88905. nodeToRoot.bone.children.push(child.bone);
  88906. }
  88907. }
  88908. }
  88909. };
  88910. /**
  88911. * Imports a skeleton
  88912. */
  88913. var importSkeleton = function (gltfRuntime, skins, mesh, newSkeleton, id) {
  88914. if (!newSkeleton) {
  88915. newSkeleton = new BABYLON.Skeleton(skins.name || "", "", gltfRuntime.scene);
  88916. }
  88917. if (!skins.babylonSkeleton) {
  88918. return newSkeleton;
  88919. }
  88920. // Find the root bones
  88921. var nodesToRoot = [];
  88922. var nodesToRootToAdd = [];
  88923. getNodesToRoot(gltfRuntime, newSkeleton, skins, nodesToRoot);
  88924. newSkeleton.bones = [];
  88925. // Joints
  88926. for (var i = 0; i < skins.jointNames.length; i++) {
  88927. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  88928. if (!jointNode) {
  88929. continue;
  88930. }
  88931. var node = jointNode.node;
  88932. if (!node) {
  88933. BABYLON.Tools.Warn("Joint named " + skins.jointNames[i] + " does not exist");
  88934. continue;
  88935. }
  88936. var id = jointNode.id;
  88937. // Optimize, if the bone already exists...
  88938. var existingBone = gltfRuntime.scene.getBoneByID(id);
  88939. if (existingBone) {
  88940. newSkeleton.bones.push(existingBone);
  88941. continue;
  88942. }
  88943. // Search for parent bone
  88944. var foundBone = false;
  88945. var parentBone = null;
  88946. for (var j = 0; j < i; j++) {
  88947. var jointNode_1 = getJointNode(gltfRuntime, skins.jointNames[j]);
  88948. if (!jointNode_1) {
  88949. continue;
  88950. }
  88951. var joint = jointNode_1.node;
  88952. if (!joint) {
  88953. BABYLON.Tools.Warn("Joint named " + skins.jointNames[j] + " does not exist when looking for parent");
  88954. continue;
  88955. }
  88956. var children = joint.children;
  88957. if (!children) {
  88958. continue;
  88959. }
  88960. foundBone = false;
  88961. for (var k = 0; k < children.length; k++) {
  88962. if (children[k] === id) {
  88963. parentBone = getParentBone(gltfRuntime, skins, skins.jointNames[j], newSkeleton);
  88964. foundBone = true;
  88965. break;
  88966. }
  88967. }
  88968. if (foundBone) {
  88969. break;
  88970. }
  88971. }
  88972. // Create bone
  88973. var mat = configureBoneTransformation(node);
  88974. if (!parentBone && nodesToRoot.length > 0) {
  88975. parentBone = getNodeToRoot(nodesToRoot, id);
  88976. if (parentBone) {
  88977. if (nodesToRootToAdd.indexOf(parentBone) === -1) {
  88978. nodesToRootToAdd.push(parentBone);
  88979. }
  88980. }
  88981. }
  88982. var bone = new BABYLON.Bone(node.jointName || "", newSkeleton, parentBone, mat);
  88983. bone.id = id;
  88984. }
  88985. // Polish
  88986. var bones = newSkeleton.bones;
  88987. newSkeleton.bones = [];
  88988. for (var i = 0; i < skins.jointNames.length; i++) {
  88989. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  88990. if (!jointNode) {
  88991. continue;
  88992. }
  88993. for (var j = 0; j < bones.length; j++) {
  88994. if (bones[j].id === jointNode.id) {
  88995. newSkeleton.bones.push(bones[j]);
  88996. break;
  88997. }
  88998. }
  88999. }
  89000. newSkeleton.prepare();
  89001. // Finish
  89002. for (var i = 0; i < nodesToRootToAdd.length; i++) {
  89003. newSkeleton.bones.push(nodesToRootToAdd[i]);
  89004. }
  89005. return newSkeleton;
  89006. };
  89007. /**
  89008. * Imports a mesh and its geometries
  89009. */
  89010. var importMesh = function (gltfRuntime, node, meshes, id, newMesh) {
  89011. if (!newMesh) {
  89012. newMesh = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  89013. newMesh.id = id;
  89014. }
  89015. if (!node.babylonNode) {
  89016. return newMesh;
  89017. }
  89018. var subMaterials = [];
  89019. var vertexData = null;
  89020. var verticesStarts = new Array();
  89021. var verticesCounts = new Array();
  89022. var indexStarts = new Array();
  89023. var indexCounts = new Array();
  89024. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  89025. var meshID = meshes[meshIndex];
  89026. var mesh = gltfRuntime.meshes[meshID];
  89027. if (!mesh) {
  89028. continue;
  89029. }
  89030. // Positions, normals and UVs
  89031. for (var i = 0; i < mesh.primitives.length; i++) {
  89032. // Temporary vertex data
  89033. var tempVertexData = new BABYLON.VertexData();
  89034. var primitive = mesh.primitives[i];
  89035. if (primitive.mode !== 4) {
  89036. // continue;
  89037. }
  89038. var attributes = primitive.attributes;
  89039. var accessor = null;
  89040. var buffer = null;
  89041. // Set positions, normal and uvs
  89042. for (var semantic in attributes) {
  89043. // Link accessor and buffer view
  89044. accessor = gltfRuntime.accessors[attributes[semantic]];
  89045. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  89046. if (semantic === "NORMAL") {
  89047. tempVertexData.normals = new Float32Array(buffer.length);
  89048. tempVertexData.normals.set(buffer);
  89049. }
  89050. else if (semantic === "POSITION") {
  89051. if (BABYLON.GLTFFileLoader.HomogeneousCoordinates) {
  89052. tempVertexData.positions = new Float32Array(buffer.length - buffer.length / 4);
  89053. for (var j = 0; j < buffer.length; j += 4) {
  89054. tempVertexData.positions[j] = buffer[j];
  89055. tempVertexData.positions[j + 1] = buffer[j + 1];
  89056. tempVertexData.positions[j + 2] = buffer[j + 2];
  89057. }
  89058. }
  89059. else {
  89060. tempVertexData.positions = new Float32Array(buffer.length);
  89061. tempVertexData.positions.set(buffer);
  89062. }
  89063. verticesCounts.push(tempVertexData.positions.length);
  89064. }
  89065. else if (semantic.indexOf("TEXCOORD_") !== -1) {
  89066. var channel = Number(semantic.split("_")[1]);
  89067. var uvKind = BABYLON.VertexBuffer.UVKind + (channel === 0 ? "" : (channel + 1));
  89068. var uvs = new Float32Array(buffer.length);
  89069. uvs.set(buffer);
  89070. normalizeUVs(uvs);
  89071. tempVertexData.set(uvs, uvKind);
  89072. }
  89073. else if (semantic === "JOINT") {
  89074. tempVertexData.matricesIndices = new Float32Array(buffer.length);
  89075. tempVertexData.matricesIndices.set(buffer);
  89076. }
  89077. else if (semantic === "WEIGHT") {
  89078. tempVertexData.matricesWeights = new Float32Array(buffer.length);
  89079. tempVertexData.matricesWeights.set(buffer);
  89080. }
  89081. else if (semantic === "COLOR") {
  89082. tempVertexData.colors = new Float32Array(buffer.length);
  89083. tempVertexData.colors.set(buffer);
  89084. }
  89085. }
  89086. // Indices
  89087. accessor = gltfRuntime.accessors[primitive.indices];
  89088. if (accessor) {
  89089. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  89090. tempVertexData.indices = new Int32Array(buffer.length);
  89091. tempVertexData.indices.set(buffer);
  89092. indexCounts.push(tempVertexData.indices.length);
  89093. }
  89094. else {
  89095. // Set indices on the fly
  89096. var indices = [];
  89097. for (var j = 0; j < tempVertexData.positions.length / 3; j++) {
  89098. indices.push(j);
  89099. }
  89100. tempVertexData.indices = new Int32Array(indices);
  89101. indexCounts.push(tempVertexData.indices.length);
  89102. }
  89103. if (!vertexData) {
  89104. vertexData = tempVertexData;
  89105. }
  89106. else {
  89107. vertexData.merge(tempVertexData);
  89108. }
  89109. // Sub material
  89110. var material_1 = gltfRuntime.scene.getMaterialByID(primitive.material);
  89111. subMaterials.push(material_1 === null ? GLTF1.GLTFUtils.GetDefaultMaterial(gltfRuntime.scene) : material_1);
  89112. // Update vertices start and index start
  89113. verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]);
  89114. indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]);
  89115. }
  89116. }
  89117. var material;
  89118. if (subMaterials.length > 1) {
  89119. material = new BABYLON.MultiMaterial("multimat" + id, gltfRuntime.scene);
  89120. material.subMaterials = subMaterials;
  89121. }
  89122. else {
  89123. material = new BABYLON.StandardMaterial("multimat" + id, gltfRuntime.scene);
  89124. }
  89125. if (subMaterials.length === 1) {
  89126. material = subMaterials[0];
  89127. }
  89128. if (!newMesh.material) {
  89129. newMesh.material = material;
  89130. }
  89131. // Apply geometry
  89132. new BABYLON.Geometry(id, gltfRuntime.scene, vertexData, false, newMesh);
  89133. newMesh.computeWorldMatrix(true);
  89134. // Apply submeshes
  89135. newMesh.subMeshes = [];
  89136. var index = 0;
  89137. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  89138. var meshID = meshes[meshIndex];
  89139. var mesh = gltfRuntime.meshes[meshID];
  89140. if (!mesh) {
  89141. continue;
  89142. }
  89143. for (var i = 0; i < mesh.primitives.length; i++) {
  89144. if (mesh.primitives[i].mode !== 4) {
  89145. //continue;
  89146. }
  89147. BABYLON.SubMesh.AddToMesh(index, verticesStarts[index], verticesCounts[index], indexStarts[index], indexCounts[index], newMesh, newMesh, true);
  89148. index++;
  89149. }
  89150. }
  89151. // Finish
  89152. return newMesh;
  89153. };
  89154. /**
  89155. * Configure node transformation from position, rotation and scaling
  89156. */
  89157. var configureNode = function (newNode, position, rotation, scaling) {
  89158. if (newNode.position) {
  89159. newNode.position = position;
  89160. }
  89161. if (newNode.rotationQuaternion || newNode.rotation) {
  89162. newNode.rotationQuaternion = rotation;
  89163. }
  89164. if (newNode.scaling) {
  89165. newNode.scaling = scaling;
  89166. }
  89167. };
  89168. /**
  89169. * Configures node from transformation matrix
  89170. */
  89171. var configureNodeFromMatrix = function (newNode, node, parent) {
  89172. if (node.matrix) {
  89173. var position = new BABYLON.Vector3(0, 0, 0);
  89174. var rotation = new BABYLON.Quaternion();
  89175. var scaling = new BABYLON.Vector3(0, 0, 0);
  89176. var mat = BABYLON.Matrix.FromArray(node.matrix);
  89177. mat.decompose(scaling, rotation, position);
  89178. configureNode(newNode, position, rotation, scaling);
  89179. }
  89180. else if (node.translation && node.rotation && node.scale) {
  89181. configureNode(newNode, BABYLON.Vector3.FromArray(node.translation), BABYLON.Quaternion.FromArray(node.rotation), BABYLON.Vector3.FromArray(node.scale));
  89182. }
  89183. newNode.computeWorldMatrix(true);
  89184. };
  89185. /**
  89186. * Imports a node
  89187. */
  89188. var importNode = function (gltfRuntime, node, id, parent) {
  89189. var lastNode = null;
  89190. if (gltfRuntime.importOnlyMeshes && (node.skin || node.meshes)) {
  89191. if (gltfRuntime.importMeshesNames && gltfRuntime.importMeshesNames.length > 0 && gltfRuntime.importMeshesNames.indexOf(node.name || "") === -1) {
  89192. return null;
  89193. }
  89194. }
  89195. // Meshes
  89196. if (node.skin) {
  89197. if (node.meshes) {
  89198. var skin = gltfRuntime.skins[node.skin];
  89199. var newMesh = importMesh(gltfRuntime, node, node.meshes, id, node.babylonNode);
  89200. newMesh.skeleton = gltfRuntime.scene.getLastSkeletonByID(node.skin);
  89201. if (newMesh.skeleton === null) {
  89202. newMesh.skeleton = importSkeleton(gltfRuntime, skin, newMesh, skin.babylonSkeleton, node.skin);
  89203. if (!skin.babylonSkeleton) {
  89204. skin.babylonSkeleton = newMesh.skeleton;
  89205. }
  89206. }
  89207. lastNode = newMesh;
  89208. }
  89209. }
  89210. else if (node.meshes) {
  89211. /**
  89212. * Improve meshes property
  89213. */
  89214. var newMesh = importMesh(gltfRuntime, node, node.mesh ? [node.mesh] : node.meshes, id, node.babylonNode);
  89215. lastNode = newMesh;
  89216. }
  89217. else if (node.light && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  89218. var light = gltfRuntime.lights[node.light];
  89219. if (light) {
  89220. if (light.type === "ambient") {
  89221. var ambienLight = light[light.type];
  89222. var hemiLight = new BABYLON.HemisphericLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  89223. hemiLight.name = node.name || "";
  89224. if (ambienLight.color) {
  89225. hemiLight.diffuse = BABYLON.Color3.FromArray(ambienLight.color);
  89226. }
  89227. lastNode = hemiLight;
  89228. }
  89229. else if (light.type === "directional") {
  89230. var directionalLight = light[light.type];
  89231. var dirLight = new BABYLON.DirectionalLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  89232. dirLight.name = node.name || "";
  89233. if (directionalLight.color) {
  89234. dirLight.diffuse = BABYLON.Color3.FromArray(directionalLight.color);
  89235. }
  89236. lastNode = dirLight;
  89237. }
  89238. else if (light.type === "point") {
  89239. var pointLight = light[light.type];
  89240. var ptLight = new BABYLON.PointLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  89241. ptLight.name = node.name || "";
  89242. if (pointLight.color) {
  89243. ptLight.diffuse = BABYLON.Color3.FromArray(pointLight.color);
  89244. }
  89245. lastNode = ptLight;
  89246. }
  89247. else if (light.type === "spot") {
  89248. var spotLight = light[light.type];
  89249. var spLight = new BABYLON.SpotLight(node.light, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, gltfRuntime.scene);
  89250. spLight.name = node.name || "";
  89251. if (spotLight.color) {
  89252. spLight.diffuse = BABYLON.Color3.FromArray(spotLight.color);
  89253. }
  89254. if (spotLight.fallOfAngle) {
  89255. spLight.angle = spotLight.fallOfAngle;
  89256. }
  89257. if (spotLight.fallOffExponent) {
  89258. spLight.exponent = spotLight.fallOffExponent;
  89259. }
  89260. lastNode = spLight;
  89261. }
  89262. }
  89263. }
  89264. else if (node.camera && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  89265. var camera = gltfRuntime.cameras[node.camera];
  89266. if (camera) {
  89267. if (camera.type === "orthographic") {
  89268. var orthoCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  89269. orthoCamera.name = node.name || "";
  89270. orthoCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  89271. orthoCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  89272. lastNode = orthoCamera;
  89273. }
  89274. else if (camera.type === "perspective") {
  89275. var perspectiveCamera = camera[camera.type];
  89276. var persCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  89277. persCamera.name = node.name || "";
  89278. persCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  89279. if (!perspectiveCamera.aspectRatio) {
  89280. perspectiveCamera.aspectRatio = gltfRuntime.scene.getEngine().getRenderWidth() / gltfRuntime.scene.getEngine().getRenderHeight();
  89281. }
  89282. if (perspectiveCamera.znear && perspectiveCamera.zfar) {
  89283. persCamera.maxZ = perspectiveCamera.zfar;
  89284. persCamera.minZ = perspectiveCamera.znear;
  89285. }
  89286. lastNode = persCamera;
  89287. }
  89288. }
  89289. }
  89290. // Empty node
  89291. if (!node.jointName) {
  89292. if (node.babylonNode) {
  89293. return node.babylonNode;
  89294. }
  89295. else if (lastNode === null) {
  89296. var dummy = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  89297. node.babylonNode = dummy;
  89298. lastNode = dummy;
  89299. }
  89300. }
  89301. if (lastNode !== null) {
  89302. if (node.matrix && lastNode instanceof BABYLON.Mesh) {
  89303. configureNodeFromMatrix(lastNode, node, parent);
  89304. }
  89305. else {
  89306. var translation = node.translation || [0, 0, 0];
  89307. var rotation = node.rotation || [0, 0, 0, 1];
  89308. var scale = node.scale || [1, 1, 1];
  89309. configureNode(lastNode, BABYLON.Vector3.FromArray(translation), BABYLON.Quaternion.FromArray(rotation), BABYLON.Vector3.FromArray(scale));
  89310. }
  89311. lastNode.updateCache(true);
  89312. node.babylonNode = lastNode;
  89313. }
  89314. return lastNode;
  89315. };
  89316. /**
  89317. * Traverses nodes and creates them
  89318. */
  89319. var traverseNodes = function (gltfRuntime, id, parent, meshIncluded) {
  89320. if (meshIncluded === void 0) { meshIncluded = false; }
  89321. var node = gltfRuntime.nodes[id];
  89322. var newNode = null;
  89323. if (gltfRuntime.importOnlyMeshes && !meshIncluded && gltfRuntime.importMeshesNames) {
  89324. if (gltfRuntime.importMeshesNames.indexOf(node.name || "") !== -1 || gltfRuntime.importMeshesNames.length === 0) {
  89325. meshIncluded = true;
  89326. }
  89327. else {
  89328. meshIncluded = false;
  89329. }
  89330. }
  89331. else {
  89332. meshIncluded = true;
  89333. }
  89334. if (!node.jointName && meshIncluded) {
  89335. newNode = importNode(gltfRuntime, node, id, parent);
  89336. if (newNode !== null) {
  89337. newNode.id = id;
  89338. newNode.parent = parent;
  89339. }
  89340. }
  89341. if (node.children) {
  89342. for (var i = 0; i < node.children.length; i++) {
  89343. traverseNodes(gltfRuntime, node.children[i], newNode, meshIncluded);
  89344. }
  89345. }
  89346. };
  89347. /**
  89348. * do stuff after buffers, shaders are loaded (e.g. hook up materials, load animations, etc.)
  89349. */
  89350. var postLoad = function (gltfRuntime) {
  89351. // Nodes
  89352. var currentScene = gltfRuntime.currentScene;
  89353. if (currentScene) {
  89354. for (var i = 0; i < currentScene.nodes.length; i++) {
  89355. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  89356. }
  89357. }
  89358. else {
  89359. for (var thing in gltfRuntime.scenes) {
  89360. currentScene = gltfRuntime.scenes[thing];
  89361. for (var i = 0; i < currentScene.nodes.length; i++) {
  89362. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  89363. }
  89364. }
  89365. }
  89366. // Set animations
  89367. loadAnimations(gltfRuntime);
  89368. for (var i = 0; i < gltfRuntime.scene.skeletons.length; i++) {
  89369. var skeleton = gltfRuntime.scene.skeletons[i];
  89370. gltfRuntime.scene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0);
  89371. }
  89372. };
  89373. /**
  89374. * onBind shaderrs callback to set uniforms and matrices
  89375. */
  89376. var onBindShaderMaterial = function (mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess) {
  89377. var materialValues = material.values || technique.parameters;
  89378. for (var unif in unTreatedUniforms) {
  89379. var uniform = unTreatedUniforms[unif];
  89380. var type = uniform.type;
  89381. if (type === GLTF1.EParameterType.FLOAT_MAT2 || type === GLTF1.EParameterType.FLOAT_MAT3 || type === GLTF1.EParameterType.FLOAT_MAT4) {
  89382. if (uniform.semantic && !uniform.source && !uniform.node) {
  89383. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, mesh, uniform, unif, shaderMaterial.getEffect());
  89384. }
  89385. else if (uniform.semantic && (uniform.source || uniform.node)) {
  89386. var source = gltfRuntime.scene.getNodeByName(uniform.source || uniform.node || "");
  89387. if (source === null) {
  89388. source = gltfRuntime.scene.getNodeByID(uniform.source || uniform.node || "");
  89389. }
  89390. if (source === null) {
  89391. continue;
  89392. }
  89393. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, source, uniform, unif, shaderMaterial.getEffect());
  89394. }
  89395. }
  89396. else {
  89397. var value = materialValues[technique.uniforms[unif]];
  89398. if (!value) {
  89399. continue;
  89400. }
  89401. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  89402. var texture = gltfRuntime.textures[material.values ? value : uniform.value].babylonTexture;
  89403. if (texture === null || texture === undefined) {
  89404. continue;
  89405. }
  89406. shaderMaterial.getEffect().setTexture(unif, texture);
  89407. }
  89408. else {
  89409. GLTF1.GLTFUtils.SetUniform((shaderMaterial.getEffect()), unif, value, type);
  89410. }
  89411. }
  89412. }
  89413. onSuccess(shaderMaterial);
  89414. };
  89415. /**
  89416. * Prepare uniforms to send the only one time
  89417. * Loads the appropriate textures
  89418. */
  89419. var prepareShaderMaterialUniforms = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms) {
  89420. var materialValues = material.values || technique.parameters;
  89421. var techniqueUniforms = technique.uniforms;
  89422. /**
  89423. * Prepare values here (not matrices)
  89424. */
  89425. for (var unif in unTreatedUniforms) {
  89426. var uniform = unTreatedUniforms[unif];
  89427. var type = uniform.type;
  89428. var value = materialValues[techniqueUniforms[unif]];
  89429. if (value === undefined) {
  89430. // In case the value is the same for all materials
  89431. value = uniform.value;
  89432. }
  89433. if (!value) {
  89434. continue;
  89435. }
  89436. var onLoadTexture = function (uniformName) {
  89437. return function (texture) {
  89438. if (uniform.value && uniformName) {
  89439. // Static uniform
  89440. shaderMaterial.setTexture(uniformName, texture);
  89441. delete unTreatedUniforms[uniformName];
  89442. }
  89443. };
  89444. };
  89445. // Texture (sampler2D)
  89446. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  89447. GLTF1.GLTFLoaderExtension.LoadTextureAsync(gltfRuntime, material.values ? value : uniform.value, onLoadTexture(unif), function () { return onLoadTexture(null); });
  89448. }
  89449. else {
  89450. if (uniform.value && GLTF1.GLTFUtils.SetUniform(shaderMaterial, unif, material.values ? value : uniform.value, type)) {
  89451. // Static uniform
  89452. delete unTreatedUniforms[unif];
  89453. }
  89454. }
  89455. }
  89456. };
  89457. /**
  89458. * Shader compilation failed
  89459. */
  89460. var onShaderCompileError = function (program, shaderMaterial, onError) {
  89461. return function (effect, error) {
  89462. shaderMaterial.dispose(true);
  89463. onError("Cannot compile program named " + program.name + ". Error: " + error + ". Default material will be applied");
  89464. };
  89465. };
  89466. /**
  89467. * Shader compilation success
  89468. */
  89469. var onShaderCompileSuccess = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess) {
  89470. return function (_) {
  89471. prepareShaderMaterialUniforms(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms);
  89472. shaderMaterial.onBind = function (mesh) {
  89473. onBindShaderMaterial(mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess);
  89474. };
  89475. };
  89476. };
  89477. /**
  89478. * Returns the appropriate uniform if already handled by babylon
  89479. */
  89480. var parseShaderUniforms = function (tokenizer, technique, unTreatedUniforms) {
  89481. for (var unif in technique.uniforms) {
  89482. var uniform = technique.uniforms[unif];
  89483. var uniformParameter = technique.parameters[uniform];
  89484. if (tokenizer.currentIdentifier === unif) {
  89485. if (uniformParameter.semantic && !uniformParameter.source && !uniformParameter.node) {
  89486. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  89487. if (transformIndex !== -1) {
  89488. delete unTreatedUniforms[unif];
  89489. return babylonTransforms[transformIndex];
  89490. }
  89491. }
  89492. }
  89493. }
  89494. return tokenizer.currentIdentifier;
  89495. };
  89496. /**
  89497. * All shaders loaded. Create materials one by one
  89498. */
  89499. var importMaterials = function (gltfRuntime) {
  89500. // Create materials
  89501. for (var mat in gltfRuntime.materials) {
  89502. GLTF1.GLTFLoaderExtension.LoadMaterialAsync(gltfRuntime, mat, function (material) { }, function () { });
  89503. }
  89504. };
  89505. /**
  89506. * Implementation of the base glTF spec
  89507. */
  89508. var GLTFLoaderBase = /** @class */ (function () {
  89509. function GLTFLoaderBase() {
  89510. }
  89511. GLTFLoaderBase.CreateRuntime = function (parsedData, scene, rootUrl) {
  89512. var gltfRuntime = {
  89513. extensions: {},
  89514. accessors: {},
  89515. buffers: {},
  89516. bufferViews: {},
  89517. meshes: {},
  89518. lights: {},
  89519. cameras: {},
  89520. nodes: {},
  89521. images: {},
  89522. textures: {},
  89523. shaders: {},
  89524. programs: {},
  89525. samplers: {},
  89526. techniques: {},
  89527. materials: {},
  89528. animations: {},
  89529. skins: {},
  89530. extensionsUsed: [],
  89531. scenes: {},
  89532. buffersCount: 0,
  89533. shaderscount: 0,
  89534. scene: scene,
  89535. rootUrl: rootUrl,
  89536. loadedBufferCount: 0,
  89537. loadedBufferViews: {},
  89538. loadedShaderCount: 0,
  89539. importOnlyMeshes: false,
  89540. dummyNodes: []
  89541. };
  89542. // Parse
  89543. if (parsedData.extensions) {
  89544. parseObject(parsedData.extensions, "extensions", gltfRuntime);
  89545. }
  89546. if (parsedData.extensionsUsed) {
  89547. parseObject(parsedData.extensionsUsed, "extensionsUsed", gltfRuntime);
  89548. }
  89549. if (parsedData.buffers) {
  89550. parseBuffers(parsedData.buffers, gltfRuntime);
  89551. }
  89552. if (parsedData.bufferViews) {
  89553. parseObject(parsedData.bufferViews, "bufferViews", gltfRuntime);
  89554. }
  89555. if (parsedData.accessors) {
  89556. parseObject(parsedData.accessors, "accessors", gltfRuntime);
  89557. }
  89558. if (parsedData.meshes) {
  89559. parseObject(parsedData.meshes, "meshes", gltfRuntime);
  89560. }
  89561. if (parsedData.lights) {
  89562. parseObject(parsedData.lights, "lights", gltfRuntime);
  89563. }
  89564. if (parsedData.cameras) {
  89565. parseObject(parsedData.cameras, "cameras", gltfRuntime);
  89566. }
  89567. if (parsedData.nodes) {
  89568. parseObject(parsedData.nodes, "nodes", gltfRuntime);
  89569. }
  89570. if (parsedData.images) {
  89571. parseObject(parsedData.images, "images", gltfRuntime);
  89572. }
  89573. if (parsedData.textures) {
  89574. parseObject(parsedData.textures, "textures", gltfRuntime);
  89575. }
  89576. if (parsedData.shaders) {
  89577. parseShaders(parsedData.shaders, gltfRuntime);
  89578. }
  89579. if (parsedData.programs) {
  89580. parseObject(parsedData.programs, "programs", gltfRuntime);
  89581. }
  89582. if (parsedData.samplers) {
  89583. parseObject(parsedData.samplers, "samplers", gltfRuntime);
  89584. }
  89585. if (parsedData.techniques) {
  89586. parseObject(parsedData.techniques, "techniques", gltfRuntime);
  89587. }
  89588. if (parsedData.materials) {
  89589. parseObject(parsedData.materials, "materials", gltfRuntime);
  89590. }
  89591. if (parsedData.animations) {
  89592. parseObject(parsedData.animations, "animations", gltfRuntime);
  89593. }
  89594. if (parsedData.skins) {
  89595. parseObject(parsedData.skins, "skins", gltfRuntime);
  89596. }
  89597. if (parsedData.scenes) {
  89598. gltfRuntime.scenes = parsedData.scenes;
  89599. }
  89600. if (parsedData.scene && parsedData.scenes) {
  89601. gltfRuntime.currentScene = parsedData.scenes[parsedData.scene];
  89602. }
  89603. return gltfRuntime;
  89604. };
  89605. GLTFLoaderBase.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  89606. var buffer = gltfRuntime.buffers[id];
  89607. if (BABYLON.Tools.IsBase64(buffer.uri)) {
  89608. setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.Tools.DecodeBase64(buffer.uri))); });
  89609. }
  89610. else {
  89611. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + buffer.uri, function (data) { return onSuccess(new Uint8Array(data)); }, onProgress, undefined, true, function (request) {
  89612. if (request) {
  89613. onError(request.status + " " + request.statusText);
  89614. }
  89615. });
  89616. }
  89617. };
  89618. GLTFLoaderBase.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  89619. var texture = gltfRuntime.textures[id];
  89620. if (!texture || !texture.source) {
  89621. onError("");
  89622. return;
  89623. }
  89624. if (texture.babylonTexture) {
  89625. onSuccess(null);
  89626. return;
  89627. }
  89628. var source = gltfRuntime.images[texture.source];
  89629. if (BABYLON.Tools.IsBase64(source.uri)) {
  89630. setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.Tools.DecodeBase64(source.uri))); });
  89631. }
  89632. else {
  89633. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + source.uri, function (data) { return onSuccess(new Uint8Array(data)); }, undefined, undefined, true, function (request) {
  89634. if (request) {
  89635. onError(request.status + " " + request.statusText);
  89636. }
  89637. });
  89638. }
  89639. };
  89640. GLTFLoaderBase.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  89641. var texture = gltfRuntime.textures[id];
  89642. if (texture.babylonTexture) {
  89643. onSuccess(texture.babylonTexture);
  89644. return;
  89645. }
  89646. var sampler = gltfRuntime.samplers[texture.sampler];
  89647. var createMipMaps = (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST) ||
  89648. (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_LINEAR) ||
  89649. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST) ||
  89650. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR);
  89651. var samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  89652. var blob = new Blob([buffer]);
  89653. var blobURL = URL.createObjectURL(blob);
  89654. var revokeBlobURL = function () { return URL.revokeObjectURL(blobURL); };
  89655. var newTexture = new BABYLON.Texture(blobURL, gltfRuntime.scene, !createMipMaps, true, samplingMode, revokeBlobURL, revokeBlobURL);
  89656. if (sampler.wrapS !== undefined) {
  89657. newTexture.wrapU = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapS);
  89658. }
  89659. if (sampler.wrapT !== undefined) {
  89660. newTexture.wrapV = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapT);
  89661. }
  89662. newTexture.name = id;
  89663. texture.babylonTexture = newTexture;
  89664. onSuccess(newTexture);
  89665. };
  89666. GLTFLoaderBase.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  89667. var shader = gltfRuntime.shaders[id];
  89668. if (BABYLON.Tools.IsBase64(shader.uri)) {
  89669. var shaderString = atob(shader.uri.split(",")[1]);
  89670. onSuccess(shaderString);
  89671. }
  89672. else {
  89673. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + shader.uri, onSuccess, undefined, undefined, false, function (request) {
  89674. if (request) {
  89675. onError(request.status + " " + request.statusText);
  89676. }
  89677. });
  89678. }
  89679. };
  89680. GLTFLoaderBase.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  89681. var material = gltfRuntime.materials[id];
  89682. if (!material.technique) {
  89683. if (onError) {
  89684. onError("No technique found.");
  89685. }
  89686. return;
  89687. }
  89688. var technique = gltfRuntime.techniques[material.technique];
  89689. if (!technique) {
  89690. var defaultMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  89691. defaultMaterial.diffuseColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  89692. defaultMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  89693. onSuccess(defaultMaterial);
  89694. return;
  89695. }
  89696. var program = gltfRuntime.programs[technique.program];
  89697. var states = technique.states;
  89698. var vertexShader = BABYLON.Effect.ShadersStore[program.vertexShader + "VertexShader"];
  89699. var pixelShader = BABYLON.Effect.ShadersStore[program.fragmentShader + "PixelShader"];
  89700. var newVertexShader = "";
  89701. var newPixelShader = "";
  89702. var vertexTokenizer = new Tokenizer(vertexShader);
  89703. var pixelTokenizer = new Tokenizer(pixelShader);
  89704. var unTreatedUniforms = {};
  89705. var uniforms = [];
  89706. var attributes = [];
  89707. var samplers = [];
  89708. // Fill uniform, sampler2D and attributes
  89709. for (var unif in technique.uniforms) {
  89710. var uniform = technique.uniforms[unif];
  89711. var uniformParameter = technique.parameters[uniform];
  89712. unTreatedUniforms[unif] = uniformParameter;
  89713. if (uniformParameter.semantic && !uniformParameter.node && !uniformParameter.source) {
  89714. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  89715. if (transformIndex !== -1) {
  89716. uniforms.push(babylonTransforms[transformIndex]);
  89717. delete unTreatedUniforms[unif];
  89718. }
  89719. else {
  89720. uniforms.push(unif);
  89721. }
  89722. }
  89723. else if (uniformParameter.type === GLTF1.EParameterType.SAMPLER_2D) {
  89724. samplers.push(unif);
  89725. }
  89726. else {
  89727. uniforms.push(unif);
  89728. }
  89729. }
  89730. for (var attr in technique.attributes) {
  89731. var attribute = technique.attributes[attr];
  89732. var attributeParameter = technique.parameters[attribute];
  89733. if (attributeParameter.semantic) {
  89734. attributes.push(getAttribute(attributeParameter));
  89735. }
  89736. }
  89737. // Configure vertex shader
  89738. while (!vertexTokenizer.isEnd() && vertexTokenizer.getNextToken()) {
  89739. var tokenType = vertexTokenizer.currentToken;
  89740. if (tokenType !== ETokenType.IDENTIFIER) {
  89741. newVertexShader += vertexTokenizer.currentString;
  89742. continue;
  89743. }
  89744. var foundAttribute = false;
  89745. for (var attr in technique.attributes) {
  89746. var attribute = technique.attributes[attr];
  89747. var attributeParameter = technique.parameters[attribute];
  89748. if (vertexTokenizer.currentIdentifier === attr && attributeParameter.semantic) {
  89749. newVertexShader += getAttribute(attributeParameter);
  89750. foundAttribute = true;
  89751. break;
  89752. }
  89753. }
  89754. if (foundAttribute) {
  89755. continue;
  89756. }
  89757. newVertexShader += parseShaderUniforms(vertexTokenizer, technique, unTreatedUniforms);
  89758. }
  89759. // Configure pixel shader
  89760. while (!pixelTokenizer.isEnd() && pixelTokenizer.getNextToken()) {
  89761. var tokenType = pixelTokenizer.currentToken;
  89762. if (tokenType !== ETokenType.IDENTIFIER) {
  89763. newPixelShader += pixelTokenizer.currentString;
  89764. continue;
  89765. }
  89766. newPixelShader += parseShaderUniforms(pixelTokenizer, technique, unTreatedUniforms);
  89767. }
  89768. // Create shader material
  89769. var shaderPath = {
  89770. vertex: program.vertexShader + id,
  89771. fragment: program.fragmentShader + id
  89772. };
  89773. var options = {
  89774. attributes: attributes,
  89775. uniforms: uniforms,
  89776. samplers: samplers,
  89777. needAlphaBlending: states && states.enable && states.enable.indexOf(3042) !== -1
  89778. };
  89779. BABYLON.Effect.ShadersStore[program.vertexShader + id + "VertexShader"] = newVertexShader;
  89780. BABYLON.Effect.ShadersStore[program.fragmentShader + id + "PixelShader"] = newPixelShader;
  89781. var shaderMaterial = new BABYLON.ShaderMaterial(id, gltfRuntime.scene, shaderPath, options);
  89782. shaderMaterial.onError = onShaderCompileError(program, shaderMaterial, onError);
  89783. shaderMaterial.onCompiled = onShaderCompileSuccess(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess);
  89784. shaderMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  89785. if (states && states.functions) {
  89786. var functions = states.functions;
  89787. if (functions.cullFace && functions.cullFace[0] !== GLTF1.ECullingType.BACK) {
  89788. shaderMaterial.backFaceCulling = false;
  89789. }
  89790. var blendFunc = functions.blendFuncSeparate;
  89791. if (blendFunc) {
  89792. 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) {
  89793. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  89794. }
  89795. else if (blendFunc[0] === GLTF1.EBlendingFunction.ONE && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  89796. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  89797. }
  89798. else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  89799. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ADD;
  89800. }
  89801. 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) {
  89802. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_SUBTRACT;
  89803. }
  89804. else if (blendFunc[0] === GLTF1.EBlendingFunction.DST_COLOR && blendFunc[1] === GLTF1.EBlendingFunction.ZERO && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  89805. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MULTIPLY;
  89806. }
  89807. 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) {
  89808. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MAXIMIZED;
  89809. }
  89810. }
  89811. }
  89812. };
  89813. return GLTFLoaderBase;
  89814. }());
  89815. GLTF1.GLTFLoaderBase = GLTFLoaderBase;
  89816. /**
  89817. * glTF V1 Loader
  89818. */
  89819. var GLTFLoader = /** @class */ (function () {
  89820. function GLTFLoader() {
  89821. // #region Stubs for IGLTFLoader interface
  89822. this.coordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode.AUTO;
  89823. this.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.FIRST;
  89824. this.compileMaterials = false;
  89825. this.useClipPlane = false;
  89826. this.compileShadowGenerators = false;
  89827. this.onDisposeObservable = new BABYLON.Observable();
  89828. this.onMeshLoadedObservable = new BABYLON.Observable();
  89829. this.onTextureLoadedObservable = new BABYLON.Observable();
  89830. this.onMaterialLoadedObservable = new BABYLON.Observable();
  89831. this.onCompleteObservable = new BABYLON.Observable();
  89832. this.onExtensionLoadedObservable = new BABYLON.Observable();
  89833. this.state = null;
  89834. }
  89835. GLTFLoader.RegisterExtension = function (extension) {
  89836. if (GLTFLoader.Extensions[extension.name]) {
  89837. BABYLON.Tools.Error("Tool with the same name \"" + extension.name + "\" already exists");
  89838. return;
  89839. }
  89840. GLTFLoader.Extensions[extension.name] = extension;
  89841. };
  89842. GLTFLoader.prototype.dispose = function () { };
  89843. // #endregion
  89844. GLTFLoader.prototype._importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  89845. var _this = this;
  89846. scene.useRightHandedSystem = true;
  89847. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  89848. gltfRuntime.importOnlyMeshes = true;
  89849. if (meshesNames === "") {
  89850. gltfRuntime.importMeshesNames = [];
  89851. }
  89852. else if (typeof meshesNames === "string") {
  89853. gltfRuntime.importMeshesNames = [meshesNames];
  89854. }
  89855. else if (meshesNames && !(meshesNames instanceof Array)) {
  89856. gltfRuntime.importMeshesNames = [meshesNames];
  89857. }
  89858. else {
  89859. gltfRuntime.importMeshesNames = [];
  89860. BABYLON.Tools.Warn("Argument meshesNames must be of type string or string[]");
  89861. }
  89862. // Create nodes
  89863. _this._createNodes(gltfRuntime);
  89864. var meshes = new Array();
  89865. var skeletons = new Array();
  89866. // Fill arrays of meshes and skeletons
  89867. for (var nde in gltfRuntime.nodes) {
  89868. var node = gltfRuntime.nodes[nde];
  89869. if (node.babylonNode instanceof BABYLON.AbstractMesh) {
  89870. meshes.push(node.babylonNode);
  89871. }
  89872. }
  89873. for (var skl in gltfRuntime.skins) {
  89874. var skin = gltfRuntime.skins[skl];
  89875. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  89876. skeletons.push(skin.babylonSkeleton);
  89877. }
  89878. }
  89879. // Load buffers, shaders, materials, etc.
  89880. _this._loadBuffersAsync(gltfRuntime, function () {
  89881. _this._loadShadersAsync(gltfRuntime, function () {
  89882. importMaterials(gltfRuntime);
  89883. postLoad(gltfRuntime);
  89884. if (!BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  89885. onSuccess(meshes, [], skeletons);
  89886. }
  89887. });
  89888. }, onProgress);
  89889. if (BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  89890. onSuccess(meshes, [], skeletons);
  89891. }
  89892. }, onError);
  89893. return true;
  89894. };
  89895. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  89896. var _this = this;
  89897. return new Promise(function (resolve, reject) {
  89898. _this._importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  89899. resolve({
  89900. meshes: meshes,
  89901. particleSystems: particleSystems,
  89902. skeletons: skeletons
  89903. });
  89904. }, onProgress, function (message) {
  89905. reject(new Error(message));
  89906. });
  89907. });
  89908. };
  89909. GLTFLoader.prototype._loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  89910. var _this = this;
  89911. scene.useRightHandedSystem = true;
  89912. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  89913. // Load runtime extensios
  89914. GLTF1.GLTFLoaderExtension.LoadRuntimeExtensionsAsync(gltfRuntime, function () {
  89915. // Create nodes
  89916. _this._createNodes(gltfRuntime);
  89917. // Load buffers, shaders, materials, etc.
  89918. _this._loadBuffersAsync(gltfRuntime, function () {
  89919. _this._loadShadersAsync(gltfRuntime, function () {
  89920. importMaterials(gltfRuntime);
  89921. postLoad(gltfRuntime);
  89922. if (!BABYLON.GLTFFileLoader.IncrementalLoading) {
  89923. onSuccess();
  89924. }
  89925. });
  89926. });
  89927. if (BABYLON.GLTFFileLoader.IncrementalLoading) {
  89928. onSuccess();
  89929. }
  89930. }, onError);
  89931. }, onError);
  89932. };
  89933. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  89934. var _this = this;
  89935. return new Promise(function (resolve, reject) {
  89936. _this._loadAsync(scene, data, rootUrl, function () {
  89937. resolve();
  89938. }, onProgress, function (message) {
  89939. reject(new Error(message));
  89940. });
  89941. });
  89942. };
  89943. GLTFLoader.prototype._loadShadersAsync = function (gltfRuntime, onload) {
  89944. var hasShaders = false;
  89945. var processShader = function (sha, shader) {
  89946. GLTF1.GLTFLoaderExtension.LoadShaderStringAsync(gltfRuntime, sha, function (shaderString) {
  89947. gltfRuntime.loadedShaderCount++;
  89948. if (shaderString) {
  89949. BABYLON.Effect.ShadersStore[sha + (shader.type === GLTF1.EShaderType.VERTEX ? "VertexShader" : "PixelShader")] = shaderString;
  89950. }
  89951. if (gltfRuntime.loadedShaderCount === gltfRuntime.shaderscount) {
  89952. onload();
  89953. }
  89954. }, function () {
  89955. BABYLON.Tools.Error("Error when loading shader program named " + sha + " located at " + shader.uri);
  89956. });
  89957. };
  89958. for (var sha in gltfRuntime.shaders) {
  89959. hasShaders = true;
  89960. var shader = gltfRuntime.shaders[sha];
  89961. if (shader) {
  89962. processShader.bind(this, sha, shader)();
  89963. }
  89964. else {
  89965. BABYLON.Tools.Error("No shader named: " + sha);
  89966. }
  89967. }
  89968. if (!hasShaders) {
  89969. onload();
  89970. }
  89971. };
  89972. ;
  89973. GLTFLoader.prototype._loadBuffersAsync = function (gltfRuntime, onLoad, onProgress) {
  89974. var hasBuffers = false;
  89975. var processBuffer = function (buf, buffer) {
  89976. GLTF1.GLTFLoaderExtension.LoadBufferAsync(gltfRuntime, buf, function (bufferView) {
  89977. gltfRuntime.loadedBufferCount++;
  89978. if (bufferView) {
  89979. if (bufferView.byteLength != gltfRuntime.buffers[buf].byteLength) {
  89980. BABYLON.Tools.Error("Buffer named " + buf + " is length " + bufferView.byteLength + ". Expected: " + buffer.byteLength); // Improve error message
  89981. }
  89982. gltfRuntime.loadedBufferViews[buf] = bufferView;
  89983. }
  89984. if (gltfRuntime.loadedBufferCount === gltfRuntime.buffersCount) {
  89985. onLoad();
  89986. }
  89987. }, function () {
  89988. BABYLON.Tools.Error("Error when loading buffer named " + buf + " located at " + buffer.uri);
  89989. });
  89990. };
  89991. for (var buf in gltfRuntime.buffers) {
  89992. hasBuffers = true;
  89993. var buffer = gltfRuntime.buffers[buf];
  89994. if (buffer) {
  89995. processBuffer.bind(this, buf, buffer)();
  89996. }
  89997. else {
  89998. BABYLON.Tools.Error("No buffer named: " + buf);
  89999. }
  90000. }
  90001. if (!hasBuffers) {
  90002. onLoad();
  90003. }
  90004. };
  90005. GLTFLoader.prototype._createNodes = function (gltfRuntime) {
  90006. var currentScene = gltfRuntime.currentScene;
  90007. if (currentScene) {
  90008. // Only one scene even if multiple scenes are defined
  90009. for (var i = 0; i < currentScene.nodes.length; i++) {
  90010. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  90011. }
  90012. }
  90013. else {
  90014. // Load all scenes
  90015. for (var thing in gltfRuntime.scenes) {
  90016. currentScene = gltfRuntime.scenes[thing];
  90017. for (var i = 0; i < currentScene.nodes.length; i++) {
  90018. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  90019. }
  90020. }
  90021. }
  90022. };
  90023. GLTFLoader.Extensions = {};
  90024. return GLTFLoader;
  90025. }());
  90026. GLTF1.GLTFLoader = GLTFLoader;
  90027. ;
  90028. BABYLON.GLTFFileLoader.CreateGLTFLoaderV1 = function () { return new GLTFLoader(); };
  90029. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  90030. })(BABYLON || (BABYLON = {}));
  90031. //# sourceMappingURL=babylon.glTFLoader.js.map
  90032. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  90033. var BABYLON;
  90034. (function (BABYLON) {
  90035. var GLTF1;
  90036. (function (GLTF1) {
  90037. /**
  90038. * Utils functions for GLTF
  90039. */
  90040. var GLTFUtils = /** @class */ (function () {
  90041. function GLTFUtils() {
  90042. }
  90043. /**
  90044. * Sets the given "parameter" matrix
  90045. * @param scene: the {BABYLON.Scene} object
  90046. * @param source: the source node where to pick the matrix
  90047. * @param parameter: the GLTF technique parameter
  90048. * @param uniformName: the name of the shader's uniform
  90049. * @param shaderMaterial: the shader material
  90050. */
  90051. GLTFUtils.SetMatrix = function (scene, source, parameter, uniformName, shaderMaterial) {
  90052. var mat = null;
  90053. if (parameter.semantic === "MODEL") {
  90054. mat = source.getWorldMatrix();
  90055. }
  90056. else if (parameter.semantic === "PROJECTION") {
  90057. mat = scene.getProjectionMatrix();
  90058. }
  90059. else if (parameter.semantic === "VIEW") {
  90060. mat = scene.getViewMatrix();
  90061. }
  90062. else if (parameter.semantic === "MODELVIEWINVERSETRANSPOSE") {
  90063. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().multiply(scene.getViewMatrix()).invert());
  90064. }
  90065. else if (parameter.semantic === "MODELVIEW") {
  90066. mat = source.getWorldMatrix().multiply(scene.getViewMatrix());
  90067. }
  90068. else if (parameter.semantic === "MODELVIEWPROJECTION") {
  90069. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix());
  90070. }
  90071. else if (parameter.semantic === "MODELINVERSE") {
  90072. mat = source.getWorldMatrix().invert();
  90073. }
  90074. else if (parameter.semantic === "VIEWINVERSE") {
  90075. mat = scene.getViewMatrix().invert();
  90076. }
  90077. else if (parameter.semantic === "PROJECTIONINVERSE") {
  90078. mat = scene.getProjectionMatrix().invert();
  90079. }
  90080. else if (parameter.semantic === "MODELVIEWINVERSE") {
  90081. mat = source.getWorldMatrix().multiply(scene.getViewMatrix()).invert();
  90082. }
  90083. else if (parameter.semantic === "MODELVIEWPROJECTIONINVERSE") {
  90084. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix()).invert();
  90085. }
  90086. else if (parameter.semantic === "MODELINVERSETRANSPOSE") {
  90087. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().invert());
  90088. }
  90089. else {
  90090. debugger;
  90091. }
  90092. if (mat) {
  90093. switch (parameter.type) {
  90094. case GLTF1.EParameterType.FLOAT_MAT2:
  90095. shaderMaterial.setMatrix2x2(uniformName, BABYLON.Matrix.GetAsMatrix2x2(mat));
  90096. break;
  90097. case GLTF1.EParameterType.FLOAT_MAT3:
  90098. shaderMaterial.setMatrix3x3(uniformName, BABYLON.Matrix.GetAsMatrix3x3(mat));
  90099. break;
  90100. case GLTF1.EParameterType.FLOAT_MAT4:
  90101. shaderMaterial.setMatrix(uniformName, mat);
  90102. break;
  90103. default: break;
  90104. }
  90105. }
  90106. };
  90107. /**
  90108. * Sets the given "parameter" matrix
  90109. * @param shaderMaterial: the shader material
  90110. * @param uniform: the name of the shader's uniform
  90111. * @param value: the value of the uniform
  90112. * @param type: the uniform's type (EParameterType FLOAT, VEC2, VEC3 or VEC4)
  90113. */
  90114. GLTFUtils.SetUniform = function (shaderMaterial, uniform, value, type) {
  90115. switch (type) {
  90116. case GLTF1.EParameterType.FLOAT:
  90117. shaderMaterial.setFloat(uniform, value);
  90118. return true;
  90119. case GLTF1.EParameterType.FLOAT_VEC2:
  90120. shaderMaterial.setVector2(uniform, BABYLON.Vector2.FromArray(value));
  90121. return true;
  90122. case GLTF1.EParameterType.FLOAT_VEC3:
  90123. shaderMaterial.setVector3(uniform, BABYLON.Vector3.FromArray(value));
  90124. return true;
  90125. case GLTF1.EParameterType.FLOAT_VEC4:
  90126. shaderMaterial.setVector4(uniform, BABYLON.Vector4.FromArray(value));
  90127. return true;
  90128. default: return false;
  90129. }
  90130. };
  90131. /**
  90132. * Returns the wrap mode of the texture
  90133. * @param mode: the mode value
  90134. */
  90135. GLTFUtils.GetWrapMode = function (mode) {
  90136. switch (mode) {
  90137. case GLTF1.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  90138. case GLTF1.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  90139. case GLTF1.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  90140. default: return BABYLON.Texture.WRAP_ADDRESSMODE;
  90141. }
  90142. };
  90143. /**
  90144. * Returns the byte stride giving an accessor
  90145. * @param accessor: the GLTF accessor objet
  90146. */
  90147. GLTFUtils.GetByteStrideFromType = function (accessor) {
  90148. // Needs this function since "byteStride" isn't requiered in glTF format
  90149. var type = accessor.type;
  90150. switch (type) {
  90151. case "VEC2": return 2;
  90152. case "VEC3": return 3;
  90153. case "VEC4": return 4;
  90154. case "MAT2": return 4;
  90155. case "MAT3": return 9;
  90156. case "MAT4": return 16;
  90157. default: return 1;
  90158. }
  90159. };
  90160. /**
  90161. * Returns the texture filter mode giving a mode value
  90162. * @param mode: the filter mode value
  90163. */
  90164. GLTFUtils.GetTextureFilterMode = function (mode) {
  90165. switch (mode) {
  90166. case GLTF1.ETextureFilterType.LINEAR:
  90167. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST:
  90168. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  90169. case GLTF1.ETextureFilterType.NEAREST:
  90170. case GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_SAMPLINGMODE;
  90171. default: return BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  90172. }
  90173. };
  90174. GLTFUtils.GetBufferFromBufferView = function (gltfRuntime, bufferView, byteOffset, byteLength, componentType) {
  90175. var byteOffset = bufferView.byteOffset + byteOffset;
  90176. var loadedBufferView = gltfRuntime.loadedBufferViews[bufferView.buffer];
  90177. if (byteOffset + byteLength > loadedBufferView.byteLength) {
  90178. throw new Error("Buffer access is out of range");
  90179. }
  90180. var buffer = loadedBufferView.buffer;
  90181. byteOffset += loadedBufferView.byteOffset;
  90182. switch (componentType) {
  90183. case GLTF1.EComponentType.BYTE: return new Int8Array(buffer, byteOffset, byteLength);
  90184. case GLTF1.EComponentType.UNSIGNED_BYTE: return new Uint8Array(buffer, byteOffset, byteLength);
  90185. case GLTF1.EComponentType.SHORT: return new Int16Array(buffer, byteOffset, byteLength);
  90186. case GLTF1.EComponentType.UNSIGNED_SHORT: return new Uint16Array(buffer, byteOffset, byteLength);
  90187. default: return new Float32Array(buffer, byteOffset, byteLength);
  90188. }
  90189. };
  90190. /**
  90191. * Returns a buffer from its accessor
  90192. * @param gltfRuntime: the GLTF runtime
  90193. * @param accessor: the GLTF accessor
  90194. */
  90195. GLTFUtils.GetBufferFromAccessor = function (gltfRuntime, accessor) {
  90196. var bufferView = gltfRuntime.bufferViews[accessor.bufferView];
  90197. var byteLength = accessor.count * GLTFUtils.GetByteStrideFromType(accessor);
  90198. return GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, accessor.byteOffset, byteLength, accessor.componentType);
  90199. };
  90200. /**
  90201. * Decodes a buffer view into a string
  90202. * @param view: the buffer view
  90203. */
  90204. GLTFUtils.DecodeBufferToText = function (view) {
  90205. var result = "";
  90206. var length = view.byteLength;
  90207. for (var i = 0; i < length; ++i) {
  90208. result += String.fromCharCode(view[i]);
  90209. }
  90210. return result;
  90211. };
  90212. /**
  90213. * Returns the default material of gltf. Related to
  90214. * https://github.com/KhronosGroup/glTF/tree/master/specification/1.0#appendix-a-default-material
  90215. * @param scene: the Babylon.js scene
  90216. */
  90217. GLTFUtils.GetDefaultMaterial = function (scene) {
  90218. if (!GLTFUtils._DefaultMaterial) {
  90219. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialVertexShader"] = [
  90220. "precision highp float;",
  90221. "",
  90222. "uniform mat4 worldView;",
  90223. "uniform mat4 projection;",
  90224. "",
  90225. "attribute vec3 position;",
  90226. "",
  90227. "void main(void)",
  90228. "{",
  90229. " gl_Position = projection * worldView * vec4(position, 1.0);",
  90230. "}"
  90231. ].join("\n");
  90232. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialPixelShader"] = [
  90233. "precision highp float;",
  90234. "",
  90235. "uniform vec4 u_emission;",
  90236. "",
  90237. "void main(void)",
  90238. "{",
  90239. " gl_FragColor = u_emission;",
  90240. "}"
  90241. ].join("\n");
  90242. var shaderPath = {
  90243. vertex: "GLTFDefaultMaterial",
  90244. fragment: "GLTFDefaultMaterial"
  90245. };
  90246. var options = {
  90247. attributes: ["position"],
  90248. uniforms: ["worldView", "projection", "u_emission"],
  90249. samplers: new Array(),
  90250. needAlphaBlending: false
  90251. };
  90252. GLTFUtils._DefaultMaterial = new BABYLON.ShaderMaterial("GLTFDefaultMaterial", scene, shaderPath, options);
  90253. GLTFUtils._DefaultMaterial.setColor4("u_emission", new BABYLON.Color4(0.5, 0.5, 0.5, 1.0));
  90254. }
  90255. return GLTFUtils._DefaultMaterial;
  90256. };
  90257. // The GLTF default material
  90258. GLTFUtils._DefaultMaterial = null;
  90259. return GLTFUtils;
  90260. }());
  90261. GLTF1.GLTFUtils = GLTFUtils;
  90262. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  90263. })(BABYLON || (BABYLON = {}));
  90264. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  90265. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  90266. var BABYLON;
  90267. (function (BABYLON) {
  90268. var GLTF1;
  90269. (function (GLTF1) {
  90270. var GLTFLoaderExtension = /** @class */ (function () {
  90271. function GLTFLoaderExtension(name) {
  90272. this._name = name;
  90273. }
  90274. Object.defineProperty(GLTFLoaderExtension.prototype, "name", {
  90275. get: function () {
  90276. return this._name;
  90277. },
  90278. enumerable: true,
  90279. configurable: true
  90280. });
  90281. /**
  90282. * Defines an override for loading the runtime
  90283. * Return true to stop further extensions from loading the runtime
  90284. */
  90285. GLTFLoaderExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  90286. return false;
  90287. };
  90288. /**
  90289. * Defines an onverride for creating gltf runtime
  90290. * Return true to stop further extensions from creating the runtime
  90291. */
  90292. GLTFLoaderExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  90293. return false;
  90294. };
  90295. /**
  90296. * Defines an override for loading buffers
  90297. * Return true to stop further extensions from loading this buffer
  90298. */
  90299. GLTFLoaderExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  90300. return false;
  90301. };
  90302. /**
  90303. * Defines an override for loading texture buffers
  90304. * Return true to stop further extensions from loading this texture data
  90305. */
  90306. GLTFLoaderExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  90307. return false;
  90308. };
  90309. /**
  90310. * Defines an override for creating textures
  90311. * Return true to stop further extensions from loading this texture
  90312. */
  90313. GLTFLoaderExtension.prototype.createTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  90314. return false;
  90315. };
  90316. /**
  90317. * Defines an override for loading shader strings
  90318. * Return true to stop further extensions from loading this shader data
  90319. */
  90320. GLTFLoaderExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  90321. return false;
  90322. };
  90323. /**
  90324. * Defines an override for loading materials
  90325. * Return true to stop further extensions from loading this material
  90326. */
  90327. GLTFLoaderExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  90328. return false;
  90329. };
  90330. // ---------
  90331. // Utilities
  90332. // ---------
  90333. GLTFLoaderExtension.LoadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  90334. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  90335. return loaderExtension.loadRuntimeAsync(scene, data, rootUrl, onSuccess, onError);
  90336. }, function () {
  90337. setTimeout(function () {
  90338. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  90339. });
  90340. });
  90341. };
  90342. GLTFLoaderExtension.LoadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  90343. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  90344. return loaderExtension.loadRuntimeExtensionsAsync(gltfRuntime, onSuccess, onError);
  90345. }, function () {
  90346. setTimeout(function () {
  90347. onSuccess();
  90348. });
  90349. });
  90350. };
  90351. GLTFLoaderExtension.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  90352. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  90353. return loaderExtension.loadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  90354. }, function () {
  90355. GLTF1.GLTFLoaderBase.LoadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  90356. });
  90357. };
  90358. GLTFLoaderExtension.LoadTextureAsync = function (gltfRuntime, id, onSuccess, onError) {
  90359. GLTFLoaderExtension.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) { return GLTFLoaderExtension.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError); }, onError);
  90360. };
  90361. GLTFLoaderExtension.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  90362. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  90363. return loaderExtension.loadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  90364. }, function () {
  90365. GLTF1.GLTFLoaderBase.LoadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  90366. });
  90367. };
  90368. GLTFLoaderExtension.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  90369. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  90370. return loaderExtension.loadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  90371. }, function () {
  90372. GLTF1.GLTFLoaderBase.LoadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  90373. });
  90374. };
  90375. GLTFLoaderExtension.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  90376. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  90377. return loaderExtension.loadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  90378. }, function () {
  90379. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  90380. });
  90381. };
  90382. GLTFLoaderExtension.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  90383. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  90384. return loaderExtension.createTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  90385. }, function () {
  90386. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  90387. });
  90388. };
  90389. GLTFLoaderExtension.ApplyExtensions = function (func, defaultFunc) {
  90390. for (var extensionName in GLTF1.GLTFLoader.Extensions) {
  90391. var loaderExtension = GLTF1.GLTFLoader.Extensions[extensionName];
  90392. if (func(loaderExtension)) {
  90393. return;
  90394. }
  90395. }
  90396. defaultFunc();
  90397. };
  90398. return GLTFLoaderExtension;
  90399. }());
  90400. GLTF1.GLTFLoaderExtension = GLTFLoaderExtension;
  90401. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  90402. })(BABYLON || (BABYLON = {}));
  90403. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  90404. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  90405. var BABYLON;
  90406. (function (BABYLON) {
  90407. var GLTF1;
  90408. (function (GLTF1) {
  90409. var BinaryExtensionBufferName = "binary_glTF";
  90410. ;
  90411. ;
  90412. var GLTFBinaryExtension = /** @class */ (function (_super) {
  90413. __extends(GLTFBinaryExtension, _super);
  90414. function GLTFBinaryExtension() {
  90415. return _super.call(this, "KHR_binary_glTF") || this;
  90416. }
  90417. GLTFBinaryExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  90418. var extensionsUsed = data.json.extensionsUsed;
  90419. if (!extensionsUsed || extensionsUsed.indexOf(this.name) === -1 || !data.bin) {
  90420. return false;
  90421. }
  90422. this._bin = data.bin;
  90423. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  90424. return true;
  90425. };
  90426. GLTFBinaryExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  90427. if (gltfRuntime.extensionsUsed.indexOf(this.name) === -1) {
  90428. return false;
  90429. }
  90430. if (id !== BinaryExtensionBufferName) {
  90431. return false;
  90432. }
  90433. onSuccess(this._bin);
  90434. return true;
  90435. };
  90436. GLTFBinaryExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  90437. var texture = gltfRuntime.textures[id];
  90438. var source = gltfRuntime.images[texture.source];
  90439. if (!source.extensions || !(this.name in source.extensions)) {
  90440. return false;
  90441. }
  90442. var sourceExt = source.extensions[this.name];
  90443. var bufferView = gltfRuntime.bufferViews[sourceExt.bufferView];
  90444. var buffer = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  90445. onSuccess(buffer);
  90446. return true;
  90447. };
  90448. GLTFBinaryExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  90449. var shader = gltfRuntime.shaders[id];
  90450. if (!shader.extensions || !(this.name in shader.extensions)) {
  90451. return false;
  90452. }
  90453. var binaryExtensionShader = shader.extensions[this.name];
  90454. var bufferView = gltfRuntime.bufferViews[binaryExtensionShader.bufferView];
  90455. var shaderBytes = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  90456. setTimeout(function () {
  90457. var shaderString = GLTF1.GLTFUtils.DecodeBufferToText(shaderBytes);
  90458. onSuccess(shaderString);
  90459. });
  90460. return true;
  90461. };
  90462. return GLTFBinaryExtension;
  90463. }(GLTF1.GLTFLoaderExtension));
  90464. GLTF1.GLTFBinaryExtension = GLTFBinaryExtension;
  90465. GLTF1.GLTFLoader.RegisterExtension(new GLTFBinaryExtension());
  90466. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  90467. })(BABYLON || (BABYLON = {}));
  90468. //# sourceMappingURL=babylon.glTFBinaryExtension.js.map
  90469. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  90470. var BABYLON;
  90471. (function (BABYLON) {
  90472. var GLTF1;
  90473. (function (GLTF1) {
  90474. ;
  90475. ;
  90476. ;
  90477. var GLTFMaterialsCommonExtension = /** @class */ (function (_super) {
  90478. __extends(GLTFMaterialsCommonExtension, _super);
  90479. function GLTFMaterialsCommonExtension() {
  90480. return _super.call(this, "KHR_materials_common") || this;
  90481. }
  90482. GLTFMaterialsCommonExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  90483. if (!gltfRuntime.extensions)
  90484. return false;
  90485. var extension = gltfRuntime.extensions[this.name];
  90486. if (!extension)
  90487. return false;
  90488. // Create lights
  90489. var lights = extension.lights;
  90490. if (lights) {
  90491. for (var thing in lights) {
  90492. var light = lights[thing];
  90493. switch (light.type) {
  90494. case "ambient":
  90495. var ambientLight = new BABYLON.HemisphericLight(light.name, new BABYLON.Vector3(0, 1, 0), gltfRuntime.scene);
  90496. var ambient = light.ambient;
  90497. if (ambient) {
  90498. ambientLight.diffuse = BABYLON.Color3.FromArray(ambient.color || [1, 1, 1]);
  90499. }
  90500. break;
  90501. case "point":
  90502. var pointLight = new BABYLON.PointLight(light.name, new BABYLON.Vector3(10, 10, 10), gltfRuntime.scene);
  90503. var point = light.point;
  90504. if (point) {
  90505. pointLight.diffuse = BABYLON.Color3.FromArray(point.color || [1, 1, 1]);
  90506. }
  90507. break;
  90508. case "directional":
  90509. var dirLight = new BABYLON.DirectionalLight(light.name, new BABYLON.Vector3(0, -1, 0), gltfRuntime.scene);
  90510. var directional = light.directional;
  90511. if (directional) {
  90512. dirLight.diffuse = BABYLON.Color3.FromArray(directional.color || [1, 1, 1]);
  90513. }
  90514. break;
  90515. case "spot":
  90516. var spot = light.spot;
  90517. if (spot) {
  90518. 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);
  90519. spotLight.diffuse = BABYLON.Color3.FromArray(spot.color || [1, 1, 1]);
  90520. }
  90521. break;
  90522. default:
  90523. BABYLON.Tools.Warn("GLTF Material Common extension: light type \"" + light.type + "\” not supported");
  90524. break;
  90525. }
  90526. }
  90527. }
  90528. return false;
  90529. };
  90530. GLTFMaterialsCommonExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  90531. var material = gltfRuntime.materials[id];
  90532. if (!material || !material.extensions)
  90533. return false;
  90534. var extension = material.extensions[this.name];
  90535. if (!extension)
  90536. return false;
  90537. var standardMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  90538. standardMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  90539. if (extension.technique === "CONSTANT") {
  90540. standardMaterial.disableLighting = true;
  90541. }
  90542. standardMaterial.backFaceCulling = extension.doubleSided === undefined ? false : !extension.doubleSided;
  90543. standardMaterial.alpha = extension.values.transparency === undefined ? 1.0 : extension.values.transparency;
  90544. standardMaterial.specularPower = extension.values.shininess === undefined ? 0.0 : extension.values.shininess;
  90545. // Ambient
  90546. if (typeof extension.values.ambient === "string") {
  90547. this._loadTexture(gltfRuntime, extension.values.ambient, standardMaterial, "ambientTexture", onError);
  90548. }
  90549. else {
  90550. standardMaterial.ambientColor = BABYLON.Color3.FromArray(extension.values.ambient || [0, 0, 0]);
  90551. }
  90552. // Diffuse
  90553. if (typeof extension.values.diffuse === "string") {
  90554. this._loadTexture(gltfRuntime, extension.values.diffuse, standardMaterial, "diffuseTexture", onError);
  90555. }
  90556. else {
  90557. standardMaterial.diffuseColor = BABYLON.Color3.FromArray(extension.values.diffuse || [0, 0, 0]);
  90558. }
  90559. // Emission
  90560. if (typeof extension.values.emission === "string") {
  90561. this._loadTexture(gltfRuntime, extension.values.emission, standardMaterial, "emissiveTexture", onError);
  90562. }
  90563. else {
  90564. standardMaterial.emissiveColor = BABYLON.Color3.FromArray(extension.values.emission || [0, 0, 0]);
  90565. }
  90566. // Specular
  90567. if (typeof extension.values.specular === "string") {
  90568. this._loadTexture(gltfRuntime, extension.values.specular, standardMaterial, "specularTexture", onError);
  90569. }
  90570. else {
  90571. standardMaterial.specularColor = BABYLON.Color3.FromArray(extension.values.specular || [0, 0, 0]);
  90572. }
  90573. return true;
  90574. };
  90575. GLTFMaterialsCommonExtension.prototype._loadTexture = function (gltfRuntime, id, material, propertyPath, onError) {
  90576. // Create buffer from texture url
  90577. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  90578. // Create texture from buffer
  90579. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, function (texture) { return material[propertyPath] = texture; }, onError);
  90580. }, onError);
  90581. };
  90582. return GLTFMaterialsCommonExtension;
  90583. }(GLTF1.GLTFLoaderExtension));
  90584. GLTF1.GLTFMaterialsCommonExtension = GLTFMaterialsCommonExtension;
  90585. GLTF1.GLTFLoader.RegisterExtension(new GLTFMaterialsCommonExtension());
  90586. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  90587. })(BABYLON || (BABYLON = {}));
  90588. //# sourceMappingURL=babylon.glTFMaterialsCommonExtension.js.map
  90589. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  90590. var BABYLON;
  90591. (function (BABYLON) {
  90592. var GLTF2;
  90593. (function (GLTF2) {
  90594. var ArrayItem = /** @class */ (function () {
  90595. function ArrayItem() {
  90596. }
  90597. ArrayItem.Assign = function (values) {
  90598. if (values) {
  90599. for (var index = 0; index < values.length; index++) {
  90600. values[index]._index = index;
  90601. }
  90602. }
  90603. };
  90604. return ArrayItem;
  90605. }());
  90606. GLTF2.ArrayItem = ArrayItem;
  90607. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  90608. })(BABYLON || (BABYLON = {}));
  90609. //# sourceMappingURL=babylon.glTFLoaderUtilities.js.map
  90610. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  90611. /// <reference path="../../../../dist/babylon.glTF2Interface.d.ts"/>
  90612. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  90613. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  90614. var BABYLON;
  90615. (function (BABYLON) {
  90616. var GLTF2;
  90617. (function (GLTF2) {
  90618. var GLTFLoader = /** @class */ (function () {
  90619. function GLTFLoader() {
  90620. this._completePromises = new Array();
  90621. this._disposed = false;
  90622. this._state = null;
  90623. this._extensions = {};
  90624. this._defaultSampler = {};
  90625. this._requests = new Array();
  90626. this.coordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode.AUTO;
  90627. this.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.FIRST;
  90628. this.compileMaterials = false;
  90629. this.useClipPlane = false;
  90630. this.compileShadowGenerators = false;
  90631. this.onDisposeObservable = new BABYLON.Observable();
  90632. this.onMeshLoadedObservable = new BABYLON.Observable();
  90633. this.onTextureLoadedObservable = new BABYLON.Observable();
  90634. this.onMaterialLoadedObservable = new BABYLON.Observable();
  90635. this.onExtensionLoadedObservable = new BABYLON.Observable();
  90636. this.onCompleteObservable = new BABYLON.Observable();
  90637. }
  90638. GLTFLoader._Register = function (name, factory) {
  90639. if (GLTFLoader._Factories[name]) {
  90640. BABYLON.Tools.Error("Extension with the name '" + name + "' already exists");
  90641. return;
  90642. }
  90643. GLTFLoader._Factories[name] = factory;
  90644. // Keep the order of registration so that extensions registered first are called first.
  90645. GLTFLoader._Names.push(name);
  90646. };
  90647. Object.defineProperty(GLTFLoader.prototype, "state", {
  90648. get: function () {
  90649. return this._state;
  90650. },
  90651. enumerable: true,
  90652. configurable: true
  90653. });
  90654. GLTFLoader.prototype.dispose = function () {
  90655. if (this._disposed) {
  90656. return;
  90657. }
  90658. this._disposed = true;
  90659. this.onDisposeObservable.notifyObservers(this);
  90660. this.onDisposeObservable.clear();
  90661. this._clear();
  90662. };
  90663. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  90664. var _this = this;
  90665. return Promise.resolve().then(function () {
  90666. var nodes = null;
  90667. if (meshesNames) {
  90668. var nodeMap_1 = {};
  90669. if (_this._gltf.nodes) {
  90670. for (var _i = 0, _a = _this._gltf.nodes; _i < _a.length; _i++) {
  90671. var node = _a[_i];
  90672. if (node.name) {
  90673. nodeMap_1[node.name] = node;
  90674. }
  90675. }
  90676. }
  90677. var names = (meshesNames instanceof Array) ? meshesNames : [meshesNames];
  90678. nodes = names.map(function (name) {
  90679. var node = nodeMap_1[name];
  90680. if (!node) {
  90681. throw new Error("Failed to find node " + name);
  90682. }
  90683. return node;
  90684. });
  90685. }
  90686. return _this._loadAsync(nodes, scene, data, rootUrl, onProgress).then(function () {
  90687. return {
  90688. meshes: _this._getMeshes(),
  90689. particleSystems: [],
  90690. skeletons: _this._getSkeletons(),
  90691. };
  90692. });
  90693. });
  90694. };
  90695. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  90696. return this._loadAsync(null, scene, data, rootUrl, onProgress);
  90697. };
  90698. GLTFLoader.prototype._loadAsync = function (nodes, scene, data, rootUrl, onProgress) {
  90699. var _this = this;
  90700. return Promise.resolve().then(function () {
  90701. _this._loadExtensions();
  90702. _this._babylonScene = scene;
  90703. _this._rootUrl = rootUrl;
  90704. _this._progressCallback = onProgress;
  90705. _this._state = BABYLON.GLTFLoaderState.Loading;
  90706. _this._loadData(data);
  90707. var promises = new Array();
  90708. if (nodes) {
  90709. promises.push(_this._loadNodesAsync(nodes));
  90710. }
  90711. else {
  90712. var scene_1 = GLTFLoader._GetProperty("#/scene", _this._gltf.scenes, _this._gltf.scene || 0);
  90713. promises.push(_this._loadSceneAsync("#/scenes/" + scene_1._index, scene_1));
  90714. }
  90715. if (_this.compileMaterials) {
  90716. promises.push(_this._compileMaterialsAsync());
  90717. }
  90718. if (_this.compileShadowGenerators) {
  90719. promises.push(_this._compileShadowGeneratorsAsync());
  90720. }
  90721. return Promise.all(promises).then(function () {
  90722. _this._state = BABYLON.GLTFLoaderState.Ready;
  90723. _this._startAnimations();
  90724. BABYLON.Tools.SetImmediate(function () {
  90725. if (!_this._disposed) {
  90726. Promise.all(_this._completePromises).then(function () {
  90727. _this._state = BABYLON.GLTFLoaderState.Complete;
  90728. _this.onCompleteObservable.notifyObservers(_this);
  90729. _this.onCompleteObservable.clear();
  90730. _this._clear();
  90731. }).catch(function (error) {
  90732. BABYLON.Tools.Error("glTF Loader: " + error.message);
  90733. _this._clear();
  90734. });
  90735. }
  90736. });
  90737. });
  90738. }).catch(function (error) {
  90739. BABYLON.Tools.Error("glTF Loader: " + error.message);
  90740. _this._clear();
  90741. throw error;
  90742. });
  90743. };
  90744. GLTFLoader.prototype._loadExtensions = function () {
  90745. for (var _i = 0, _a = GLTFLoader._Names; _i < _a.length; _i++) {
  90746. var name_1 = _a[_i];
  90747. var extension = GLTFLoader._Factories[name_1](this);
  90748. this._extensions[name_1] = extension;
  90749. this.onExtensionLoadedObservable.notifyObservers(extension);
  90750. }
  90751. this.onExtensionLoadedObservable.clear();
  90752. };
  90753. GLTFLoader.prototype._loadData = function (data) {
  90754. this._gltf = data.json;
  90755. this._setupData();
  90756. if (data.bin) {
  90757. var buffers = this._gltf.buffers;
  90758. if (buffers && buffers[0] && !buffers[0].uri) {
  90759. var binaryBuffer = buffers[0];
  90760. if (binaryBuffer.byteLength < data.bin.byteLength - 3 || binaryBuffer.byteLength > data.bin.byteLength) {
  90761. BABYLON.Tools.Warn("Binary buffer length (" + binaryBuffer.byteLength + ") from JSON does not match chunk length (" + data.bin.byteLength + ")");
  90762. }
  90763. binaryBuffer._data = Promise.resolve(data.bin);
  90764. }
  90765. else {
  90766. BABYLON.Tools.Warn("Unexpected BIN chunk");
  90767. }
  90768. }
  90769. };
  90770. GLTFLoader.prototype._setupData = function () {
  90771. GLTF2.ArrayItem.Assign(this._gltf.accessors);
  90772. GLTF2.ArrayItem.Assign(this._gltf.animations);
  90773. GLTF2.ArrayItem.Assign(this._gltf.buffers);
  90774. GLTF2.ArrayItem.Assign(this._gltf.bufferViews);
  90775. GLTF2.ArrayItem.Assign(this._gltf.cameras);
  90776. GLTF2.ArrayItem.Assign(this._gltf.images);
  90777. GLTF2.ArrayItem.Assign(this._gltf.materials);
  90778. GLTF2.ArrayItem.Assign(this._gltf.meshes);
  90779. GLTF2.ArrayItem.Assign(this._gltf.nodes);
  90780. GLTF2.ArrayItem.Assign(this._gltf.samplers);
  90781. GLTF2.ArrayItem.Assign(this._gltf.scenes);
  90782. GLTF2.ArrayItem.Assign(this._gltf.skins);
  90783. GLTF2.ArrayItem.Assign(this._gltf.textures);
  90784. if (this._gltf.nodes) {
  90785. var nodeParents = {};
  90786. for (var _i = 0, _a = this._gltf.nodes; _i < _a.length; _i++) {
  90787. var node = _a[_i];
  90788. if (node.children) {
  90789. for (var _b = 0, _c = node.children; _b < _c.length; _b++) {
  90790. var index = _c[_b];
  90791. nodeParents[index] = node._index;
  90792. }
  90793. }
  90794. }
  90795. var rootNode = this._createRootNode();
  90796. for (var _d = 0, _e = this._gltf.nodes; _d < _e.length; _d++) {
  90797. var node = _e[_d];
  90798. var parentIndex = nodeParents[node._index];
  90799. node._parent = parentIndex === undefined ? rootNode : this._gltf.nodes[parentIndex];
  90800. }
  90801. }
  90802. };
  90803. GLTFLoader.prototype._createRootNode = function () {
  90804. this._rootBabylonMesh = new BABYLON.Mesh("__root__", this._babylonScene);
  90805. var rootNode = { _babylonMesh: this._rootBabylonMesh };
  90806. switch (this.coordinateSystemMode) {
  90807. case BABYLON.GLTFLoaderCoordinateSystemMode.AUTO: {
  90808. if (!this._babylonScene.useRightHandedSystem) {
  90809. rootNode.rotation = [0, 1, 0, 0];
  90810. rootNode.scale = [1, 1, -1];
  90811. GLTFLoader._LoadTransform(rootNode, this._rootBabylonMesh);
  90812. }
  90813. break;
  90814. }
  90815. case BABYLON.GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED: {
  90816. this._babylonScene.useRightHandedSystem = true;
  90817. break;
  90818. }
  90819. default: {
  90820. throw new Error("Invalid coordinate system mode " + this.coordinateSystemMode);
  90821. }
  90822. }
  90823. this.onMeshLoadedObservable.notifyObservers(this._rootBabylonMesh);
  90824. return rootNode;
  90825. };
  90826. GLTFLoader.prototype._loadNodesAsync = function (nodes) {
  90827. var promises = new Array();
  90828. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  90829. var node = nodes_1[_i];
  90830. promises.push(this._loadNodeAsync("#/nodes/" + node._index, node));
  90831. }
  90832. promises.push(this._loadAnimationsAsync());
  90833. return Promise.all(promises).then(function () { });
  90834. };
  90835. GLTFLoader.prototype._loadSceneAsync = function (context, scene) {
  90836. var promise = GLTF2.GLTFLoaderExtension._LoadSceneAsync(this, context, scene);
  90837. if (promise) {
  90838. return promise;
  90839. }
  90840. var promises = new Array();
  90841. for (var _i = 0, _a = scene.nodes; _i < _a.length; _i++) {
  90842. var index = _a[_i];
  90843. var node = GLTFLoader._GetProperty(context + "/nodes/" + index, this._gltf.nodes, index);
  90844. promises.push(this._loadNodeAsync("#/nodes/" + node._index, node));
  90845. }
  90846. promises.push(this._loadAnimationsAsync());
  90847. return Promise.all(promises).then(function () { });
  90848. };
  90849. GLTFLoader.prototype._getMeshes = function () {
  90850. var meshes = new Array();
  90851. // Root mesh is always first.
  90852. meshes.push(this._rootBabylonMesh);
  90853. var nodes = this._gltf.nodes;
  90854. if (nodes) {
  90855. for (var _i = 0, nodes_2 = nodes; _i < nodes_2.length; _i++) {
  90856. var node = nodes_2[_i];
  90857. if (node._babylonMesh) {
  90858. meshes.push(node._babylonMesh);
  90859. }
  90860. }
  90861. }
  90862. return meshes;
  90863. };
  90864. GLTFLoader.prototype._getSkeletons = function () {
  90865. var skeletons = new Array();
  90866. var skins = this._gltf.skins;
  90867. if (skins) {
  90868. for (var _i = 0, skins_1 = skins; _i < skins_1.length; _i++) {
  90869. var skin = skins_1[_i];
  90870. if (skin._babylonSkeleton) {
  90871. skeletons.push(skin._babylonSkeleton);
  90872. }
  90873. }
  90874. }
  90875. return skeletons;
  90876. };
  90877. GLTFLoader.prototype._startAnimations = function () {
  90878. var animations = this._gltf.animations;
  90879. if (!animations) {
  90880. return;
  90881. }
  90882. switch (this.animationStartMode) {
  90883. case BABYLON.GLTFLoaderAnimationStartMode.NONE: {
  90884. // do nothing
  90885. break;
  90886. }
  90887. case BABYLON.GLTFLoaderAnimationStartMode.FIRST: {
  90888. var animation = animations[0];
  90889. animation._babylonAnimationGroup.start(true);
  90890. break;
  90891. }
  90892. case BABYLON.GLTFLoaderAnimationStartMode.ALL: {
  90893. for (var _i = 0, animations_1 = animations; _i < animations_1.length; _i++) {
  90894. var animation = animations_1[_i];
  90895. animation._babylonAnimationGroup.start(true);
  90896. }
  90897. break;
  90898. }
  90899. default: {
  90900. BABYLON.Tools.Error("Invalid animation start mode " + this.animationStartMode);
  90901. return;
  90902. }
  90903. }
  90904. };
  90905. GLTFLoader.prototype._loadNodeAsync = function (context, node) {
  90906. var promise = GLTF2.GLTFLoaderExtension._LoadNodeAsync(this, context, node);
  90907. if (promise) {
  90908. return promise;
  90909. }
  90910. if (node._babylonMesh) {
  90911. throw new Error(context + ": Invalid recursive node hierarchy");
  90912. }
  90913. var promises = new Array();
  90914. var babylonMesh = new BABYLON.Mesh(node.name || "node" + node._index, this._babylonScene, node._parent._babylonMesh);
  90915. node._babylonMesh = babylonMesh;
  90916. node._babylonAnimationTargets = node._babylonAnimationTargets || [];
  90917. node._babylonAnimationTargets.push(babylonMesh);
  90918. GLTFLoader._LoadTransform(node, babylonMesh);
  90919. if (node.mesh != undefined) {
  90920. var mesh = GLTFLoader._GetProperty(context + "/mesh", this._gltf.meshes, node.mesh);
  90921. promises.push(this._loadMeshAsync("#/meshes/" + mesh._index, node, mesh));
  90922. }
  90923. if (node.children) {
  90924. for (var _i = 0, _a = node.children; _i < _a.length; _i++) {
  90925. var index = _a[_i];
  90926. var childNode = GLTFLoader._GetProperty(context + "/children/" + index, this._gltf.nodes, index);
  90927. promises.push(this._loadNodeAsync("#/nodes/" + index, childNode));
  90928. }
  90929. }
  90930. this.onMeshLoadedObservable.notifyObservers(babylonMesh);
  90931. return Promise.all(promises).then(function () { });
  90932. };
  90933. GLTFLoader.prototype._loadMeshAsync = function (context, node, mesh) {
  90934. // TODO: instancing
  90935. var promises = new Array();
  90936. var primitives = mesh.primitives;
  90937. if (!primitives || primitives.length === 0) {
  90938. throw new Error(context + ": Primitives are missing");
  90939. }
  90940. GLTF2.ArrayItem.Assign(primitives);
  90941. for (var _i = 0, primitives_1 = primitives; _i < primitives_1.length; _i++) {
  90942. var primitive = primitives_1[_i];
  90943. promises.push(this._loadPrimitiveAsync(context + "/primitives/" + primitive._index, node, mesh, primitive));
  90944. }
  90945. if (node.skin != undefined) {
  90946. var skin = GLTFLoader._GetProperty(context + "/skin", this._gltf.skins, node.skin);
  90947. promises.push(this._loadSkinAsync("#/skins/" + skin._index, node, mesh, skin));
  90948. }
  90949. return Promise.all(promises).then(function () {
  90950. if (node._primitiveBabylonMeshes) {
  90951. for (var _i = 0, _a = node._primitiveBabylonMeshes; _i < _a.length; _i++) {
  90952. var primitiveBabylonMesh = _a[_i];
  90953. primitiveBabylonMesh._refreshBoundingInfo(true);
  90954. }
  90955. }
  90956. });
  90957. };
  90958. GLTFLoader.prototype._loadPrimitiveAsync = function (context, node, mesh, primitive) {
  90959. var _this = this;
  90960. var promises = new Array();
  90961. var babylonMesh = new BABYLON.Mesh((mesh.name || node._babylonMesh.name) + "_" + primitive._index, this._babylonScene, node._babylonMesh);
  90962. babylonMesh.setEnabled(false);
  90963. node._primitiveBabylonMeshes = node._primitiveBabylonMeshes || [];
  90964. node._primitiveBabylonMeshes[primitive._index] = babylonMesh;
  90965. this._createMorphTargets(context, node, mesh, primitive, babylonMesh);
  90966. promises.push(this._loadVertexDataAsync(context, primitive, babylonMesh).then(function (babylonVertexData) {
  90967. new BABYLON.Geometry(babylonMesh.name, _this._babylonScene, babylonVertexData, false, babylonMesh);
  90968. return _this._loadMorphTargetsAsync(context, primitive, babylonMesh, babylonVertexData);
  90969. }));
  90970. if (primitive.material == undefined) {
  90971. babylonMesh.material = this._getDefaultMaterial();
  90972. }
  90973. else {
  90974. var material = GLTFLoader._GetProperty(context + "/material", this._gltf.materials, primitive.material);
  90975. promises.push(this._loadMaterialAsync("#/materials/" + material._index, material, babylonMesh));
  90976. }
  90977. return Promise.all(promises).then(function () {
  90978. babylonMesh.setEnabled(true);
  90979. });
  90980. };
  90981. GLTFLoader.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) {
  90982. var _this = this;
  90983. var attributes = primitive.attributes;
  90984. if (!attributes) {
  90985. throw new Error(context + ": Attributes are missing");
  90986. }
  90987. if (primitive.mode && primitive.mode !== 4 /* TRIANGLES */) {
  90988. // TODO: handle other primitive modes
  90989. throw new Error(context + ": Mode " + primitive.mode + " is not currently supported");
  90990. }
  90991. var promises = new Array();
  90992. var babylonVertexData = new BABYLON.VertexData();
  90993. if (primitive.indices == undefined) {
  90994. var positionAccessorIndex = attributes["POSITION"];
  90995. if (positionAccessorIndex != undefined) {
  90996. var accessor = GLTFLoader._GetProperty(context + "/attributes/POSITION", this._gltf.accessors, positionAccessorIndex);
  90997. babylonVertexData.indices = new Uint32Array(accessor.count);
  90998. for (var i = 0; i < babylonVertexData.indices.length; i++) {
  90999. babylonVertexData.indices[i] = i;
  91000. }
  91001. }
  91002. }
  91003. else {
  91004. var indicesAccessor = GLTFLoader._GetProperty(context + "/indices", this._gltf.accessors, primitive.indices);
  91005. promises.push(this._loadAccessorAsync("#/accessors/" + indicesAccessor._index, indicesAccessor).then(function (data) {
  91006. babylonVertexData.indices = data;
  91007. }));
  91008. }
  91009. var loadAttribute = function (attribute, kind) {
  91010. if (attributes[attribute] == undefined) {
  91011. return;
  91012. }
  91013. babylonMesh._delayInfo = babylonMesh._delayInfo || [];
  91014. if (babylonMesh._delayInfo.indexOf(kind) === -1) {
  91015. babylonMesh._delayInfo.push(kind);
  91016. }
  91017. var accessor = GLTFLoader._GetProperty(context + "/attributes/" + attribute, _this._gltf.accessors, attributes[attribute]);
  91018. promises.push(_this._loadAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  91019. var attributeData = GLTFLoader._ConvertToFloat32Array(context, accessor, data);
  91020. if (attribute === "COLOR_0") {
  91021. // Assume vertex color has alpha on the mesh. The alphaMode of the material controls whether the material should use alpha or not.
  91022. babylonMesh.hasVertexAlpha = true;
  91023. if (accessor.type === "VEC3") {
  91024. attributeData = GLTFLoader._ConvertVec3ToVec4(context, attributeData);
  91025. }
  91026. }
  91027. babylonVertexData.set(attributeData, kind);
  91028. }));
  91029. };
  91030. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind);
  91031. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind);
  91032. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind);
  91033. loadAttribute("TEXCOORD_0", BABYLON.VertexBuffer.UVKind);
  91034. loadAttribute("TEXCOORD_1", BABYLON.VertexBuffer.UV2Kind);
  91035. loadAttribute("JOINTS_0", BABYLON.VertexBuffer.MatricesIndicesKind);
  91036. loadAttribute("WEIGHTS_0", BABYLON.VertexBuffer.MatricesWeightsKind);
  91037. loadAttribute("COLOR_0", BABYLON.VertexBuffer.ColorKind);
  91038. return Promise.all(promises).then(function () {
  91039. return babylonVertexData;
  91040. });
  91041. };
  91042. GLTFLoader.prototype._createMorphTargets = function (context, node, mesh, primitive, babylonMesh) {
  91043. if (!primitive.targets) {
  91044. return;
  91045. }
  91046. if (node._numMorphTargets == undefined) {
  91047. node._numMorphTargets = primitive.targets.length;
  91048. }
  91049. else if (primitive.targets.length !== node._numMorphTargets) {
  91050. throw new Error(context + ": Primitives do not have the same number of targets");
  91051. }
  91052. babylonMesh.morphTargetManager = new BABYLON.MorphTargetManager();
  91053. for (var index = 0; index < primitive.targets.length; index++) {
  91054. var weight = node.weights ? node.weights[index] : mesh.weights ? mesh.weights[index] : 0;
  91055. babylonMesh.morphTargetManager.addTarget(new BABYLON.MorphTarget("morphTarget" + index, weight));
  91056. // TODO: tell the target whether it has positions, normals, tangents
  91057. }
  91058. };
  91059. GLTFLoader.prototype._loadMorphTargetsAsync = function (context, primitive, babylonMesh, babylonVertexData) {
  91060. if (!primitive.targets) {
  91061. return Promise.resolve();
  91062. }
  91063. var promises = new Array();
  91064. var morphTargetManager = babylonMesh.morphTargetManager;
  91065. for (var index = 0; index < morphTargetManager.numTargets; index++) {
  91066. var babylonMorphTarget = morphTargetManager.getTarget(index);
  91067. promises.push(this._loadMorphTargetVertexDataAsync(context + "/targets/" + index, babylonVertexData, primitive.targets[index], babylonMorphTarget));
  91068. }
  91069. return Promise.all(promises).then(function () { });
  91070. };
  91071. GLTFLoader.prototype._loadMorphTargetVertexDataAsync = function (context, babylonVertexData, attributes, babylonMorphTarget) {
  91072. var _this = this;
  91073. var promises = new Array();
  91074. var loadAttribute = function (attribute, setData) {
  91075. if (attributes[attribute] == undefined) {
  91076. return;
  91077. }
  91078. var accessor = GLTFLoader._GetProperty(context + "/" + attribute, _this._gltf.accessors, attributes[attribute]);
  91079. promises.push(_this._loadAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  91080. setData(data);
  91081. }));
  91082. };
  91083. loadAttribute("POSITION", function (data) {
  91084. if (babylonVertexData.positions) {
  91085. for (var i = 0; i < data.length; i++) {
  91086. data[i] += babylonVertexData.positions[i];
  91087. }
  91088. babylonMorphTarget.setPositions(data);
  91089. }
  91090. });
  91091. loadAttribute("NORMAL", function (data) {
  91092. if (babylonVertexData.normals) {
  91093. for (var i = 0; i < data.length; i++) {
  91094. data[i] += babylonVertexData.normals[i];
  91095. }
  91096. babylonMorphTarget.setNormals(data);
  91097. }
  91098. });
  91099. loadAttribute("TANGENT", function (data) {
  91100. if (babylonVertexData.tangents) {
  91101. // Tangent data for morph targets is stored as xyz delta.
  91102. // The vertexData.tangent is stored as xyzw.
  91103. // So we need to skip every fourth vertexData.tangent.
  91104. for (var i = 0, j = 0; i < data.length; i++) {
  91105. data[i] += babylonVertexData.tangents[j++];
  91106. if ((i + 1) % 3 == 0) {
  91107. j++;
  91108. }
  91109. }
  91110. babylonMorphTarget.setTangents(data);
  91111. }
  91112. });
  91113. return Promise.all(promises).then(function () { });
  91114. };
  91115. GLTFLoader._ConvertToFloat32Array = function (context, accessor, data) {
  91116. if (accessor.componentType == 5126 /* FLOAT */) {
  91117. return data;
  91118. }
  91119. var factor = 1;
  91120. if (accessor.normalized) {
  91121. switch (accessor.componentType) {
  91122. case 5121 /* UNSIGNED_BYTE */: {
  91123. factor = 1 / 255;
  91124. break;
  91125. }
  91126. case 5123 /* UNSIGNED_SHORT */: {
  91127. factor = 1 / 65535;
  91128. break;
  91129. }
  91130. default: {
  91131. throw new Error(context + ": Invalid component type " + accessor.componentType);
  91132. }
  91133. }
  91134. }
  91135. var result = new Float32Array(accessor.count * GLTFLoader._GetNumComponents(context, accessor.type));
  91136. for (var i = 0; i < result.length; i++) {
  91137. result[i] = data[i] * factor;
  91138. }
  91139. return result;
  91140. };
  91141. GLTFLoader._ConvertVec3ToVec4 = function (context, data) {
  91142. var result = new Float32Array(data.length / 3 * 4);
  91143. var offset = 0;
  91144. for (var i = 0; i < result.length; i++) {
  91145. if ((i + 1) % 4 === 0) {
  91146. result[i] = 1;
  91147. }
  91148. else {
  91149. result[i] = data[offset++];
  91150. }
  91151. }
  91152. return result;
  91153. };
  91154. GLTFLoader._LoadTransform = function (node, babylonNode) {
  91155. var position = BABYLON.Vector3.Zero();
  91156. var rotation = BABYLON.Quaternion.Identity();
  91157. var scaling = BABYLON.Vector3.One();
  91158. if (node.matrix) {
  91159. var matrix = BABYLON.Matrix.FromArray(node.matrix);
  91160. matrix.decompose(scaling, rotation, position);
  91161. }
  91162. else {
  91163. if (node.translation)
  91164. position = BABYLON.Vector3.FromArray(node.translation);
  91165. if (node.rotation)
  91166. rotation = BABYLON.Quaternion.FromArray(node.rotation);
  91167. if (node.scale)
  91168. scaling = BABYLON.Vector3.FromArray(node.scale);
  91169. }
  91170. babylonNode.position = position;
  91171. babylonNode.rotationQuaternion = rotation;
  91172. babylonNode.scaling = scaling;
  91173. };
  91174. GLTFLoader.prototype._loadSkinAsync = function (context, node, mesh, skin) {
  91175. var _this = this;
  91176. var assignSkeleton = function () {
  91177. for (var _i = 0, _a = node._primitiveBabylonMeshes; _i < _a.length; _i++) {
  91178. var babylonMesh = _a[_i];
  91179. babylonMesh.skeleton = skin._babylonSkeleton;
  91180. }
  91181. node._babylonMesh.parent = _this._rootBabylonMesh;
  91182. node._babylonMesh.position = BABYLON.Vector3.Zero();
  91183. node._babylonMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  91184. node._babylonMesh.scaling = BABYLON.Vector3.One();
  91185. };
  91186. if (skin._loaded) {
  91187. assignSkeleton();
  91188. return skin._loaded;
  91189. }
  91190. // TODO: split into two parts so that bones are created before inverseBindMatricesData is loaded (for compiling materials).
  91191. return (skin._loaded = this._loadSkinInverseBindMatricesDataAsync(context, skin).then(function (inverseBindMatricesData) {
  91192. var skeletonId = "skeleton" + skin._index;
  91193. var babylonSkeleton = new BABYLON.Skeleton(skin.name || skeletonId, skeletonId, _this._babylonScene);
  91194. skin._babylonSkeleton = babylonSkeleton;
  91195. _this._loadBones(context, skin, inverseBindMatricesData);
  91196. assignSkeleton();
  91197. }));
  91198. };
  91199. GLTFLoader.prototype._loadSkinInverseBindMatricesDataAsync = function (context, skin) {
  91200. if (skin.inverseBindMatrices == undefined) {
  91201. return Promise.resolve(null);
  91202. }
  91203. var accessor = GLTFLoader._GetProperty(context + "/inverseBindMatrices", this._gltf.accessors, skin.inverseBindMatrices);
  91204. return this._loadAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  91205. return data;
  91206. });
  91207. };
  91208. GLTFLoader.prototype._createBone = function (node, skin, parent, localMatrix, baseMatrix, index) {
  91209. var babylonBone = new BABYLON.Bone(node.name || "joint" + node._index, skin._babylonSkeleton, parent, localMatrix, null, baseMatrix, index);
  91210. node._babylonAnimationTargets = node._babylonAnimationTargets || [];
  91211. node._babylonAnimationTargets.push(babylonBone);
  91212. return babylonBone;
  91213. };
  91214. GLTFLoader.prototype._loadBones = function (context, skin, inverseBindMatricesData) {
  91215. var babylonBones = {};
  91216. for (var _i = 0, _a = skin.joints; _i < _a.length; _i++) {
  91217. var index = _a[_i];
  91218. var node = GLTFLoader._GetProperty(context + "/joints/" + index, this._gltf.nodes, index);
  91219. this._loadBone(node, skin, inverseBindMatricesData, babylonBones);
  91220. }
  91221. };
  91222. GLTFLoader.prototype._loadBone = function (node, skin, inverseBindMatricesData, babylonBones) {
  91223. var babylonBone = babylonBones[node._index];
  91224. if (babylonBone) {
  91225. return babylonBone;
  91226. }
  91227. var boneIndex = skin.joints.indexOf(node._index);
  91228. var baseMatrix = BABYLON.Matrix.Identity();
  91229. if (inverseBindMatricesData && boneIndex !== -1) {
  91230. baseMatrix = BABYLON.Matrix.FromArray(inverseBindMatricesData, boneIndex * 16);
  91231. baseMatrix.invertToRef(baseMatrix);
  91232. }
  91233. var babylonParentBone = null;
  91234. if (node._parent._babylonMesh !== this._rootBabylonMesh) {
  91235. babylonParentBone = this._loadBone(node._parent, skin, inverseBindMatricesData, babylonBones);
  91236. baseMatrix.multiplyToRef(babylonParentBone.getInvertedAbsoluteTransform(), baseMatrix);
  91237. }
  91238. babylonBone = this._createBone(node, skin, babylonParentBone, this._getNodeMatrix(node), baseMatrix, boneIndex);
  91239. babylonBones[node._index] = babylonBone;
  91240. return babylonBone;
  91241. };
  91242. GLTFLoader.prototype._getNodeMatrix = function (node) {
  91243. return node.matrix ?
  91244. BABYLON.Matrix.FromArray(node.matrix) :
  91245. 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());
  91246. };
  91247. GLTFLoader.prototype._loadAnimationsAsync = function () {
  91248. var animations = this._gltf.animations;
  91249. if (!animations) {
  91250. return Promise.resolve();
  91251. }
  91252. var promises = new Array();
  91253. for (var index = 0; index < animations.length; index++) {
  91254. var animation = animations[index];
  91255. promises.push(this._loadAnimationAsync("#/animations/" + index, animation));
  91256. }
  91257. return Promise.all(promises).then(function () { });
  91258. };
  91259. GLTFLoader.prototype._loadAnimationAsync = function (context, animation) {
  91260. var babylonAnimationGroup = new BABYLON.AnimationGroup(animation.name || "animation" + animation._index, this._babylonScene);
  91261. animation._babylonAnimationGroup = babylonAnimationGroup;
  91262. var promises = new Array();
  91263. GLTF2.ArrayItem.Assign(animation.channels);
  91264. GLTF2.ArrayItem.Assign(animation.samplers);
  91265. for (var _i = 0, _a = animation.channels; _i < _a.length; _i++) {
  91266. var channel = _a[_i];
  91267. promises.push(this._loadAnimationChannelAsync(context + "/channels/" + channel._index, context, animation, channel, babylonAnimationGroup));
  91268. }
  91269. return Promise.all(promises).then(function () {
  91270. babylonAnimationGroup.normalize();
  91271. });
  91272. };
  91273. GLTFLoader.prototype._loadAnimationChannelAsync = function (context, animationContext, animation, channel, babylonAnimationGroup) {
  91274. var targetNode = GLTFLoader._GetProperty(context + "/target/node", this._gltf.nodes, channel.target.node);
  91275. if (!targetNode._babylonMesh) {
  91276. return Promise.resolve();
  91277. }
  91278. var sampler = GLTFLoader._GetProperty(context + "/sampler", animation.samplers, channel.sampler);
  91279. return this._loadAnimationSamplerAsync(animationContext + "/samplers/" + channel.sampler, sampler).then(function (data) {
  91280. var targetPath;
  91281. var animationType;
  91282. switch (channel.target.path) {
  91283. case "translation" /* TRANSLATION */: {
  91284. targetPath = "position";
  91285. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  91286. break;
  91287. }
  91288. case "rotation" /* ROTATION */: {
  91289. targetPath = "rotationQuaternion";
  91290. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  91291. break;
  91292. }
  91293. case "scale" /* SCALE */: {
  91294. targetPath = "scaling";
  91295. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  91296. break;
  91297. }
  91298. case "weights" /* WEIGHTS */: {
  91299. targetPath = "influence";
  91300. animationType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  91301. break;
  91302. }
  91303. default: {
  91304. throw new Error(context + ": Invalid target path " + channel.target.path);
  91305. }
  91306. }
  91307. var outputBufferOffset = 0;
  91308. var getNextOutputValue;
  91309. switch (targetPath) {
  91310. case "position": {
  91311. getNextOutputValue = function () {
  91312. var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset);
  91313. outputBufferOffset += 3;
  91314. return value;
  91315. };
  91316. break;
  91317. }
  91318. case "rotationQuaternion": {
  91319. getNextOutputValue = function () {
  91320. var value = BABYLON.Quaternion.FromArray(data.output, outputBufferOffset);
  91321. outputBufferOffset += 4;
  91322. return value;
  91323. };
  91324. break;
  91325. }
  91326. case "scaling": {
  91327. getNextOutputValue = function () {
  91328. var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset);
  91329. outputBufferOffset += 3;
  91330. return value;
  91331. };
  91332. break;
  91333. }
  91334. case "influence": {
  91335. getNextOutputValue = function () {
  91336. var value = new Array(targetNode._numMorphTargets);
  91337. for (var i = 0; i < targetNode._numMorphTargets; i++) {
  91338. value[i] = data.output[outputBufferOffset++];
  91339. }
  91340. return value;
  91341. };
  91342. break;
  91343. }
  91344. }
  91345. var getNextKey;
  91346. switch (data.interpolation) {
  91347. case "STEP" /* STEP */: {
  91348. getNextKey = function (frameIndex) { return ({
  91349. frame: data.input[frameIndex],
  91350. value: getNextOutputValue(),
  91351. interpolation: BABYLON.AnimationKeyInterpolation.STEP
  91352. }); };
  91353. break;
  91354. }
  91355. case "LINEAR" /* LINEAR */: {
  91356. getNextKey = function (frameIndex) { return ({
  91357. frame: data.input[frameIndex],
  91358. value: getNextOutputValue()
  91359. }); };
  91360. break;
  91361. }
  91362. case "CUBICSPLINE" /* CUBICSPLINE */: {
  91363. getNextKey = function (frameIndex) { return ({
  91364. frame: data.input[frameIndex],
  91365. inTangent: getNextOutputValue(),
  91366. value: getNextOutputValue(),
  91367. outTangent: getNextOutputValue()
  91368. }); };
  91369. break;
  91370. }
  91371. }
  91372. var keys;
  91373. if (data.input.length === 1) {
  91374. var key = getNextKey(0);
  91375. keys = [
  91376. { frame: key.frame, value: key.value },
  91377. { frame: key.frame + 1, value: key.value }
  91378. ];
  91379. }
  91380. else {
  91381. keys = new Array(data.input.length);
  91382. for (var frameIndex = 0; frameIndex < data.input.length; frameIndex++) {
  91383. keys[frameIndex] = getNextKey(frameIndex);
  91384. }
  91385. }
  91386. if (targetPath === "influence") {
  91387. var _loop_1 = function (targetIndex) {
  91388. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  91389. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  91390. babylonAnimation.setKeys(keys.map(function (key) { return ({
  91391. frame: key.frame,
  91392. inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined,
  91393. value: key.value[targetIndex],
  91394. outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined
  91395. }); }));
  91396. for (var _i = 0, _a = targetNode._primitiveBabylonMeshes; _i < _a.length; _i++) {
  91397. var babylonMesh = _a[_i];
  91398. var morphTarget = babylonMesh.morphTargetManager.getTarget(targetIndex);
  91399. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, morphTarget);
  91400. }
  91401. };
  91402. for (var targetIndex = 0; targetIndex < targetNode._numMorphTargets; targetIndex++) {
  91403. _loop_1(targetIndex);
  91404. }
  91405. }
  91406. else {
  91407. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  91408. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  91409. babylonAnimation.setKeys(keys);
  91410. if (targetNode._babylonAnimationTargets) {
  91411. for (var _i = 0, _a = targetNode._babylonAnimationTargets; _i < _a.length; _i++) {
  91412. var target = _a[_i];
  91413. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, target);
  91414. }
  91415. }
  91416. }
  91417. });
  91418. };
  91419. GLTFLoader.prototype._loadAnimationSamplerAsync = function (context, sampler) {
  91420. if (sampler._data) {
  91421. return sampler._data;
  91422. }
  91423. var interpolation = sampler.interpolation || "LINEAR" /* LINEAR */;
  91424. switch (interpolation) {
  91425. case "STEP" /* STEP */:
  91426. case "LINEAR" /* LINEAR */:
  91427. case "CUBICSPLINE" /* CUBICSPLINE */: {
  91428. break;
  91429. }
  91430. default: {
  91431. throw new Error(context + ": Invalid interpolation " + sampler.interpolation);
  91432. }
  91433. }
  91434. var inputData;
  91435. var outputData;
  91436. var inputAccessor = GLTFLoader._GetProperty(context + "/input", this._gltf.accessors, sampler.input);
  91437. var outputAccessor = GLTFLoader._GetProperty(context + "/output", this._gltf.accessors, sampler.output);
  91438. sampler._data = Promise.all([
  91439. this._loadAccessorAsync("#/accessors/" + inputAccessor._index, inputAccessor).then(function (data) {
  91440. inputData = data;
  91441. }),
  91442. this._loadAccessorAsync("#/accessors/" + outputAccessor._index, outputAccessor).then(function (data) {
  91443. outputData = data;
  91444. })
  91445. ]).then(function () {
  91446. return {
  91447. input: inputData,
  91448. interpolation: interpolation,
  91449. output: outputData,
  91450. };
  91451. });
  91452. return sampler._data;
  91453. };
  91454. GLTFLoader.prototype._loadBufferAsync = function (context, buffer) {
  91455. if (buffer._data) {
  91456. return buffer._data;
  91457. }
  91458. if (!buffer.uri) {
  91459. throw new Error(context + ": Uri is missing");
  91460. }
  91461. buffer._data = this._loadUriAsync(context, buffer.uri);
  91462. return buffer._data;
  91463. };
  91464. GLTFLoader.prototype._loadBufferViewAsync = function (context, bufferView) {
  91465. if (bufferView._data) {
  91466. return bufferView._data;
  91467. }
  91468. var buffer = GLTFLoader._GetProperty(context + "/buffer", this._gltf.buffers, bufferView.buffer);
  91469. bufferView._data = this._loadBufferAsync("#/buffers/" + buffer._index, buffer).then(function (bufferData) {
  91470. try {
  91471. return new Uint8Array(bufferData.buffer, bufferData.byteOffset + (bufferView.byteOffset || 0), bufferView.byteLength);
  91472. }
  91473. catch (e) {
  91474. throw new Error(context + ": " + e.message);
  91475. }
  91476. });
  91477. return bufferView._data;
  91478. };
  91479. GLTFLoader.prototype._loadAccessorAsync = function (context, accessor) {
  91480. var _this = this;
  91481. if (accessor.sparse) {
  91482. throw new Error(context + ": Sparse accessors are not currently supported");
  91483. }
  91484. if (accessor._data) {
  91485. return accessor._data;
  91486. }
  91487. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, accessor.bufferView);
  91488. accessor._data = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView).then(function (bufferViewData) {
  91489. var numComponents = GLTFLoader._GetNumComponents(context, accessor.type);
  91490. var byteOffset = accessor.byteOffset || 0;
  91491. var byteStride = bufferView.byteStride;
  91492. if (byteStride === 0) {
  91493. BABYLON.Tools.Warn(context + ": Byte stride of 0 is not valid");
  91494. }
  91495. try {
  91496. switch (accessor.componentType) {
  91497. case 5120 /* BYTE */: {
  91498. return _this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  91499. }
  91500. case 5121 /* UNSIGNED_BYTE */: {
  91501. return _this._buildArrayBuffer(Uint8Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  91502. }
  91503. case 5122 /* SHORT */: {
  91504. return _this._buildArrayBuffer(Int16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  91505. }
  91506. case 5123 /* UNSIGNED_SHORT */: {
  91507. return _this._buildArrayBuffer(Uint16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  91508. }
  91509. case 5125 /* UNSIGNED_INT */: {
  91510. return _this._buildArrayBuffer(Uint32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  91511. }
  91512. case 5126 /* FLOAT */: {
  91513. return _this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  91514. }
  91515. default: {
  91516. throw new Error(context + ": Invalid component type " + accessor.componentType);
  91517. }
  91518. }
  91519. }
  91520. catch (e) {
  91521. throw new Error(context + ": " + e);
  91522. }
  91523. });
  91524. return accessor._data;
  91525. };
  91526. GLTFLoader.prototype._buildArrayBuffer = function (typedArray, data, byteOffset, count, numComponents, byteStride) {
  91527. byteOffset += data.byteOffset;
  91528. var targetLength = count * numComponents;
  91529. if (!byteStride || byteStride === numComponents * typedArray.BYTES_PER_ELEMENT) {
  91530. return new typedArray(data.buffer, byteOffset, targetLength);
  91531. }
  91532. var elementStride = byteStride / typedArray.BYTES_PER_ELEMENT;
  91533. var sourceBuffer = new typedArray(data.buffer, byteOffset, elementStride * count);
  91534. var targetBuffer = new typedArray(targetLength);
  91535. var sourceIndex = 0;
  91536. var targetIndex = 0;
  91537. while (targetIndex < targetLength) {
  91538. for (var componentIndex = 0; componentIndex < numComponents; componentIndex++) {
  91539. targetBuffer[targetIndex] = sourceBuffer[sourceIndex + componentIndex];
  91540. targetIndex++;
  91541. }
  91542. sourceIndex += elementStride;
  91543. }
  91544. return targetBuffer;
  91545. };
  91546. GLTFLoader.prototype._getDefaultMaterial = function () {
  91547. var id = "__gltf_default";
  91548. var babylonMaterial = this._babylonScene.getMaterialByName(id);
  91549. if (!babylonMaterial) {
  91550. babylonMaterial = new BABYLON.PBRMaterial(id, this._babylonScene);
  91551. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  91552. babylonMaterial.sideOrientation = this._babylonScene.useRightHandedSystem ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation;
  91553. babylonMaterial.metallic = 1;
  91554. babylonMaterial.roughness = 1;
  91555. this.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  91556. }
  91557. return babylonMaterial;
  91558. };
  91559. GLTFLoader.prototype._loadMaterialMetallicRoughnessPropertiesAsync = function (context, material) {
  91560. var promises = new Array();
  91561. var babylonMaterial = material._babylonMaterial;
  91562. // Ensure metallic workflow
  91563. babylonMaterial.metallic = 1;
  91564. babylonMaterial.roughness = 1;
  91565. var properties = material.pbrMetallicRoughness;
  91566. if (properties) {
  91567. if (properties.baseColorFactor) {
  91568. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.baseColorFactor);
  91569. babylonMaterial.alpha = properties.baseColorFactor[3];
  91570. }
  91571. else {
  91572. babylonMaterial.albedoColor = BABYLON.Color3.White();
  91573. }
  91574. babylonMaterial.metallic = properties.metallicFactor == undefined ? 1 : properties.metallicFactor;
  91575. babylonMaterial.roughness = properties.roughnessFactor == undefined ? 1 : properties.roughnessFactor;
  91576. if (properties.baseColorTexture) {
  91577. promises.push(this._loadTextureAsync(context + "/baseColorTexture", properties.baseColorTexture, function (texture) {
  91578. babylonMaterial.albedoTexture = texture;
  91579. }));
  91580. }
  91581. if (properties.metallicRoughnessTexture) {
  91582. promises.push(this._loadTextureAsync(context + "/metallicRoughnessTexture", properties.metallicRoughnessTexture, function (texture) {
  91583. babylonMaterial.metallicTexture = texture;
  91584. }));
  91585. babylonMaterial.useMetallnessFromMetallicTextureBlue = true;
  91586. babylonMaterial.useRoughnessFromMetallicTextureGreen = true;
  91587. babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;
  91588. }
  91589. }
  91590. this._loadMaterialAlphaProperties(context, material);
  91591. return Promise.all(promises).then(function () { });
  91592. };
  91593. GLTFLoader.prototype._loadMaterialAsync = function (context, material, babylonMesh) {
  91594. var promise = GLTF2.GLTFLoaderExtension._LoadMaterialAsync(this, context, material, babylonMesh);
  91595. if (promise) {
  91596. return promise;
  91597. }
  91598. material._babylonMeshes = material._babylonMeshes || [];
  91599. material._babylonMeshes.push(babylonMesh);
  91600. if (material._loaded) {
  91601. babylonMesh.material = material._babylonMaterial;
  91602. return material._loaded;
  91603. }
  91604. var promises = new Array();
  91605. var babylonMaterial = this._createMaterial(material);
  91606. material._babylonMaterial = babylonMaterial;
  91607. promises.push(this._loadMaterialBasePropertiesAsync(context, material));
  91608. promises.push(this._loadMaterialMetallicRoughnessPropertiesAsync(context, material));
  91609. this.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  91610. babylonMesh.material = babylonMaterial;
  91611. return (material._loaded = Promise.all(promises).then(function () { }));
  91612. };
  91613. GLTFLoader.prototype._createMaterial = function (material) {
  91614. var babylonMaterial = new BABYLON.PBRMaterial(material.name || "material" + material._index, this._babylonScene);
  91615. babylonMaterial.sideOrientation = this._babylonScene.useRightHandedSystem ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation;
  91616. return babylonMaterial;
  91617. };
  91618. GLTFLoader.prototype._loadMaterialBasePropertiesAsync = function (context, material) {
  91619. var promises = new Array();
  91620. var babylonMaterial = material._babylonMaterial;
  91621. babylonMaterial.emissiveColor = material.emissiveFactor ? BABYLON.Color3.FromArray(material.emissiveFactor) : new BABYLON.Color3(0, 0, 0);
  91622. if (material.doubleSided) {
  91623. babylonMaterial.backFaceCulling = false;
  91624. babylonMaterial.twoSidedLighting = true;
  91625. }
  91626. if (material.normalTexture) {
  91627. promises.push(this._loadTextureAsync(context + "/normalTexture", material.normalTexture, function (texture) {
  91628. babylonMaterial.bumpTexture = texture;
  91629. }));
  91630. babylonMaterial.invertNormalMapX = !this._babylonScene.useRightHandedSystem;
  91631. babylonMaterial.invertNormalMapY = this._babylonScene.useRightHandedSystem;
  91632. if (material.normalTexture.scale != undefined) {
  91633. babylonMaterial.bumpTexture.level = material.normalTexture.scale;
  91634. }
  91635. }
  91636. if (material.occlusionTexture) {
  91637. promises.push(this._loadTextureAsync(context + "/occlusionTexture", material.occlusionTexture, function (texture) {
  91638. babylonMaterial.ambientTexture = texture;
  91639. }));
  91640. babylonMaterial.useAmbientInGrayScale = true;
  91641. if (material.occlusionTexture.strength != undefined) {
  91642. babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;
  91643. }
  91644. }
  91645. if (material.emissiveTexture) {
  91646. promises.push(this._loadTextureAsync(context + "/emissiveTexture", material.emissiveTexture, function (texture) {
  91647. babylonMaterial.emissiveTexture = texture;
  91648. }));
  91649. }
  91650. return Promise.all(promises).then(function () { });
  91651. };
  91652. GLTFLoader.prototype._loadMaterialAlphaProperties = function (context, material) {
  91653. var babylonMaterial = material._babylonMaterial;
  91654. var alphaMode = material.alphaMode || "OPAQUE" /* OPAQUE */;
  91655. switch (alphaMode) {
  91656. case "OPAQUE" /* OPAQUE */: {
  91657. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  91658. break;
  91659. }
  91660. case "MASK" /* MASK */: {
  91661. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
  91662. babylonMaterial.alphaCutOff = (material.alphaCutoff == undefined ? 0.5 : material.alphaCutoff);
  91663. if (babylonMaterial.alpha) {
  91664. if (babylonMaterial.alpha === 0) {
  91665. babylonMaterial.alphaCutOff = 1;
  91666. }
  91667. else {
  91668. babylonMaterial.alphaCutOff /= babylonMaterial.alpha;
  91669. }
  91670. babylonMaterial.alpha = 1;
  91671. }
  91672. if (babylonMaterial.albedoTexture) {
  91673. babylonMaterial.albedoTexture.hasAlpha = true;
  91674. }
  91675. break;
  91676. }
  91677. case "BLEND" /* BLEND */: {
  91678. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND;
  91679. if (babylonMaterial.albedoTexture) {
  91680. babylonMaterial.albedoTexture.hasAlpha = true;
  91681. babylonMaterial.useAlphaFromAlbedoTexture = true;
  91682. }
  91683. break;
  91684. }
  91685. default: {
  91686. throw new Error(context + ": Invalid alpha mode " + material.alphaMode);
  91687. }
  91688. }
  91689. };
  91690. GLTFLoader.prototype._loadTextureAsync = function (context, textureInfo, assign) {
  91691. var _this = this;
  91692. var texture = GLTFLoader._GetProperty(context + "/index", this._gltf.textures, textureInfo.index);
  91693. context = "#/textures/" + textureInfo.index;
  91694. var promises = new Array();
  91695. var sampler = (texture.sampler == undefined ? this._defaultSampler : GLTFLoader._GetProperty(context + "/sampler", this._gltf.samplers, texture.sampler));
  91696. var samplerData = this._loadSampler("#/samplers/" + sampler._index, sampler);
  91697. var deferred = new BABYLON.Deferred();
  91698. var babylonTexture = new BABYLON.Texture(null, this._babylonScene, samplerData.noMipMaps, false, samplerData.samplingMode, function () {
  91699. if (!_this._disposed) {
  91700. deferred.resolve();
  91701. }
  91702. }, function (message, exception) {
  91703. if (!_this._disposed) {
  91704. deferred.reject(new Error(context + ": " + (exception && exception.message) ? exception.message : message || "Failed to load texture"));
  91705. }
  91706. });
  91707. promises.push(deferred.promise);
  91708. babylonTexture.name = texture.name || "texture" + texture._index;
  91709. babylonTexture.wrapU = samplerData.wrapU;
  91710. babylonTexture.wrapV = samplerData.wrapV;
  91711. babylonTexture.coordinatesIndex = textureInfo.texCoord || 0;
  91712. var image = GLTFLoader._GetProperty(context + "/source", this._gltf.images, texture.source);
  91713. promises.push(this._loadImageAsync("#/images/" + image._index, image).then(function (objectURL) {
  91714. babylonTexture.updateURL(objectURL);
  91715. }));
  91716. assign(babylonTexture);
  91717. this.onTextureLoadedObservable.notifyObservers(babylonTexture);
  91718. return Promise.all(promises).then(function () { });
  91719. };
  91720. GLTFLoader.prototype._loadSampler = function (context, sampler) {
  91721. if (!sampler._data) {
  91722. sampler._data = {
  91723. noMipMaps: (sampler.minFilter === 9728 /* NEAREST */ || sampler.minFilter === 9729 /* LINEAR */),
  91724. samplingMode: GLTFLoader._GetTextureSamplingMode(context, sampler.magFilter, sampler.minFilter),
  91725. wrapU: GLTFLoader._GetTextureWrapMode(context, sampler.wrapS),
  91726. wrapV: GLTFLoader._GetTextureWrapMode(context, sampler.wrapT)
  91727. };
  91728. }
  91729. ;
  91730. return sampler._data;
  91731. };
  91732. GLTFLoader.prototype._loadImageAsync = function (context, image) {
  91733. if (image._objectURL) {
  91734. return image._objectURL;
  91735. }
  91736. var promise;
  91737. if (image.uri) {
  91738. promise = this._loadUriAsync(context, image.uri);
  91739. }
  91740. else {
  91741. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, image.bufferView);
  91742. promise = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView);
  91743. }
  91744. image._objectURL = promise.then(function (data) {
  91745. return URL.createObjectURL(new Blob([data], { type: image.mimeType }));
  91746. });
  91747. return image._objectURL;
  91748. };
  91749. GLTFLoader.prototype._loadUriAsync = function (context, uri) {
  91750. var _this = this;
  91751. var promise = GLTF2.GLTFLoaderExtension._LoadUriAsync(this, context, uri);
  91752. if (promise) {
  91753. return promise;
  91754. }
  91755. if (!GLTFLoader._ValidateUri(uri)) {
  91756. throw new Error(context + ": Uri '" + uri + "' is invalid");
  91757. }
  91758. if (BABYLON.Tools.IsBase64(uri)) {
  91759. return Promise.resolve(new Uint8Array(BABYLON.Tools.DecodeBase64(uri)));
  91760. }
  91761. return new Promise(function (resolve, reject) {
  91762. var request = BABYLON.Tools.LoadFile(_this._rootUrl + uri, function (data) {
  91763. if (!_this._disposed) {
  91764. resolve(new Uint8Array(data));
  91765. }
  91766. }, function (event) {
  91767. if (!_this._disposed) {
  91768. try {
  91769. if (request && _this._state === BABYLON.GLTFLoaderState.Loading) {
  91770. request._lengthComputable = event.lengthComputable;
  91771. request._loaded = event.loaded;
  91772. request._total = event.total;
  91773. _this._onProgress();
  91774. }
  91775. }
  91776. catch (e) {
  91777. reject(e);
  91778. }
  91779. }
  91780. }, _this._babylonScene.database, true, function (request, exception) {
  91781. if (!_this._disposed) {
  91782. reject(new BABYLON.LoadFileError(context + ": Failed to load '" + uri + "'" + (request ? ": " + request.status + " " + request.statusText : ""), request));
  91783. }
  91784. });
  91785. _this._requests.push(request);
  91786. });
  91787. };
  91788. GLTFLoader.prototype._onProgress = function () {
  91789. if (!this._progressCallback) {
  91790. return;
  91791. }
  91792. var lengthComputable = true;
  91793. var loaded = 0;
  91794. var total = 0;
  91795. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  91796. var request = _a[_i];
  91797. if (request._lengthComputable === undefined || request._loaded === undefined || request._total === undefined) {
  91798. return;
  91799. }
  91800. lengthComputable = lengthComputable && request._lengthComputable;
  91801. loaded += request._loaded;
  91802. total += request._total;
  91803. }
  91804. this._progressCallback(new BABYLON.SceneLoaderProgressEvent(lengthComputable, loaded, lengthComputable ? total : 0));
  91805. };
  91806. GLTFLoader._GetProperty = function (context, array, index) {
  91807. if (!array || index == undefined || !array[index]) {
  91808. throw new Error(context + ": Failed to find index " + index);
  91809. }
  91810. return array[index];
  91811. };
  91812. GLTFLoader._GetTextureWrapMode = function (context, mode) {
  91813. // Set defaults if undefined
  91814. mode = mode == undefined ? 10497 /* REPEAT */ : mode;
  91815. switch (mode) {
  91816. case 33071 /* CLAMP_TO_EDGE */: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  91817. case 33648 /* MIRRORED_REPEAT */: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  91818. case 10497 /* REPEAT */: return BABYLON.Texture.WRAP_ADDRESSMODE;
  91819. default:
  91820. BABYLON.Tools.Warn(context + ": Invalid texture wrap mode " + mode);
  91821. return BABYLON.Texture.WRAP_ADDRESSMODE;
  91822. }
  91823. };
  91824. GLTFLoader._GetTextureSamplingMode = function (context, magFilter, minFilter) {
  91825. // Set defaults if undefined
  91826. magFilter = magFilter == undefined ? 9729 /* LINEAR */ : magFilter;
  91827. minFilter = minFilter == undefined ? 9987 /* LINEAR_MIPMAP_LINEAR */ : minFilter;
  91828. if (magFilter === 9729 /* LINEAR */) {
  91829. switch (minFilter) {
  91830. case 9728 /* NEAREST */: return BABYLON.Texture.LINEAR_NEAREST;
  91831. case 9729 /* LINEAR */: return BABYLON.Texture.LINEAR_LINEAR;
  91832. case 9984 /* NEAREST_MIPMAP_NEAREST */: return BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST;
  91833. case 9985 /* LINEAR_MIPMAP_NEAREST */: return BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST;
  91834. case 9986 /* NEAREST_MIPMAP_LINEAR */: return BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR;
  91835. case 9987 /* LINEAR_MIPMAP_LINEAR */: return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  91836. default:
  91837. BABYLON.Tools.Warn(context + ": Invalid texture minification filter " + minFilter);
  91838. return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  91839. }
  91840. }
  91841. else {
  91842. if (magFilter !== 9728 /* NEAREST */) {
  91843. BABYLON.Tools.Warn(context + ": Invalid texture magnification filter " + magFilter);
  91844. }
  91845. switch (minFilter) {
  91846. case 9728 /* NEAREST */: return BABYLON.Texture.NEAREST_NEAREST;
  91847. case 9729 /* LINEAR */: return BABYLON.Texture.NEAREST_LINEAR;
  91848. case 9984 /* NEAREST_MIPMAP_NEAREST */: return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  91849. case 9985 /* LINEAR_MIPMAP_NEAREST */: return BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST;
  91850. case 9986 /* NEAREST_MIPMAP_LINEAR */: return BABYLON.Texture.NEAREST_NEAREST_MIPLINEAR;
  91851. case 9987 /* LINEAR_MIPMAP_LINEAR */: return BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR;
  91852. default:
  91853. BABYLON.Tools.Warn(context + ": Invalid texture minification filter " + minFilter);
  91854. return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  91855. }
  91856. }
  91857. };
  91858. GLTFLoader._GetNumComponents = function (context, type) {
  91859. switch (type) {
  91860. case "SCALAR": return 1;
  91861. case "VEC2": return 2;
  91862. case "VEC3": return 3;
  91863. case "VEC4": return 4;
  91864. case "MAT2": return 4;
  91865. case "MAT3": return 9;
  91866. case "MAT4": return 16;
  91867. }
  91868. throw new Error(context + ": Invalid type " + type);
  91869. };
  91870. GLTFLoader._ValidateUri = function (uri) {
  91871. return (BABYLON.Tools.IsBase64(uri) || uri.indexOf("..") === -1);
  91872. };
  91873. GLTFLoader.prototype._compileMaterialsAsync = function () {
  91874. var promises = new Array();
  91875. if (this._gltf.materials) {
  91876. for (var _i = 0, _a = this._gltf.materials; _i < _a.length; _i++) {
  91877. var material = _a[_i];
  91878. var babylonMaterial = material._babylonMaterial;
  91879. var babylonMeshes = material._babylonMeshes;
  91880. if (babylonMaterial && babylonMeshes) {
  91881. for (var _b = 0, babylonMeshes_1 = babylonMeshes; _b < babylonMeshes_1.length; _b++) {
  91882. var babylonMesh = babylonMeshes_1[_b];
  91883. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh));
  91884. if (this.useClipPlane) {
  91885. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh, { clipPlane: true }));
  91886. }
  91887. }
  91888. }
  91889. }
  91890. }
  91891. return Promise.all(promises).then(function () { });
  91892. };
  91893. GLTFLoader.prototype._compileShadowGeneratorsAsync = function () {
  91894. var promises = new Array();
  91895. var lights = this._babylonScene.lights;
  91896. for (var _i = 0, lights_1 = lights; _i < lights_1.length; _i++) {
  91897. var light = lights_1[_i];
  91898. var generator = light.getShadowGenerator();
  91899. if (generator) {
  91900. promises.push(generator.forceCompilationAsync());
  91901. }
  91902. }
  91903. return Promise.all(promises).then(function () { });
  91904. };
  91905. GLTFLoader.prototype._clear = function () {
  91906. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  91907. var request = _a[_i];
  91908. request.abort();
  91909. }
  91910. this._requests.length = 0;
  91911. if (this._gltf && this._gltf.images) {
  91912. for (var _b = 0, _c = this._gltf.images; _b < _c.length; _b++) {
  91913. var image = _c[_b];
  91914. if (image._objectURL) {
  91915. image._objectURL.then(function (value) {
  91916. URL.revokeObjectURL(value);
  91917. });
  91918. image._objectURL = undefined;
  91919. }
  91920. }
  91921. }
  91922. delete this._gltf;
  91923. delete this._babylonScene;
  91924. this._completePromises.length = 0;
  91925. this._extensions = {};
  91926. delete this._rootBabylonMesh;
  91927. delete this._progressCallback;
  91928. this.onMeshLoadedObservable.clear();
  91929. this.onTextureLoadedObservable.clear();
  91930. this.onMaterialLoadedObservable.clear();
  91931. };
  91932. GLTFLoader.prototype._applyExtensions = function (actionAsync) {
  91933. for (var _i = 0, _a = GLTFLoader._Names; _i < _a.length; _i++) {
  91934. var name_2 = _a[_i];
  91935. var extension = this._extensions[name_2];
  91936. if (extension.enabled) {
  91937. var promise = actionAsync(extension);
  91938. if (promise) {
  91939. return promise;
  91940. }
  91941. }
  91942. }
  91943. return null;
  91944. };
  91945. GLTFLoader._Names = new Array();
  91946. GLTFLoader._Factories = {};
  91947. return GLTFLoader;
  91948. }());
  91949. GLTF2.GLTFLoader = GLTFLoader;
  91950. BABYLON.GLTFFileLoader.CreateGLTFLoaderV2 = function () { return new GLTFLoader(); };
  91951. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  91952. })(BABYLON || (BABYLON = {}));
  91953. //# sourceMappingURL=babylon.glTFLoader.js.map
  91954. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  91955. var BABYLON;
  91956. (function (BABYLON) {
  91957. var GLTF2;
  91958. (function (GLTF2) {
  91959. var GLTFLoaderExtension = /** @class */ (function () {
  91960. function GLTFLoaderExtension(loader) {
  91961. this.enabled = true;
  91962. this._loader = loader;
  91963. }
  91964. // #region Overridable Methods
  91965. /** Override this method to modify the default behavior for loading scenes. */
  91966. GLTFLoaderExtension.prototype._loadSceneAsync = function (context, node) { return null; };
  91967. /** Override this method to modify the default behavior for loading nodes. */
  91968. GLTFLoaderExtension.prototype._loadNodeAsync = function (context, node) { return null; };
  91969. /** Override this method to modify the default behavior for loading materials. */
  91970. GLTFLoaderExtension.prototype._loadMaterialAsync = function (context, material, babylonMesh) { return null; };
  91971. /** Override this method to modify the default behavior for loading uris. */
  91972. GLTFLoaderExtension.prototype._loadUriAsync = function (context, uri) { return null; };
  91973. // #endregion
  91974. /** Helper method called by a loader extension to load an glTF extension. */
  91975. GLTFLoaderExtension.prototype._loadExtensionAsync = function (context, property, actionAsync) {
  91976. var _this = this;
  91977. if (!property.extensions) {
  91978. return null;
  91979. }
  91980. var extensions = property.extensions;
  91981. var extension = extensions[this.name];
  91982. if (!extension) {
  91983. return null;
  91984. }
  91985. // Clear out the extension before executing the action to avoid recursing into the same property.
  91986. delete extensions[this.name];
  91987. return actionAsync(context + "/extensions/" + this.name, extension).then(function () {
  91988. // Restore the extension after completing the action.
  91989. extensions[_this.name] = extension;
  91990. });
  91991. };
  91992. /** Helper method called by the loader to allow extensions to override loading scenes. */
  91993. GLTFLoaderExtension._LoadSceneAsync = function (loader, context, scene) {
  91994. return loader._applyExtensions(function (extension) { return extension._loadSceneAsync(context, scene); });
  91995. };
  91996. /** Helper method called by the loader to allow extensions to override loading nodes. */
  91997. GLTFLoaderExtension._LoadNodeAsync = function (loader, context, node) {
  91998. return loader._applyExtensions(function (extension) { return extension._loadNodeAsync(context, node); });
  91999. };
  92000. /** Helper method called by the loader to allow extensions to override loading materials. */
  92001. GLTFLoaderExtension._LoadMaterialAsync = function (loader, context, material, babylonMesh) {
  92002. return loader._applyExtensions(function (extension) { return extension._loadMaterialAsync(context, material, babylonMesh); });
  92003. };
  92004. /** Helper method called by the loader to allow extensions to override loading uris. */
  92005. GLTFLoaderExtension._LoadUriAsync = function (loader, context, uri) {
  92006. return loader._applyExtensions(function (extension) { return extension._loadUriAsync(context, uri); });
  92007. };
  92008. return GLTFLoaderExtension;
  92009. }());
  92010. GLTF2.GLTFLoaderExtension = GLTFLoaderExtension;
  92011. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  92012. })(BABYLON || (BABYLON = {}));
  92013. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  92014. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  92015. var BABYLON;
  92016. (function (BABYLON) {
  92017. var GLTF2;
  92018. (function (GLTF2) {
  92019. var Extensions;
  92020. (function (Extensions) {
  92021. // https://github.com/sbtron/glTF/tree/MSFT_lod/extensions/Vendor/MSFT_lod
  92022. var NAME = "MSFT_lod";
  92023. var MSFT_lod = /** @class */ (function (_super) {
  92024. __extends(MSFT_lod, _super);
  92025. function MSFT_lod() {
  92026. var _this = _super !== null && _super.apply(this, arguments) || this;
  92027. _this.name = NAME;
  92028. /**
  92029. * Maximum number of LODs to load, starting from the lowest LOD.
  92030. */
  92031. _this.maxLODsToLoad = Number.MAX_VALUE;
  92032. _this._loadingNodeLOD = null;
  92033. _this._loadNodeSignals = {};
  92034. _this._loadingMaterialLOD = null;
  92035. _this._loadMaterialSignals = {};
  92036. return _this;
  92037. }
  92038. MSFT_lod.prototype._loadNodeAsync = function (context, node) {
  92039. var _this = this;
  92040. return this._loadExtensionAsync(context, node, function (context, extension) {
  92041. var firstPromise;
  92042. var nodeLODs = _this._getLODs(context, node, _this._loader._gltf.nodes, extension.ids);
  92043. var _loop_1 = function (indexLOD) {
  92044. var nodeLOD = nodeLODs[indexLOD];
  92045. if (indexLOD !== 0) {
  92046. _this._loadingNodeLOD = nodeLOD;
  92047. _this._loadNodeSignals[nodeLOD._index] = new BABYLON.Deferred();
  92048. }
  92049. var promise = _this._loader._loadNodeAsync("#/nodes/" + nodeLOD._index, nodeLOD).then(function () {
  92050. if (indexLOD !== 0) {
  92051. var previousNodeLOD = nodeLODs[indexLOD - 1];
  92052. previousNodeLOD._babylonMesh.setEnabled(false);
  92053. }
  92054. if (indexLOD !== nodeLODs.length - 1) {
  92055. var nodeIndex = nodeLODs[indexLOD + 1]._index;
  92056. _this._loadNodeSignals[nodeIndex].resolve();
  92057. delete _this._loadNodeSignals[nodeIndex];
  92058. }
  92059. });
  92060. if (indexLOD === 0) {
  92061. firstPromise = promise;
  92062. }
  92063. else {
  92064. _this._loader._completePromises.push(promise);
  92065. _this._loadingNodeLOD = null;
  92066. }
  92067. };
  92068. for (var indexLOD = 0; indexLOD < nodeLODs.length; indexLOD++) {
  92069. _loop_1(indexLOD);
  92070. }
  92071. return firstPromise;
  92072. });
  92073. };
  92074. MSFT_lod.prototype._loadMaterialAsync = function (context, material, babylonMesh) {
  92075. var _this = this;
  92076. // Don't load material LODs if already loading a node LOD.
  92077. if (this._loadingNodeLOD) {
  92078. return null;
  92079. }
  92080. return this._loadExtensionAsync(context, material, function (context, extension) {
  92081. var firstPromise;
  92082. var materialLODs = _this._getLODs(context, material, _this._loader._gltf.materials, extension.ids);
  92083. var _loop_2 = function (indexLOD) {
  92084. var materialLOD = materialLODs[indexLOD];
  92085. if (indexLOD !== 0) {
  92086. _this._loadingMaterialLOD = materialLOD;
  92087. _this._loadMaterialSignals[materialLOD._index] = new BABYLON.Deferred();
  92088. }
  92089. var promise = _this._loader._loadMaterialAsync("#/materials/" + materialLOD._index, materialLOD, babylonMesh).then(function () {
  92090. if (indexLOD !== materialLODs.length - 1) {
  92091. var materialIndex = materialLODs[indexLOD + 1]._index;
  92092. _this._loadMaterialSignals[materialIndex].resolve();
  92093. delete _this._loadMaterialSignals[materialIndex];
  92094. }
  92095. });
  92096. if (indexLOD === 0) {
  92097. firstPromise = promise;
  92098. }
  92099. else {
  92100. _this._loader._completePromises.push(promise);
  92101. _this._loadingMaterialLOD = null;
  92102. }
  92103. };
  92104. for (var indexLOD = 0; indexLOD < materialLODs.length; indexLOD++) {
  92105. _loop_2(indexLOD);
  92106. }
  92107. return firstPromise;
  92108. });
  92109. };
  92110. MSFT_lod.prototype._loadUriAsync = function (context, uri) {
  92111. var _this = this;
  92112. // Defer the loading of uris if loading a material or node LOD.
  92113. if (this._loadingMaterialLOD) {
  92114. var index = this._loadingMaterialLOD._index;
  92115. return this._loadMaterialSignals[index].promise.then(function () {
  92116. return _this._loader._loadUriAsync(context, uri);
  92117. });
  92118. }
  92119. else if (this._loadingNodeLOD) {
  92120. var index = this._loadingNodeLOD._index;
  92121. return this._loadNodeSignals[index].promise.then(function () {
  92122. return _this._loader._loadUriAsync(context, uri);
  92123. });
  92124. }
  92125. return null;
  92126. };
  92127. /**
  92128. * Gets an array of LOD properties from lowest to highest.
  92129. */
  92130. MSFT_lod.prototype._getLODs = function (context, property, array, ids) {
  92131. if (this.maxLODsToLoad <= 0) {
  92132. throw new Error("maxLODsToLoad must be greater than zero");
  92133. }
  92134. var properties = new Array();
  92135. for (var i = ids.length - 1; i >= 0; i--) {
  92136. properties.push(GLTF2.GLTFLoader._GetProperty(context + "/ids/" + ids[i], array, ids[i]));
  92137. if (properties.length === this.maxLODsToLoad) {
  92138. return properties;
  92139. }
  92140. }
  92141. properties.push(property);
  92142. return properties;
  92143. };
  92144. return MSFT_lod;
  92145. }(GLTF2.GLTFLoaderExtension));
  92146. Extensions.MSFT_lod = MSFT_lod;
  92147. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new MSFT_lod(loader); });
  92148. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  92149. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  92150. })(BABYLON || (BABYLON = {}));
  92151. //# sourceMappingURL=MSFT_lod.js.map
  92152. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  92153. var BABYLON;
  92154. (function (BABYLON) {
  92155. var GLTF2;
  92156. (function (GLTF2) {
  92157. var Extensions;
  92158. (function (Extensions) {
  92159. // https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_pbrSpecularGlossiness
  92160. var NAME = "KHR_materials_pbrSpecularGlossiness";
  92161. var KHR_materials_pbrSpecularGlossiness = /** @class */ (function (_super) {
  92162. __extends(KHR_materials_pbrSpecularGlossiness, _super);
  92163. function KHR_materials_pbrSpecularGlossiness() {
  92164. var _this = _super !== null && _super.apply(this, arguments) || this;
  92165. _this.name = NAME;
  92166. return _this;
  92167. }
  92168. KHR_materials_pbrSpecularGlossiness.prototype._loadMaterialAsync = function (context, material, babylonMesh) {
  92169. var _this = this;
  92170. return this._loadExtensionAsync(context, material, function (context, extension) {
  92171. material._babylonMeshes = material._babylonMeshes || [];
  92172. material._babylonMeshes.push(babylonMesh);
  92173. if (material._loaded) {
  92174. babylonMesh.material = material._babylonMaterial;
  92175. return material._loaded;
  92176. }
  92177. var promises = new Array();
  92178. var babylonMaterial = _this._loader._createMaterial(material);
  92179. material._babylonMaterial = babylonMaterial;
  92180. promises.push(_this._loader._loadMaterialBasePropertiesAsync(context, material));
  92181. promises.push(_this._loadSpecularGlossinessPropertiesAsync(_this._loader, context, material, extension));
  92182. _this._loader.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  92183. babylonMesh.material = babylonMaterial;
  92184. return (material._loaded = Promise.all(promises).then(function () { }));
  92185. });
  92186. };
  92187. KHR_materials_pbrSpecularGlossiness.prototype._loadSpecularGlossinessPropertiesAsync = function (loader, context, material, properties) {
  92188. var promises = new Array();
  92189. var babylonMaterial = material._babylonMaterial;
  92190. if (properties.diffuseFactor) {
  92191. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.diffuseFactor);
  92192. babylonMaterial.alpha = properties.diffuseFactor[3];
  92193. }
  92194. else {
  92195. babylonMaterial.albedoColor = BABYLON.Color3.White();
  92196. }
  92197. babylonMaterial.reflectivityColor = properties.specularFactor ? BABYLON.Color3.FromArray(properties.specularFactor) : BABYLON.Color3.White();
  92198. babylonMaterial.microSurface = properties.glossinessFactor == undefined ? 1 : properties.glossinessFactor;
  92199. if (properties.diffuseTexture) {
  92200. promises.push(loader._loadTextureAsync(context + "/diffuseTexture", properties.diffuseTexture, function (texture) {
  92201. babylonMaterial.albedoTexture = texture;
  92202. }));
  92203. }
  92204. if (properties.specularGlossinessTexture) {
  92205. promises.push(loader._loadTextureAsync(context + "/specularGlossinessTexture", properties.specularGlossinessTexture, function (texture) {
  92206. babylonMaterial.reflectivityTexture = texture;
  92207. }));
  92208. babylonMaterial.reflectivityTexture.hasAlpha = true;
  92209. babylonMaterial.useMicroSurfaceFromReflectivityMapAlpha = true;
  92210. }
  92211. loader._loadMaterialAlphaProperties(context, material);
  92212. return Promise.all(promises).then(function () { });
  92213. };
  92214. return KHR_materials_pbrSpecularGlossiness;
  92215. }(GLTF2.GLTFLoaderExtension));
  92216. Extensions.KHR_materials_pbrSpecularGlossiness = KHR_materials_pbrSpecularGlossiness;
  92217. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_materials_pbrSpecularGlossiness(loader); });
  92218. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  92219. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  92220. })(BABYLON || (BABYLON = {}));
  92221. //# sourceMappingURL=KHR_materials_pbrSpecularGlossiness.js.map
  92222. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  92223. var BABYLON;
  92224. (function (BABYLON) {
  92225. var GLTF2;
  92226. (function (GLTF2) {
  92227. var Extensions;
  92228. (function (Extensions) {
  92229. // https://github.com/MiiBond/glTF/tree/khr_lights_v1/extensions/Khronos/KHR_lights
  92230. var NAME = "KHR_lights";
  92231. var LightType;
  92232. (function (LightType) {
  92233. LightType["AMBIENT"] = "ambient";
  92234. LightType["DIRECTIONAL"] = "directional";
  92235. LightType["POINT"] = "point";
  92236. LightType["SPOT"] = "spot";
  92237. })(LightType || (LightType = {}));
  92238. var KHR_lights = /** @class */ (function (_super) {
  92239. __extends(KHR_lights, _super);
  92240. function KHR_lights() {
  92241. var _this = _super !== null && _super.apply(this, arguments) || this;
  92242. _this.name = NAME;
  92243. return _this;
  92244. }
  92245. KHR_lights.prototype._loadSceneAsync = function (context, scene) {
  92246. var _this = this;
  92247. return this._loadExtensionAsync(context, scene, function (context, extension) {
  92248. var promise = _this._loader._loadSceneAsync(context, scene);
  92249. var light = GLTF2.GLTFLoader._GetProperty(context, _this._lights, extension.light);
  92250. if (light.type !== LightType.AMBIENT) {
  92251. throw new Error(context + ": Only ambient lights are allowed on a scene");
  92252. }
  92253. _this._loader._babylonScene.ambientColor = light.color ? BABYLON.Color3.FromArray(light.color) : BABYLON.Color3.Black();
  92254. return promise;
  92255. });
  92256. };
  92257. KHR_lights.prototype._loadNodeAsync = function (context, node) {
  92258. var _this = this;
  92259. return this._loadExtensionAsync(context, node, function (context, extension) {
  92260. var promise = _this._loader._loadNodeAsync(context, node);
  92261. var babylonLight;
  92262. var light = GLTF2.GLTFLoader._GetProperty(context, _this._lights, extension.light);
  92263. var name = node._babylonMesh.name;
  92264. switch (light.type) {
  92265. case LightType.AMBIENT: {
  92266. throw new Error(context + ": Ambient lights are not allowed on a node");
  92267. }
  92268. case LightType.DIRECTIONAL: {
  92269. babylonLight = new BABYLON.DirectionalLight(name, BABYLON.Vector3.Forward(), _this._loader._babylonScene);
  92270. break;
  92271. }
  92272. case LightType.POINT: {
  92273. babylonLight = new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), _this._loader._babylonScene);
  92274. break;
  92275. }
  92276. case LightType.SPOT: {
  92277. var spotLight = light;
  92278. // TODO: support inner and outer cone angles
  92279. //const innerConeAngle = spotLight.innerConeAngle || 0;
  92280. var outerConeAngle = spotLight.outerConeAngle || Math.PI / 4;
  92281. babylonLight = new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward(), outerConeAngle, 2, _this._loader._babylonScene);
  92282. break;
  92283. }
  92284. default: {
  92285. throw new Error(context + ": Invalid light type " + light.type);
  92286. }
  92287. }
  92288. babylonLight.diffuse = light.color ? BABYLON.Color3.FromArray(light.color) : BABYLON.Color3.White();
  92289. babylonLight.intensity = light.intensity == undefined ? 1 : light.intensity;
  92290. babylonLight.parent = node._babylonMesh;
  92291. return promise;
  92292. });
  92293. };
  92294. Object.defineProperty(KHR_lights.prototype, "_lights", {
  92295. get: function () {
  92296. var extensions = this._loader._gltf.extensions;
  92297. if (!extensions || !extensions[this.name]) {
  92298. throw new Error("#/extensions: " + this.name + " not found");
  92299. }
  92300. var extension = extensions[this.name];
  92301. return extension.lights;
  92302. },
  92303. enumerable: true,
  92304. configurable: true
  92305. });
  92306. return KHR_lights;
  92307. }(GLTF2.GLTFLoaderExtension));
  92308. Extensions.KHR_lights = KHR_lights;
  92309. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_lights(loader); });
  92310. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  92311. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  92312. })(BABYLON || (BABYLON = {}));
  92313. //# sourceMappingURL=KHR_lights.js.map
  92314. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  92315. globalObject["BABYLON"] = BABYLON;
  92316. var EffectFallbacks = BABYLON.EffectFallbacks;var EffectCreationOptions = BABYLON.EffectCreationOptions;var Effect = BABYLON.Effect;var KeyboardEventTypes = BABYLON.KeyboardEventTypes;var KeyboardInfo = BABYLON.KeyboardInfo;var KeyboardInfoPre = BABYLON.KeyboardInfoPre;var PointerEventTypes = BABYLON.PointerEventTypes;var PointerInfoBase = BABYLON.PointerInfoBase;var PointerInfoPre = BABYLON.PointerInfoPre;var PointerInfo = BABYLON.PointerInfo;var Color3 = BABYLON.Color3;var Color4 = BABYLON.Color4;var Vector2 = BABYLON.Vector2;var Vector3 = BABYLON.Vector3;var Vector4 = BABYLON.Vector4;var Size = BABYLON.Size;var Quaternion = BABYLON.Quaternion;var Matrix = BABYLON.Matrix;var Plane = BABYLON.Plane;var Viewport = BABYLON.Viewport;var Frustum = BABYLON.Frustum;var Axis = BABYLON.Axis;var BezierCurve = BABYLON.BezierCurve;var Angle = BABYLON.Angle;var Arc2 = BABYLON.Arc2;var Path2 = BABYLON.Path2;var Path3D = BABYLON.Path3D;var Curve3 = BABYLON.Curve3;var PositionNormalVertex = BABYLON.PositionNormalVertex;var PositionNormalTextureVertex = BABYLON.PositionNormalTextureVertex;var Tmp = BABYLON.Tmp;var Scalar = BABYLON.Scalar;var expandToProperty = BABYLON.expandToProperty;var serialize = BABYLON.serialize;var serializeAsTexture = BABYLON.serializeAsTexture;var serializeAsColor3 = BABYLON.serializeAsColor3;var serializeAsFresnelParameters = BABYLON.serializeAsFresnelParameters;var serializeAsVector2 = BABYLON.serializeAsVector2;var serializeAsVector3 = BABYLON.serializeAsVector3;var serializeAsMeshReference = BABYLON.serializeAsMeshReference;var serializeAsColorCurves = BABYLON.serializeAsColorCurves;var serializeAsColor4 = BABYLON.serializeAsColor4;var serializeAsImageProcessingConfiguration = BABYLON.serializeAsImageProcessingConfiguration;var serializeAsQuaternion = BABYLON.serializeAsQuaternion;var SerializationHelper = BABYLON.SerializationHelper;var Deferred = BABYLON.Deferred;var EventState = BABYLON.EventState;var Observer = BABYLON.Observer;var MultiObserver = BABYLON.MultiObserver;var Observable = BABYLON.Observable;var SmartArray = BABYLON.SmartArray;var SmartArrayNoDuplicate = BABYLON.SmartArrayNoDuplicate;var LoadFileError = BABYLON.LoadFileError;var RetryStrategy = BABYLON.RetryStrategy;var Tools = BABYLON.Tools;var PerfCounter = BABYLON.PerfCounter;var className = BABYLON.className;var AsyncLoop = BABYLON.AsyncLoop;var PromisePolyfill = BABYLON.PromisePolyfill;var _AlphaState = BABYLON._AlphaState;var _DepthCullingState = BABYLON._DepthCullingState;var _StencilState = BABYLON._StencilState;var InstancingAttributeInfo = BABYLON.InstancingAttributeInfo;var RenderTargetCreationOptions = BABYLON.RenderTargetCreationOptions;var EngineCapabilities = BABYLON.EngineCapabilities;var Engine = BABYLON.Engine;var Node = BABYLON.Node;var BoundingSphere = BABYLON.BoundingSphere;var BoundingBox = BABYLON.BoundingBox;var BoundingInfo = BABYLON.BoundingInfo;var TransformNode = BABYLON.TransformNode;var AbstractMesh = BABYLON.AbstractMesh;var Light = BABYLON.Light;var Camera = BABYLON.Camera;var RenderingManager = BABYLON.RenderingManager;var RenderingGroup = BABYLON.RenderingGroup;var RenderingGroupInfo = BABYLON.RenderingGroupInfo;var Scene = BABYLON.Scene;var KeepAssets = BABYLON.KeepAssets;var AssetContainer = BABYLON.AssetContainer;var Buffer = BABYLON.Buffer;var VertexBuffer = BABYLON.VertexBuffer;var DummyInternalTextureTracker = BABYLON.DummyInternalTextureTracker;var InternalTexture = BABYLON.InternalTexture;var BaseTexture = BABYLON.BaseTexture;var Texture = BABYLON.Texture;var _InstancesBatch = BABYLON._InstancesBatch;var Mesh = BABYLON.Mesh;var BaseSubMesh = BABYLON.BaseSubMesh;var SubMesh = BABYLON.SubMesh;var MaterialDefines = BABYLON.MaterialDefines;var Material = BABYLON.Material;var UniformBuffer = BABYLON.UniformBuffer;var VertexData = BABYLON.VertexData;var Geometry = BABYLON.Geometry;var _PrimitiveGeometry = BABYLON._PrimitiveGeometry;var RibbonGeometry = BABYLON.RibbonGeometry;var BoxGeometry = BABYLON.BoxGeometry;var SphereGeometry = BABYLON.SphereGeometry;var DiscGeometry = BABYLON.DiscGeometry;var CylinderGeometry = BABYLON.CylinderGeometry;var TorusGeometry = BABYLON.TorusGeometry;var GroundGeometry = BABYLON.GroundGeometry;var TiledGroundGeometry = BABYLON.TiledGroundGeometry;var PlaneGeometry = BABYLON.PlaneGeometry;var TorusKnotGeometry = BABYLON.TorusKnotGeometry;var PostProcessManager = BABYLON.PostProcessManager;var PerformanceMonitor = BABYLON.PerformanceMonitor;var RollingAverage = BABYLON.RollingAverage;var ImageProcessingConfiguration = BABYLON.ImageProcessingConfiguration;var ColorGradingTexture = BABYLON.ColorGradingTexture;var ColorCurves = BABYLON.ColorCurves;var MaterialHelper = BABYLON.MaterialHelper;var PushMaterial = BABYLON.PushMaterial;var StandardMaterialDefines = BABYLON.StandardMaterialDefines;var StandardMaterial = BABYLON.StandardMaterial;var PBRBaseMaterial = BABYLON.PBRBaseMaterial;var PBRBaseSimpleMaterial = BABYLON.PBRBaseSimpleMaterial;var PBRMaterial = BABYLON.PBRMaterial;var PBRMetallicRoughnessMaterial = BABYLON.PBRMetallicRoughnessMaterial;var PBRSpecularGlossinessMaterial = BABYLON.PBRSpecularGlossinessMaterial;var CameraInputsManager = BABYLON.CameraInputsManager;var TargetCamera = BABYLON.TargetCamera;var FreeCameraMouseInput = BABYLON.FreeCameraMouseInput;var FreeCameraKeyboardMoveInput = BABYLON.FreeCameraKeyboardMoveInput;var FreeCameraInputsManager = BABYLON.FreeCameraInputsManager;var FreeCamera = BABYLON.FreeCamera;var ArcRotateCameraKeyboardMoveInput = BABYLON.ArcRotateCameraKeyboardMoveInput;var ArcRotateCameraMouseWheelInput = BABYLON.ArcRotateCameraMouseWheelInput;var ArcRotateCameraPointersInput = BABYLON.ArcRotateCameraPointersInput;var ArcRotateCameraInputsManager = BABYLON.ArcRotateCameraInputsManager;var ArcRotateCamera = BABYLON.ArcRotateCamera;var HemisphericLight = BABYLON.HemisphericLight;var ShadowLight = BABYLON.ShadowLight;var PointLight = BABYLON.PointLight;var DirectionalLight = BABYLON.DirectionalLight;var SpotLight = BABYLON.SpotLight;var AnimationRange = BABYLON.AnimationRange;var AnimationEvent = BABYLON.AnimationEvent;var PathCursor = BABYLON.PathCursor;var Animation = BABYLON.Animation;var TargetedAnimation = BABYLON.TargetedAnimation;var AnimationGroup = BABYLON.AnimationGroup;var RuntimeAnimation = BABYLON.RuntimeAnimation;var Animatable = BABYLON.Animatable;var EasingFunction = BABYLON.EasingFunction;var CircleEase = BABYLON.CircleEase;var BackEase = BABYLON.BackEase;var BounceEase = BABYLON.BounceEase;var CubicEase = BABYLON.CubicEase;var ElasticEase = BABYLON.ElasticEase;var ExponentialEase = BABYLON.ExponentialEase;var PowerEase = BABYLON.PowerEase;var QuadraticEase = BABYLON.QuadraticEase;var QuarticEase = BABYLON.QuarticEase;var QuinticEase = BABYLON.QuinticEase;var SineEase = BABYLON.SineEase;var BezierCurveEase = BABYLON.BezierCurveEase;var Condition = BABYLON.Condition;var ValueCondition = BABYLON.ValueCondition;var PredicateCondition = BABYLON.PredicateCondition;var StateCondition = BABYLON.StateCondition;var Action = BABYLON.Action;var ActionEvent = BABYLON.ActionEvent;var ActionManager = BABYLON.ActionManager;var InterpolateValueAction = BABYLON.InterpolateValueAction;var SwitchBooleanAction = BABYLON.SwitchBooleanAction;var SetStateAction = BABYLON.SetStateAction;var SetValueAction = BABYLON.SetValueAction;var IncrementValueAction = BABYLON.IncrementValueAction;var PlayAnimationAction = BABYLON.PlayAnimationAction;var StopAnimationAction = BABYLON.StopAnimationAction;var DoNothingAction = BABYLON.DoNothingAction;var CombineAction = BABYLON.CombineAction;var ExecuteCodeAction = BABYLON.ExecuteCodeAction;var SetParentAction = BABYLON.SetParentAction;var PlaySoundAction = BABYLON.PlaySoundAction;var StopSoundAction = BABYLON.StopSoundAction;var SpriteManager = BABYLON.SpriteManager;var Sprite = BABYLON.Sprite;var IntersectionInfo = BABYLON.IntersectionInfo;var PickingInfo = BABYLON.PickingInfo;var Ray = BABYLON.Ray;var Collider = BABYLON.Collider;var CollisionCoordinatorWorker = BABYLON.CollisionCoordinatorWorker;var CollisionCoordinatorLegacy = BABYLON.CollisionCoordinatorLegacy;var Particle = BABYLON.Particle;var ParticleSystem = BABYLON.ParticleSystem;var BoxParticleEmitter = BABYLON.BoxParticleEmitter;var ConeParticleEmitter = BABYLON.ConeParticleEmitter;var SphereParticleEmitter = BABYLON.SphereParticleEmitter;var SphereDirectedParticleEmitter = BABYLON.SphereDirectedParticleEmitter;var SolidParticle = BABYLON.SolidParticle;var ModelShape = BABYLON.ModelShape;var DepthSortedParticle = BABYLON.DepthSortedParticle;var SolidParticleSystem = BABYLON.SolidParticleSystem;var ShaderMaterial = BABYLON.ShaderMaterial;var GroundMesh = BABYLON.GroundMesh;var InstancedMesh = BABYLON.InstancedMesh;var LinesMesh = BABYLON.LinesMesh;var MeshBuilder = BABYLON.MeshBuilder;var AudioEngine = BABYLON.AudioEngine;var Sound = BABYLON.Sound;var SoundTrack = BABYLON.SoundTrack;var Analyser = BABYLON.Analyser;var CubeTexture = BABYLON.CubeTexture;var RenderTargetTexture = BABYLON.RenderTargetTexture;var MultiRenderTarget = BABYLON.MultiRenderTarget;var MirrorTexture = BABYLON.MirrorTexture;var RefractionTexture = BABYLON.RefractionTexture;var DynamicTexture = BABYLON.DynamicTexture;var VideoTexture = BABYLON.VideoTexture;var RawTexture = BABYLON.RawTexture;var PostProcess = BABYLON.PostProcess;var PassPostProcess = BABYLON.PassPostProcess;var ShadowGenerator = BABYLON.ShadowGenerator;var DefaultLoadingScreen = BABYLON.DefaultLoadingScreen;var SceneLoaderProgressEvent = BABYLON.SceneLoaderProgressEvent;var SceneLoader = BABYLON.SceneLoader;var FilesInput = BABYLON.FilesInput;var StringDictionary = BABYLON.StringDictionary;var Tags = BABYLON.Tags;var AndOrNotEvaluator = BABYLON.AndOrNotEvaluator;var Database = BABYLON.Database;var FresnelParameters = BABYLON.FresnelParameters;var MultiMaterial = BABYLON.MultiMaterial;var FreeCameraTouchInput = BABYLON.FreeCameraTouchInput;var TouchCamera = BABYLON.TouchCamera;var ProceduralTexture = BABYLON.ProceduralTexture;var CustomProceduralTexture = BABYLON.CustomProceduralTexture;var FreeCameraGamepadInput = BABYLON.FreeCameraGamepadInput;var ArcRotateCameraGamepadInput = BABYLON.ArcRotateCameraGamepadInput;var GamepadManager = BABYLON.GamepadManager;var StickValues = BABYLON.StickValues;var Gamepad = BABYLON.Gamepad;var GenericPad = BABYLON.GenericPad;var Xbox360Pad = BABYLON.Xbox360Pad;var PoseEnabledControllerHelper = BABYLON.PoseEnabledControllerHelper;var PoseEnabledController = BABYLON.PoseEnabledController;var WebVRController = BABYLON.WebVRController;var OculusTouchController = BABYLON.OculusTouchController;var ViveController = BABYLON.ViveController;var GenericController = BABYLON.GenericController;var WindowsMotionController = BABYLON.WindowsMotionController;var GearVRController = BABYLON.GearVRController;var FollowCamera = BABYLON.FollowCamera;var ArcFollowCamera = BABYLON.ArcFollowCamera;var UniversalCamera = BABYLON.UniversalCamera;var GamepadCamera = BABYLON.GamepadCamera;var PostProcessRenderPipelineManager = BABYLON.PostProcessRenderPipelineManager;var PostProcessRenderEffect = BABYLON.PostProcessRenderEffect;var PostProcessRenderPipeline = BABYLON.PostProcessRenderPipeline;var DepthRenderer = BABYLON.DepthRenderer;var SSAORenderingPipeline = BABYLON.SSAORenderingPipeline;var SSAO2RenderingPipeline = BABYLON.SSAO2RenderingPipeline;var LensRenderingPipeline = BABYLON.LensRenderingPipeline;var StandardRenderingPipeline = BABYLON.StandardRenderingPipeline;var FxaaPostProcess = BABYLON.FxaaPostProcess;var CircleOfConfusionPostProcess = BABYLON.CircleOfConfusionPostProcess;var DepthOfFieldMergePostProcess = BABYLON.DepthOfFieldMergePostProcess;var DepthOfFieldEffect = BABYLON.DepthOfFieldEffect;var DefaultRenderingPipeline = BABYLON.DefaultRenderingPipeline;var GeometryBufferRenderer = BABYLON.GeometryBufferRenderer;var RefractionPostProcess = BABYLON.RefractionPostProcess;var BlackAndWhitePostProcess = BABYLON.BlackAndWhitePostProcess;var ConvolutionPostProcess = BABYLON.ConvolutionPostProcess;var FilterPostProcess = BABYLON.FilterPostProcess;var VolumetricLightScatteringPostProcess = BABYLON.VolumetricLightScatteringPostProcess;var ColorCorrectionPostProcess = BABYLON.ColorCorrectionPostProcess;var TonemapPostProcess = BABYLON.TonemapPostProcess;var DisplayPassPostProcess = BABYLON.DisplayPassPostProcess;var HighlightsPostProcess = BABYLON.HighlightsPostProcess;var ImageProcessingPostProcess = BABYLON.ImageProcessingPostProcess;var BlurPostProcess = BABYLON.BlurPostProcess;var Bone = BABYLON.Bone;var BoneIKController = BABYLON.BoneIKController;var BoneLookController = BABYLON.BoneLookController;var Skeleton = BABYLON.Skeleton;var SphericalPolynomial = BABYLON.SphericalPolynomial;var SphericalHarmonics = BABYLON.SphericalHarmonics;var CubeMapToSphericalPolynomialTools = BABYLON.CubeMapToSphericalPolynomialTools;var PanoramaToCubeMapTools = BABYLON.PanoramaToCubeMapTools;var HDRTools = BABYLON.HDRTools;var HDRCubeTexture = BABYLON.HDRCubeTexture;var Polygon = BABYLON.Polygon;var PolygonMeshBuilder = BABYLON.PolygonMeshBuilder;var CSG = BABYLON.CSG;var LensFlare = BABYLON.LensFlare;var LensFlareSystem = BABYLON.LensFlareSystem;var PhysicsJoint = BABYLON.PhysicsJoint;var DistanceJoint = BABYLON.DistanceJoint;var MotorEnabledJoint = BABYLON.MotorEnabledJoint;var HingeJoint = BABYLON.HingeJoint;var Hinge2Joint = BABYLON.Hinge2Joint;var PhysicsImpostor = BABYLON.PhysicsImpostor;var PhysicsEngine = BABYLON.PhysicsEngine;var PhysicsHelper = BABYLON.PhysicsHelper;var PhysicsRadialExplosionEvent = BABYLON.PhysicsRadialExplosionEvent;var PhysicsGravitationalFieldEvent = BABYLON.PhysicsGravitationalFieldEvent;var PhysicsUpdraftEvent = BABYLON.PhysicsUpdraftEvent;var PhysicsVortexEvent = BABYLON.PhysicsVortexEvent;var CannonJSPlugin = BABYLON.CannonJSPlugin;var OimoJSPlugin = BABYLON.OimoJSPlugin;var TGATools = BABYLON.TGATools;var DDSTools = BABYLON.DDSTools;var KhronosTextureContainer = BABYLON.KhronosTextureContainer;var Debug = BABYLON.Debug;var RayHelper = BABYLON.RayHelper;var DebugLayer = BABYLON.DebugLayer;var BoundingBoxRenderer = BABYLON.BoundingBoxRenderer;var MorphTarget = BABYLON.MorphTarget;var MorphTargetManager = BABYLON.MorphTargetManager;var Octree = BABYLON.Octree;var OctreeBlock = BABYLON.OctreeBlock;var VRDistortionCorrectionPostProcess = BABYLON.VRDistortionCorrectionPostProcess;var AnaglyphPostProcess = BABYLON.AnaglyphPostProcess;var StereoscopicInterlacePostProcess = BABYLON.StereoscopicInterlacePostProcess;var FreeCameraDeviceOrientationInput = BABYLON.FreeCameraDeviceOrientationInput;var ArcRotateCameraVRDeviceOrientationInput = BABYLON.ArcRotateCameraVRDeviceOrientationInput;var VRCameraMetrics = BABYLON.VRCameraMetrics;var WebVRFreeCamera = BABYLON.WebVRFreeCamera;var DeviceOrientationCamera = BABYLON.DeviceOrientationCamera;var VRDeviceOrientationFreeCamera = BABYLON.VRDeviceOrientationFreeCamera;var VRDeviceOrientationGamepadCamera = BABYLON.VRDeviceOrientationGamepadCamera;var VRDeviceOrientationArcRotateCamera = BABYLON.VRDeviceOrientationArcRotateCamera;var AnaglyphFreeCamera = BABYLON.AnaglyphFreeCamera;var AnaglyphArcRotateCamera = BABYLON.AnaglyphArcRotateCamera;var AnaglyphGamepadCamera = BABYLON.AnaglyphGamepadCamera;var AnaglyphUniversalCamera = BABYLON.AnaglyphUniversalCamera;var StereoscopicFreeCamera = BABYLON.StereoscopicFreeCamera;var StereoscopicArcRotateCamera = BABYLON.StereoscopicArcRotateCamera;var StereoscopicGamepadCamera = BABYLON.StereoscopicGamepadCamera;var StereoscopicUniversalCamera = BABYLON.StereoscopicUniversalCamera;var VRExperienceHelper = BABYLON.VRExperienceHelper;var VirtualJoystick = BABYLON.VirtualJoystick;var VirtualJoysticksCamera = BABYLON.VirtualJoysticksCamera;var FreeCameraVirtualJoystickInput = BABYLON.FreeCameraVirtualJoystickInput;var SimplificationSettings = BABYLON.SimplificationSettings;var SimplificationQueue = BABYLON.SimplificationQueue;var DecimationTriangle = BABYLON.DecimationTriangle;var DecimationVertex = BABYLON.DecimationVertex;var QuadraticMatrix = BABYLON.QuadraticMatrix;var Reference = BABYLON.Reference;var QuadraticErrorSimplification = BABYLON.QuadraticErrorSimplification;var MeshLODLevel = BABYLON.MeshLODLevel;var SceneOptimization = BABYLON.SceneOptimization;var TextureOptimization = BABYLON.TextureOptimization;var HardwareScalingOptimization = BABYLON.HardwareScalingOptimization;var ShadowsOptimization = BABYLON.ShadowsOptimization;var PostProcessesOptimization = BABYLON.PostProcessesOptimization;var LensFlaresOptimization = BABYLON.LensFlaresOptimization;var CustomOptimization = BABYLON.CustomOptimization;var ParticlesOptimization = BABYLON.ParticlesOptimization;var RenderTargetsOptimization = BABYLON.RenderTargetsOptimization;var MergeMeshesOptimization = BABYLON.MergeMeshesOptimization;var SceneOptimizerOptions = BABYLON.SceneOptimizerOptions;var SceneOptimizer = BABYLON.SceneOptimizer;var OutlineRenderer = BABYLON.OutlineRenderer;var EdgesRenderer = BABYLON.EdgesRenderer;var EffectLayer = BABYLON.EffectLayer;var HighlightLayer = BABYLON.HighlightLayer;var GlowLayer = BABYLON.GlowLayer;var AbstractAssetTask = BABYLON.AbstractAssetTask;var AssetsProgressEvent = BABYLON.AssetsProgressEvent;var MeshAssetTask = BABYLON.MeshAssetTask;var TextFileAssetTask = BABYLON.TextFileAssetTask;var BinaryFileAssetTask = BABYLON.BinaryFileAssetTask;var ImageAssetTask = BABYLON.ImageAssetTask;var TextureAssetTask = BABYLON.TextureAssetTask;var CubeTextureAssetTask = BABYLON.CubeTextureAssetTask;var HDRCubeTextureAssetTask = BABYLON.HDRCubeTextureAssetTask;var AssetsManager = BABYLON.AssetsManager;var SceneSerializer = BABYLON.SceneSerializer;var ReflectionProbe = BABYLON.ReflectionProbe;var Layer = BABYLON.Layer;var TextureTools = BABYLON.TextureTools;var FramingBehavior = BABYLON.FramingBehavior;var BouncingBehavior = BABYLON.BouncingBehavior;var AutoRotationBehavior = BABYLON.AutoRotationBehavior;var EngineInstrumentation = BABYLON.EngineInstrumentation;var SceneInstrumentation = BABYLON.SceneInstrumentation;var _TimeToken = BABYLON._TimeToken;var BackgroundMaterial = BABYLON.BackgroundMaterial;var EnvironmentHelper = BABYLON.EnvironmentHelper;var GridMaterial = BABYLON.GridMaterial;var GLTFFileLoader = BABYLON.GLTFFileLoader;
  92317. export { EffectFallbacks,EffectCreationOptions,Effect,KeyboardEventTypes,KeyboardInfo,KeyboardInfoPre,PointerEventTypes,PointerInfoBase,PointerInfoPre,PointerInfo,Color3,Color4,Vector2,Vector3,Vector4,Size,Quaternion,Matrix,Plane,Viewport,Frustum,Axis,BezierCurve,Angle,Arc2,Path2,Path3D,Curve3,PositionNormalVertex,PositionNormalTextureVertex,Tmp,Scalar,expandToProperty,serialize,serializeAsTexture,serializeAsColor3,serializeAsFresnelParameters,serializeAsVector2,serializeAsVector3,serializeAsMeshReference,serializeAsColorCurves,serializeAsColor4,serializeAsImageProcessingConfiguration,serializeAsQuaternion,SerializationHelper,Deferred,EventState,Observer,MultiObserver,Observable,SmartArray,SmartArrayNoDuplicate,LoadFileError,RetryStrategy,Tools,PerfCounter,className,AsyncLoop,PromisePolyfill,_AlphaState,_DepthCullingState,_StencilState,InstancingAttributeInfo,RenderTargetCreationOptions,EngineCapabilities,Engine,Node,BoundingSphere,BoundingBox,BoundingInfo,TransformNode,AbstractMesh,Light,Camera,RenderingManager,RenderingGroup,RenderingGroupInfo,Scene,KeepAssets,AssetContainer,Buffer,VertexBuffer,DummyInternalTextureTracker,InternalTexture,BaseTexture,Texture,_InstancesBatch,Mesh,BaseSubMesh,SubMesh,MaterialDefines,Material,UniformBuffer,VertexData,Geometry,_PrimitiveGeometry,RibbonGeometry,BoxGeometry,SphereGeometry,DiscGeometry,CylinderGeometry,TorusGeometry,GroundGeometry,TiledGroundGeometry,PlaneGeometry,TorusKnotGeometry,PostProcessManager,PerformanceMonitor,RollingAverage,ImageProcessingConfiguration,ColorGradingTexture,ColorCurves,MaterialHelper,PushMaterial,StandardMaterialDefines,StandardMaterial,PBRBaseMaterial,PBRBaseSimpleMaterial,PBRMaterial,PBRMetallicRoughnessMaterial,PBRSpecularGlossinessMaterial,CameraInputsManager,TargetCamera,FreeCameraMouseInput,FreeCameraKeyboardMoveInput,FreeCameraInputsManager,FreeCamera,ArcRotateCameraKeyboardMoveInput,ArcRotateCameraMouseWheelInput,ArcRotateCameraPointersInput,ArcRotateCameraInputsManager,ArcRotateCamera,HemisphericLight,ShadowLight,PointLight,DirectionalLight,SpotLight,AnimationRange,AnimationEvent,PathCursor,Animation,TargetedAnimation,AnimationGroup,RuntimeAnimation,Animatable,EasingFunction,CircleEase,BackEase,BounceEase,CubicEase,ElasticEase,ExponentialEase,PowerEase,QuadraticEase,QuarticEase,QuinticEase,SineEase,BezierCurveEase,Condition,ValueCondition,PredicateCondition,StateCondition,Action,ActionEvent,ActionManager,InterpolateValueAction,SwitchBooleanAction,SetStateAction,SetValueAction,IncrementValueAction,PlayAnimationAction,StopAnimationAction,DoNothingAction,CombineAction,ExecuteCodeAction,SetParentAction,PlaySoundAction,StopSoundAction,SpriteManager,Sprite,IntersectionInfo,PickingInfo,Ray,Collider,CollisionCoordinatorWorker,CollisionCoordinatorLegacy,Particle,ParticleSystem,BoxParticleEmitter,ConeParticleEmitter,SphereParticleEmitter,SphereDirectedParticleEmitter,SolidParticle,ModelShape,DepthSortedParticle,SolidParticleSystem,ShaderMaterial,GroundMesh,InstancedMesh,LinesMesh,MeshBuilder,AudioEngine,Sound,SoundTrack,Analyser,CubeTexture,RenderTargetTexture,MultiRenderTarget,MirrorTexture,RefractionTexture,DynamicTexture,VideoTexture,RawTexture,PostProcess,PassPostProcess,ShadowGenerator,DefaultLoadingScreen,SceneLoaderProgressEvent,SceneLoader,FilesInput,StringDictionary,Tags,AndOrNotEvaluator,Database,FresnelParameters,MultiMaterial,FreeCameraTouchInput,TouchCamera,ProceduralTexture,CustomProceduralTexture,FreeCameraGamepadInput,ArcRotateCameraGamepadInput,GamepadManager,StickValues,Gamepad,GenericPad,Xbox360Pad,PoseEnabledControllerHelper,PoseEnabledController,WebVRController,OculusTouchController,ViveController,GenericController,WindowsMotionController,GearVRController,FollowCamera,ArcFollowCamera,UniversalCamera,GamepadCamera,PostProcessRenderPipelineManager,PostProcessRenderEffect,PostProcessRenderPipeline,DepthRenderer,SSAORenderingPipeline,SSAO2RenderingPipeline,LensRenderingPipeline,StandardRenderingPipeline,FxaaPostProcess,CircleOfConfusionPostProcess,DepthOfFieldMergePostProcess,DepthOfFieldEffect,DefaultRenderingPipeline,GeometryBufferRenderer,RefractionPostProcess,BlackAndWhitePostProcess,ConvolutionPostProcess,FilterPostProcess,VolumetricLightScatteringPostProcess,ColorCorrectionPostProcess,TonemapPostProcess,DisplayPassPostProcess,HighlightsPostProcess,ImageProcessingPostProcess,BlurPostProcess,Bone,BoneIKController,BoneLookController,Skeleton,SphericalPolynomial,SphericalHarmonics,CubeMapToSphericalPolynomialTools,PanoramaToCubeMapTools,HDRTools,HDRCubeTexture,Polygon,PolygonMeshBuilder,CSG,LensFlare,LensFlareSystem,PhysicsJoint,DistanceJoint,MotorEnabledJoint,HingeJoint,Hinge2Joint,PhysicsImpostor,PhysicsEngine,PhysicsHelper,PhysicsRadialExplosionEvent,PhysicsGravitationalFieldEvent,PhysicsUpdraftEvent,PhysicsVortexEvent,CannonJSPlugin,OimoJSPlugin,TGATools,DDSTools,KhronosTextureContainer,Debug,RayHelper,DebugLayer,BoundingBoxRenderer,MorphTarget,MorphTargetManager,Octree,OctreeBlock,VRDistortionCorrectionPostProcess,AnaglyphPostProcess,StereoscopicInterlacePostProcess,FreeCameraDeviceOrientationInput,ArcRotateCameraVRDeviceOrientationInput,VRCameraMetrics,WebVRFreeCamera,DeviceOrientationCamera,VRDeviceOrientationFreeCamera,VRDeviceOrientationGamepadCamera,VRDeviceOrientationArcRotateCamera,AnaglyphFreeCamera,AnaglyphArcRotateCamera,AnaglyphGamepadCamera,AnaglyphUniversalCamera,StereoscopicFreeCamera,StereoscopicArcRotateCamera,StereoscopicGamepadCamera,StereoscopicUniversalCamera,VRExperienceHelper,VirtualJoystick,VirtualJoysticksCamera,FreeCameraVirtualJoystickInput,SimplificationSettings,SimplificationQueue,DecimationTriangle,DecimationVertex,QuadraticMatrix,Reference,QuadraticErrorSimplification,MeshLODLevel,SceneOptimization,TextureOptimization,HardwareScalingOptimization,ShadowsOptimization,PostProcessesOptimization,LensFlaresOptimization,CustomOptimization,ParticlesOptimization,RenderTargetsOptimization,MergeMeshesOptimization,SceneOptimizerOptions,SceneOptimizer,OutlineRenderer,EdgesRenderer,EffectLayer,HighlightLayer,GlowLayer,AbstractAssetTask,AssetsProgressEvent,MeshAssetTask,TextFileAssetTask,BinaryFileAssetTask,ImageAssetTask,TextureAssetTask,CubeTextureAssetTask,HDRCubeTextureAssetTask,AssetsManager,SceneSerializer,ReflectionProbe,Layer,TextureTools,FramingBehavior,BouncingBehavior,AutoRotationBehavior,EngineInstrumentation,SceneInstrumentation,_TimeToken,BackgroundMaterial,EnvironmentHelper,GridMaterial,GLTFFileLoader };